diff --git "a/agents/data_analysis.py" "b/agents/data_analysis.py" new file mode 100644 --- /dev/null +++ "b/agents/data_analysis.py" @@ -0,0 +1,2685 @@ +""" +data_analysis.py — smolagents manager + `data_worker` sub-agent for the +Data Analysis tab (the same orchestration shape as rag_agent.py and +deep_research_agent.py). + +NOTE — matplotlib backend safety: the `data_worker` sandbox may execute +raw model-written matplotlib code (the curated `save_chart` tool forces +Agg itself, but the model can bypass it with hand-written plt.savefig). +The app's splash screen owns a tkinter Tk root on the MAIN thread; if +pyplot auto-selected TkAgg in the worker thread, the Tk objects created +and garbage-collected there would abort the whole process with +`Tcl_AsyncDelete: async handler deleted by the wrong thread` (exit +0x80000003). The MPLBACKEND env var forces the non-GUI Agg backend +process-wide — set it here too so the guard holds even when the app is +entered through a path that skips run_webview.py / app.py. + +Architecture (manager / sub-agent): * MANAGER (`data_worker` is the ONLY thing it can call) — a CodeAgent + that ANALYZES the user's data question (totals, breakdowns, charts, + payroll, cleaning…), decomposes it into focused sub-tasks and + delegates each one to the `data_worker` sub-agent via plain Python + expressions (`data_worker(task='...')`, which the executor resolves + to the managed agent), then SYNTHESIZES the full Markdown report from + the worker's findings. It never touches the data itself. It is a + CodeAgent rather than a ToolCallingAgent because this tab's verified + models (small GGUFs) are reliable on the app's forgiving code grammar + — see _build_manager_agent's docstring for the end-to-end evidence. + * SUB-AGENT (`data_worker`) — a plain CodeAgent (Python execution is its + whole point — ToolCallingAgent has no Python executor) holding + ONLY the curated data tools (`list_columns`, `aggregate`, + `summarize_numeric`, `save_chart`, `complete_missing_data`, + `install_package`). Given ONE + focused sub-task per call (it has no memory of other calls), it loads + the data file, runs the tools / pandas / matplotlib, and returns its + findings (the tool outputs transcribed VERBATIM — a transcription + validator enforces this) for the manager to write the final report + from. + +This replaces the older single-agent design (one CodeAgent holding every +tool and doing the whole EDA itself). Splitting the work mirrors the +proven RAG / Deep Research pattern: each worker call has a FOCUSED task +with far less context than the whole EDA instruction block, and the +manager's context accumulates the workers' findings instead of one huge +monolithic run. The curated tools' file-path contract and the exact- +column-name rule are unchanged — they live on the worker, which is the +only agent that touches the data. + +The full Markdown report is returned as the manager's final answer (never +auto-saved to disk — the user exports it to Word on demand via the +💾 Save Report button). The worker can install any missing Python packages +itself via the `install_package` tool, and can COMPLETE blank (empty) +columns (e.g. កាត់ពន្ធ / tax or ប្រាក់ខែសុទ្ធ (USD) / net salary) when +their values are derivable from the other columns viathe `complete_missing_data` tool. +""" + +import os + +# Matplotlib backend safety — see the module docstring: the worker sandbox +# may run raw model-written pyplot code, and the tkinter splash must never +# make matplotlib auto-select TkAgg in the worker thread (Tcl_AsyncDelete +# would abort the process). Force the non-GUI Agg backend app-wide. +os.environ.setdefault("MPLBACKEND", "Agg") + +import datetime +import html +import os +import re +import shutil +import subprocess +import sys +import threading +import time +import types +from pathlib import Path +from typing import Optional + +from smolagents import tool + +from agents.agent_factory import build_smol_agent +from agents import agent_memory +from agents import agent_streaming +from backend import model_registry as mr +from backend import models +from backend.hardware import DEVICE +from backend.knowledge_base import get_file_path +from ui import i18n + +_data_agent = None +_data_worker = None +_data_agent_model_id = None +_data_agent_max_steps = None +_data_agent_worker_max_steps = None +_data_agent_execution_timeout = None +_data_agent_n_ctx = None +_data_agent_files = () +_data_agent_lock = threading.Lock() + +# How many conversation turns the Data Analysis MANAGER is allowed to +# remember (see agent_memory.cap_agent_memory()). Kept smaller than the +# other tabs' default of 6 because each turn's task prompt here is already +# long (the full analysis instructions in build_data_task() below), so +# memory grows the prompt much faster per turn than a one-line chat +# question would. +DATA_AGENT_MEMORY_TURNS = 3 + +# Tracks which uploaded file paths the manager's current memory "belongs +# to". A new/changed set of files means a different dataset, so old +# memory (which may reference the previous file's columns/stats) needs to +# be dropped even though the model itself hasn't changed — see +# agent_memory.reset_if_context_changed(). +_last_data_context = {"key": None} + + +_SAFE_PACKAGE_NAME_RE = re.compile(r"^[a-zA-Z0-9_-]+(==[0-9.]+[a-zA-Z0-9]*)?$") + + +@tool +def install_package(package_name: str) -> str: + """ + Install a Python package into the current environment using pip. + Use this whenever a data-analysis step needs a library that is not + yet installed (e.g. "openpyxl" for reading .xlsx files, "seaborn", + "scikit-learn", "statsmodels", "plotly", "xlsxwriter"). + + Args: + package_name: The pip package name to install, e.g. "seaborn" or + "scikit-learn==1.4.0". Pass a single package per call. + """ + pkg = str(package_name or "").strip() + if not pkg or not _SAFE_PACKAGE_NAME_RE.match(pkg) or pkg.startswith("-") or "/" in pkg or "\\" in pkg: + return ( + f"❌ Rejected package name '{package_name}': invalid format. " + "Only standard PyPI package names (e.g. 'openpyxl', 'seaborn==0.13.0') are allowed." + ) + + try: + from backend.hardware import _pip_base_args + flags = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0 + cmd = _pip_base_args() + ["--quiet", "--disable-pip-version-check", pkg] + result = subprocess.run( + cmd, + capture_output=True, text=True, timeout=1200, + creationflags=flags, + ) + if result.returncode == 0: + return f"✅ Installed '{pkg}' successfully." + return f"❌ Failed to install '{pkg}':\n{result.stderr[-2000:]}" + except subprocess.TimeoutExpired: + return f"❌ Installing '{pkg}' timed out after 1200s." + except Exception as e: + return f"❌ Error installing '{pkg}': {e}" + + +install_package.input_aliases = { + "package_name": ("package", "name", "pkg", "lib"), +} + + +def _normalize_tool_path(file_path: str) -> str: + """Normalize a model-transcribed file path back to the real Windows path. + Small models (E2B observed end-to-end) sometimes rewrite the uploaded + file's `G:\\user_data\\...` path as a POSIX-style `/G/localailab_svelet/...` + or `/G:/user_data/...` (leading slash + drive letter + forward slashes) — + which Path.is_file() then rejects with 'file not found' and the worker + burns its step budget retrying the same broken path. Convert a + `/X:/...` or `/X/...` drive-letter prefix back to `X:\\...`. Returns the + original when there is nothing to normalize.""" + raw = (file_path or "").strip() + m = re.match(r"^/([A-Za-z]):?/(.*)$", raw, re.DOTALL) + if m: + cand = f"{m.group(1)}:\\{m.group(2)}".replace("/", "\\") + return cand + return raw + + +def _load_dataframe(file_path: str): + """Read a CSV or Excel file into a pandas DataFrame (lazy imports so a + failed load degrades to an informative tool message, never a crash). + + CSVs are read with DELIMITER SNIFFING (sep=None, python engine) so + comma-, tab- and semicolon-separated uploads all work out of the box + (Excel "CSV" exports are frequently tab- or semicolon-delimited, and + real payroll sheets like the user's sample paste are tab-separated), + and the UTF-8 BOM is auto-stripped (Excel-saved CSVs carry it, which + would otherwise corrupt the first column name into '\ufeffEmployee ID').""" + import pandas as pd + + p = Path(_normalize_tool_path(file_path)) + if not p.is_file(): + raise FileNotFoundError(f"file not found: {file_path}") + if p.suffix.lower() in (".xlsx", ".xls"): + try: + return pd.read_excel(p) + except Exception as e: + raise RuntimeError( + f"could not read '{p.name}' (Excel). If 'openpyxl' is missing, call " + f"install_package('openpyxl') first, then retry. Original error: {e}" + ) + return pd.read_csv(p, sep=None, engine="python", encoding="utf-8-sig") + + +def _missing_columns(df, wanted) -> str: + """Return the exact available column list when any `wanted` column is + absent — the mechanical version of the task prompt's KeyError-recovery + rule (never guess/translate a column name). Empty string = all present.""" + cols = list(df.columns) + missing = [c for c in wanted if c not in cols] + if not missing: + return "" + return f"column(s) not found: {missing}. Available columns: {cols}" + + +def _run_with_timeout(fn, args=(), kwargs=None, timeout_seconds: float = 60.0): + """Execute a function in a thread with a hard timeout to prevent slow file IO + or complex dataframe operations from hanging indefinitely.""" + if kwargs is None: + kwargs = {} + res = [None] + err = [None] + + def _worker(): + try: + res[0] = fn(*args, **kwargs) + except Exception as e: + err[0] = e + + t = threading.Thread(target=_worker, daemon=True) + t.start() + t.join(timeout_seconds) + if t.is_alive(): + return f"❌ Operation timed out after {int(timeout_seconds)}s." + if err[0] is not None: + raise err[0] + return res[0] + + +@tool +def list_columns(file_path: str) -> str: + """Get the EXACT column names, data types and a sample of the uploaded + data file. + + ALWAYS call this first after loading your data, and copy the column + names it returns VERBATIM into your code — they may be in Khmer or any + language and are never translated, renamed or guessed. + + Args: + file_path: Absolute path to the uploaded data file (.csv or .xlsx). + """ + def _impl(): + df = _load_dataframe(file_path) + lines = ["Columns (exact names, use verbatim):"] + for c in df.columns: + lines.append(f" - {c} ({df[c].dtype})") + lines.append("\nFirst 3 rows:\n" + df.head(3).to_string()) + return "\n".join(lines) + + try: + return _run_with_timeout(_impl, timeout_seconds=60.0) + except Exception as e: + return f"❌ list_columns failed: {e}" + + +list_columns.input_aliases = { + "file_path": ("filepath", "file", "path", "filename", "data_path", "source"), +} + + +@tool +def aggregate(file_path: str, group_col: str, value_col: str, agg: str = "sum") -> str: + """Aggregate a numeric column grouped by a categorical column and return a + Markdown table with the computed values. + + Prefer this over writing groupby code yourself — it verifies that BOTH + column names exist exactly as you passed them, so a wrong (translated or + guessed) name returns the real column list instead of a KeyError. + + Args: + file_path: Absolute path to the loaded data file (.csv or .xlsx). + group_col: The EXACT name of the grouping column (e.g. 'ផលិតផល'), + or '' / empty to get the OVERALL aggregate with no grouping. + value_col: The EXACT name of the numeric column to aggregate + (e.g. 'សរុប (USD)'). + agg: Aggregation function — 'sum', 'mean', 'count', 'min' or 'max'. + """ + def _impl(): + df = _load_dataframe(file_path) + if agg not in ("sum", "mean", "count", "min", "max"): + return f"❌ Unsupported agg '{agg}'. Use one of: sum, mean, count, min, max." + missing = _missing_columns(df, [value_col] + ([group_col] if group_col.strip() else [])) + if missing: + return f"❌ aggregate failed: {missing}" + if agg != "count": + df = df.copy() + df[value_col] = df[value_col].map(_to_number) + if not group_col.strip(): + value = float(df[value_col].agg(agg)) + return ( + f"| {value_col} ({agg}) |\n|---|\n| {value:.4g} |\n\n" + f"**{agg.title()} {value_col} = {value:.4g}**" + ) + grouped = df.groupby(group_col)[value_col].agg(agg).reset_index() + rows = "\n".join( + f"| {row[group_col]} | {row[value_col]:.4g} |" + for _, row in grouped.iterrows() + ) + total = f"**{agg.title()} {value_col} = {grouped[value_col].sum():.4g}**" + return f"| {group_col} | {value_col} ({agg}) |\n|---|---|\n{rows}\n\n{total}" + + try: + return _run_with_timeout(_impl, timeout_seconds=60.0) + except Exception as e: + return f"❌ aggregate failed: {e}" + + +aggregate.input_aliases = { + "file_path": ("filepath", "file", "path", "filename", "data_path", "source"), + "group_col": ("group_by", "groupby", "by", "category", "category_col", "column"), + "value_col": ("target_col", "metric_col", "num_col", "val_col", "value", "column_name"), + "agg": ("aggregation", "agg_func", "function", "method", "op"), +} + + +@tool +def summarize_numeric(file_path: str, value_col: str) -> str: + """Summary statistics for one numeric column: count, mean, std, min, + quartiles and max. + + Prefer this over writing describe code yourself — the column name is + verified exactly as you pass it. + + Args: + file_path: Absolute path to the loaded data file (.csv or .xlsx). + value_col: The EXACT name of the numeric column to summarise + (e.g. 'បរិមាណ'). + """ + def _impl(): + import numpy as np + import pandas as pd + + df = _load_dataframe(file_path) + missing = _missing_columns(df, [value_col]) + if missing: + return f"❌ summarize_numeric failed: {missing}" + s = df[value_col] + if not pd.api.types.is_numeric_dtype(s): + coerced = s.map(_to_number) + if coerced.notna().any() and coerced.notna().all(): + s = coerced + else: + return f"❌ Column '{value_col}' is not numeric (dtype {s.dtype})." + clean = s.dropna() + q1, q2, q3 = clean.quantile([0.25, 0.5, 0.75]) + out = { + "count": int(clean.count()), + "mean": round(float(clean.mean()), 4), + "std": round(float(clean.std()), 4), + "min": round(float(clean.min()), 4), + "25%": round(float(q1), 4), + "50% (median)": round(float(q2), 4), + "75%": round(float(q3), 4), + "max": round(float(clean.max()), 4), + "sum": round(float(clean.sum()), 4), + } + return "\n".join(f" - {k}: {v}" for k, v in out.items()) + + try: + return _run_with_timeout(_impl, timeout_seconds=60.0) + except Exception as e: + return f"❌ summarize_numeric failed: {e}" + + +summarize_numeric.input_aliases = { + "file_path": ("filepath", "file", "path", "filename", "data_path", "source"), + "value_col": ("target_col", "metric_col", "num_col", "val_col", "value", "column", "column_name"), +} + + +# ── Professional chart rendering ──────────────────────────────────────── +# save_chart applies a clean, consistent look instead of matplotlib's bare +# defaults (no grid, default colors, 100 DPI): white canvas, light dashed +# grid, clean spines, a coherent palette, compact tick formatting, bar value +# labels and a high 150 DPI so charts stay crisp on HiDPI screens. It also +# registers a Khmer-capable font — DejaVu Sans has NO Khmer glyphs, so Khmer +# column names / titles used to render as empty boxes (the "Glyph ... missing +# from font(s) DejaVu Sans" warnings). The font probe is cached: the +# font-manager scan is once per process, and machines without any Khmer font +# degrade to DejaVu's boxed behaviour — never a crash. + +_KHMER_FONT_CACHE = None # None = not probed yet; then a family name or None + +_KHMER_FONT_FAMILIES = ( + "Noto Sans Khmer", "Khmer OS", "Leelawadee UI", + "DaunPenh", "MoolBoran", "Khmer UI", +) + + +def _khmer_font_family(): + """Find a Khmer-capable font family for matplotlib so Khmer axis labels / + titles render instead of missing-glyph boxes. Returns the family name to + put FIRST in font.family, or None when no Khmer font exists on this + machine (charts then degrade to DejaVu's boxed behaviour). Never raises. + Cached after the first probe.""" + global _KHMER_FONT_CACHE + if _KHMER_FONT_CACHE is not None: + return _KHMER_FONT_CACHE + family = None + try: + from matplotlib import font_manager + + # Already registered (matplotlib found a system/user Khmer font itself). + known = {f.name for f in font_manager.fontManager.ttflist} + for fam in _KHMER_FONT_FAMILIES: + if fam in known: + family = fam + break + if family is None: + # Register a font file from the well-known Windows locations. + local = os.environ.get("LOCALAPPDATA", "") + windir = os.environ.get("WINDIR", r"C:\Windows") + candidates = [ + os.path.join(local, "Microsoft", "Windows", "Fonts", "NotoSansKhmer-Regular.ttf"), + os.path.join(local, "Microsoft", "Windows", "Fonts", "NotoSansKhmerUI-Regular.ttf"), + os.path.join(windir, "Fonts", "LeelawadeeUI.ttf"), + os.path.join(windir, "Fonts", "khmerui.ttf"), + os.path.join(windir, "Fonts", "daunpenh.ttf"), + os.path.join(windir, "Fonts", "moolbor.ttf"), + os.path.join(windir, "Fonts", "KhmerOS.ttf"), + ] + for p in candidates: + if not (p and os.path.isfile(p)): + continue + try: + font_manager.fontManager.addfont(p) + family = font_manager.FontProperties(fname=p).get_name() + break + except Exception: + continue + except Exception: + family = None + _KHMER_FONT_CACHE = family + return family + + +# A professional categorical palette (terracotta accent first, then a muted +# blue/gold/violet set) — charts read like the app, not like a default +# matplotlib rainbow. +_CHART_PALETTE = ("#d97757", "#4e79a7", "#59a14f", "#edc948", "#b07aa1", "#f28e2b") + + +def _apply_chart_style(khmer_family): + """The shared professional look every save_chart plot gets: white canvas, + light dashed grid, clean spines, muted axis text, the coherent palette. + `khmer_family` (or None) goes first in font.family so Khmer renders; the + font list keeps DejaVu Sans as the always-present fallback.""" + import matplotlib as mpl + + families = [khmer_family] if khmer_family else [] + families.append("DejaVu Sans") + mpl.rcParams.update({ + "font.family": families, + "font.size": 11, + "figure.facecolor": "white", + "axes.facecolor": "white", + "axes.edgecolor": "#d8d2c6", + "axes.grid": True, + "grid.color": "#e9e3d8", + "grid.linewidth": 0.8, + "grid.linestyle": "--", + "axes.spines.top": False, + "axes.spines.right": False, + "axes.spines.left": True, + "axes.spines.bottom": True, + "axes.titleweight": "bold", + "axes.titlesize": 14, + "axes.titlecolor": "#333333", + "axes.labelcolor": "#4a4a4a", + "axes.labelsize": 11.5, + "xtick.color": "#666666", + "ytick.color": "#666666", + "xtick.labelsize": 10.5, + "ytick.labelsize": 10.5, + "legend.frameon": False, + "legend.fontsize": 10.5, + }) + + +def _fmt_num(v): + """Compact professional number formatting for chart ticks/labels: comma + thousands (1,250,000), 1.2M for millions, whole numbers without a + trailing .0. Never raises on non-numeric input.""" + try: + v = float(v) + except (TypeError, ValueError): + return str(v) + if abs(v) >= 1_000_000: + return (f"{v / 1_000_000:.1f}M").replace(".0M", "M") + if abs(v) >= 1_000: + return f"{v:,.0f}" + if v == int(v): + return str(int(v)) + return f"{v:,.2f}".rstrip("0").rstrip(".") + + +_active_data_report_dir: Optional[Path] = None + + +def get_active_report_dir() -> Optional[Path]: + """Return the active timestamped report folder for the current Data Analysis run, + or None if no run has set one.""" + global _active_data_report_dir + return _active_data_report_dir + + +def set_active_report_dir(p: Optional[Path]) -> None: + """Set or clear the active timestamped report folder.""" + global _active_data_report_dir + _active_data_report_dir = Path(p) if p else None + + +def _maybe_rotate_xticks(ax, series, max_ticks=8): + """Rotate crowded category labels (many x values) so they don't overlap.""" + if len(series) > max_ticks: + ax.tick_params(axis="x", rotation=45) + + +@tool +def save_chart(file_path: str, chart_type: str, x_col: str, y_col: str = "", title: str = "") -> str: + """Create a chart from the data, save it as a PNG and return its filename. + + Use this for ALL charts — it produces a deterministic, valid image every + time, so you never need to write matplotlib code yourself. The filename it + returns is what you reference in your report. + + Args: + file_path: Absolute path to the loaded data file (.csv or .xlsx). + chart_type: 'line', 'bar', 'pie', 'hist' or 'scatter'. + x_col: For line/bar — the EXACT X axis column (e.g. 'កាលបរិច្ឆេទ'); + for pie — the EXACT category column to group by; for hist — the + EXACT numeric column to plot; for scatter — the EXACT X column. + y_col: The EXACT numeric column for the Y axis (line/bar/scatter) or + the EXACT numeric values for the pie slices. Ignored for hist. + title: Optional chart title. + """ + def _impl(): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.ticker import FuncFormatter + + # Professional style + Khmer-capable font (cached probe; charts on + # machines without a Khmer font degrade gracefully, never crash). + _apply_chart_style(_khmer_font_family()) + fmt = FuncFormatter(lambda v, _pos: _fmt_num(v)) + + df = _load_dataframe(file_path) + wanted = [x_col] + ([y_col] if y_col else []) + missing = _missing_columns(df, wanted) + if missing: + return f"❌ save_chart failed: {missing}" + if chart_type not in ("line", "bar", "pie", "hist", "scatter"): + return f"❌ Unsupported chart_type '{chart_type}'. Use: line, bar, pie, hist, scatter." + + fig, ax = plt.subplots(figsize=(9, 5.2), dpi=150) + if chart_type == "line": + series = df.groupby(x_col)[y_col].sum().sort_index() + ax.plot(series.index.astype(str), series.values, marker="o", + linewidth=2.5, markersize=5, color=_CHART_PALETTE[0]) + ax.set_xlabel(str(x_col)) + ax.set_ylabel(str(y_col)) + ax.yaxis.set_major_formatter(fmt) + _maybe_rotate_xticks(ax, series) + elif chart_type == "bar": + series = df.groupby(x_col)[y_col].sum().sort_values(ascending=False) + bars = ax.bar(series.index.astype(str), series.values, + color=_CHART_PALETTE[0], width=0.65) + ax.set_xlabel(str(x_col)) + ax.set_ylabel(str(y_col)) + ax.yaxis.set_major_formatter(fmt) + ax.bar_label(bars, fmt=_fmt_num, fontsize=9, padding=2) + ax.margins(y=0.12) + _maybe_rotate_xticks(ax, series) + elif chart_type == "pie": + series = df.groupby(x_col)[y_col].sum() + colors = [_CHART_PALETTE[i % len(_CHART_PALETTE)] for i in range(len(series))] + ax.pie(series.values, labels=series.index.astype(str), autopct="%1.1f%%", + startangle=90, counterclock=False, colors=colors, + wedgeprops={"edgecolor": "white", "linewidth": 1.5}) + ax.set_ylabel("") + elif chart_type == "hist": + ax.hist(df[x_col].dropna(), bins=min(20, int(df[x_col].nunique()) or 1), + color=_CHART_PALETTE[1], edgecolor="white", linewidth=0.8) + ax.set_xlabel(str(x_col)) + ax.set_ylabel("Count") + ax.xaxis.set_major_formatter(fmt) + elif chart_type == "scatter": + ax.scatter(df[x_col], df[y_col], color=_CHART_PALETTE[0], + alpha=0.75, s=42, edgecolor="white", linewidth=0.6) + ax.set_xlabel(str(x_col)) + ax.set_ylabel(str(y_col)) + ax.xaxis.set_major_formatter(fmt) + ax.yaxis.set_major_formatter(fmt) + ax.set_title(title or f"{y_col or x_col} by {x_col}", + fontsize=14, fontweight="bold", pad=12) + fig.tight_layout() + + out_dir = get_active_report_dir() or Path(mr.DATA_OUTPUT_DIR) + out_dir.mkdir(parents=True, exist_ok=True) + stem = title.replace(" ", "_")[:40] if title else f"{chart_type}_{x_col}_{y_col or x_col}" + stem = "".join(c for c in stem if c.isalnum() or c in ("-", "_")).strip("_") or chart_type + name = f"{stem}.png" + # High DPI (150) keeps the chart crisp on HiDPI screens; the white + # facecolor guarantees the image is legible in dark mode too. + fig.savefig(out_dir / name, dpi=150, bbox_inches="tight", facecolor="white") + # Keep DATA_OUTPUT_DIR in sync as fallback + fallback_dir = Path(mr.DATA_OUTPUT_DIR) + fallback_dir.mkdir(parents=True, exist_ok=True) + if out_dir.resolve() != fallback_dir.resolve(): + try: + shutil.copy2(out_dir / name, fallback_dir / name) + except OSError: + pass + plt.close(fig) + return f"✅ Chart saved as: {name}" + + try: + return _run_with_timeout(_impl, timeout_seconds=60.0) + except Exception as e: + return f"❌ save_chart failed: {e}" + + +save_chart.input_aliases = { + "file_path": ("filepath", "file", "path", "filename", "data_path", "source"), + "chart_type": ("type", "kind", "plot_type"), + "x_col": ("x", "x_axis", "category_col", "column_x"), + "y_col": ("y", "y_axis", "value_col", "metric_col", "column_y"), + "title": ("chart_title", "name", "heading"), +} + + +# ────────────────────────────────────────────────────────────────── +# Missing-data completion ("complete the missing data") +# ────────────────────────────────────────────────────────────────── +# A GENERAL missing-data completion tool for ANY dataset / file type +# (.csv — comma/tab/semicolon — and .xlsx): when a file leaves cells or +# columns blank, the worker can COMPLETE them from the rest of the data — +# an explicit rule (rules={'កាត់ពន្ធ': '...'}), a relation auto-derived +# from the column names (payroll: net = base + bonus − tax; generic: +# quantity × unit price = total — the latter validated against the +# column's known values), or the standard statistical treatment (mean / +# mode of the observed values for partially-blank columns). The tool +# NEVER invents numbers: only cells whose value is computed from real +# source values (or honestly estimated from observed ones, clearly +# labeled) are filled, and blank columns that cannot be completed are +# reported honestly instead of guessed. + +_KHMER_DIGITS = str.maketrans("០១២៣៤៥៦៧៨៩", "0123456789") + + +def _to_number(v): + """Coerce one cell to a float — tolerating the two formatting + corruptions real uploads carry: thousands separators ('1,100.00') and + Khmer digits ('២២'). Returns None for anything non-numeric (blank + cells included).""" + import math + + if v is None: + return None + if isinstance(v, float) and math.isnan(v): + return None + s = str(v).strip().translate(_KHMER_DIGITS).replace(",", "").replace(" ", "") + if not s: + return None + try: + return float(s) + except ValueError: + return None + + +def _blank_mask(series): + """True per row when the cell is blank: NaN/None OR an empty/whitespace + string. pandas reads an entirely-blank CSV column as NaN floats, but a + partially-blank column can come through as object dtype with ''.""" + import pandas as pd + + blank = pd.isna(series) + blank |= series.astype("object").astype(str).str.strip().isin(["", "nan", "None"]) + return blank + + +def _fmt_cell(v) -> str: + """Display one cell: '' for blank, a tidy number (990 → '990', 995.55 + → '995.55') for numeric values, else the raw string.""" + import pandas as pd + + n = _to_number(v) + if n is None: + return "" if _blank_mask(pd.Series([v])).iloc[0] else str(v) + s = f"{round(n, 2):.2f}".rstrip("0").rstrip(".") + return s if s else "0" + + +def _norm_col_name(name: str) -> str: + """Column-name fingerprint for payroll-role detection: lowercase, + separators/punctuation stripped, but ALL MARK CHARACTERS KEPT (Mn + nonspacing — the coeng U+17D2 — AND Mc spacing marks ��� the Khmer vowel + signs U+17B6..U+17C6 like ោ) — so 'ប្រាក់ខែសុទ្ធ (USD)' and 'Net + Salary' both fingerprint cleanly and match by substring. Stripping the + marks (e.g. only isalnum(), which drops both mark classes) corrupts the + Khmer tokens so 'សុទ្ធ' / 'គោល' never match their own fingerprints — + the silent roles={} bug this fixes (observed: unicodedata.combining() + alone still dropped the Mc vowel signs, leaving 'គល' for 'គោល').""" + import unicodedata + + return "".join( + ch for ch in str(name).lower() + if ch.isalpha() or unicodedata.category(ch) in ("Mn", "Mc", "Me") + ) + + +def _classify_columns(df) -> dict: + """Map the dataframe's columns to ROLES by name (Khmer + English): the + payroll roles (base / bonus / tax / net / gross) plus the generic + derived-column roles (qty, unit_price, total) — so the completion tool + understands ANY dataset, not just payroll sheets. Detection is + substring-based on the fingerprint, so partially translated headers + still match. Role branches are ordered so a payroll column is never + misread as a generic one (e.g. ប្រាក់ខែសុទ្ធ → net, not total; the + hours / position / ID columns match nothing).""" + roles = {} + for col in df.columns: + n = _norm_col_name(col) + if "សុទ្ធ" in n or "net" in n: + roles.setdefault("net", col) + elif "កាត់ពន្ធ" in n or "tax" in n or "deduct" in n: + roles.setdefault("tax", col) + elif "គោល" in n or "base" in n: + roles.setdefault("base", col) + elif "បន្ថែម" in n or "bonus" in n or "allowance" in n or "overtime" in n: + roles.setdefault("bonus", col) + elif "gross" in n or ("សរុប" in n and "ប្រាក់ខែ" in n): + roles.setdefault("gross", col) + elif "បរិមាណ" in n or "quantity" in n or "qty" in n or "units" in n: + roles.setdefault("qty", col) + elif "តម្លៃ" in n or "unit price" in n or "price" in n or "rate" in n: + roles.setdefault("unit_price", col) + elif "សរុប" in n or "total" in n or "revenue" in n or "sum" in n or "ចំណូល" in n: + roles.setdefault("total", col) + return roles + + +def _has_values(df, col) -> bool: + """True when the column has at least one non-blank cell — a formula + whose source column is entirely blank could never compute anything.""" + return bool((~_blank_mask(df[col])).any()) + + +def _payroll_role_aliases(df) -> dict: + """Canonical payroll-role aliases → the EXACT column name, keyed by + fingerprint: 'tax' → 'កាត់ពន្ធ', 'net salary'/'net' → 'ប្រាក់ខែសុទ្ធ + (USD)', 'base salary' → 'ប្រាក់ខែគោល (USD)', … Built from the + detected roles so a model writing completion rules with TRANSLATED + names still works — the observed E2B failure: the worker passed + rules={'tax': '…'} against a កាត់ពន្ធ column and the tool refused with + 'Rule column tax not found' instead of completing the payroll.""" + roles = _classify_columns(df) + aliases = {} + for role, col in roles.items(): + aliases[_norm_col_name(role)] = col + for token, role in (("base salary", "base"), ("gross salary", "gross"), + ("net salary", "net"), ("take home", "net"), + ("allowance", "bonus"), ("deduction", "tax"), + ("tax deduction", "tax")): + if roles.get(role): + aliases[_norm_col_name(token)] = roles[role] + return aliases + + +def _resolve_rule_column(df, aliases, key) -> Optional[str]: + """Map a completion-rule target name to the EXACT column name: exact + match first, then a payroll-role alias ('tax' → 'កាត់ពន្ធ'), then a + fingerprint match (case / space / paren-insensitive). None when nothing + matches — the caller reports the real column list.""" + if key in df.columns: + return key + fp = _norm_col_name(key) + if not fp: + return None + if fp in aliases: + return aliases[fp] + for col in df.columns: + if _norm_col_name(col) == fp or fp in _norm_col_name(col): + return col + return None + + +def _substitute_formula_aliases(df, aliases, formula) -> str: + """Rewrite a completion-rule formula so every payroll-role alias is + replaced by the EXACT column name (the model's '… - tax' becomes + '… - កាត់ពន្ធ') before evaluation. Exact column names are protected by + substituting longest-first (an exact name never gets partially + rewritten by a shorter alias inside it).""" + subs = {str(col): str(col) for col in df.columns} + for alias, col in aliases.items(): + subs[alias] = col + expr = str(formula) + for name in sorted(subs, key=len, reverse=True): + expr = expr.replace(name, subs[name]) + return expr + + +def _auto_payroll_rules(df) -> list: + """Auto-derived completion rules from the detected payroll column + roles: a list of (target_column, formula, description) tried in order. + Only targets columns that still have blank cells, and only when every + source column the formula needs actually HAS values (so the user's + both-columns-blank payroll sheet is honestly reported as underivable + rather than filled with NaN or guessed numbers).""" + roles = _classify_columns(df) + blank = {c for c in df.columns if _blank_mask(df[c]).any()} + rules = [] + + def sources_have_values(*names) -> bool: + return all(roles.get(n) and _has_values(df, roles[n]) for n in names) + + if roles.get("net") in blank and sources_have_values("base", "bonus", "tax"): + rules.append((roles["net"], + f"{roles['base']} + {roles['bonus']} - {roles['tax']}", + "net = base + bonus − tax")) + if roles.get("tax") in blank and sources_have_values("base", "bonus", "net"): + rules.append((roles["tax"], + f"{roles['base']} + {roles['bonus']} - {roles['net']}", + "tax = base + bonus − net")) + if roles.get("net") in blank and sources_have_values("gross", "tax"): + rules.append((roles["net"], + f"{roles['gross']} - {roles['tax']}", + "net = gross − tax")) + if roles.get("gross") in blank and sources_have_values("base", "bonus"): + rules.append((roles["gross"], + f"{roles['base']} + {roles['bonus']}", + "gross = base + bonus")) + if roles.get("tax") in blank and sources_have_values("gross", "net"): + rules.append((roles["tax"], + f"{roles['gross']} - {roles['net']}", + "tax = gross − net")) + return rules + + +def _validate_formula_against_known(df, col, result, tolerance: float = 0.01) -> bool: + """The general-tool SAFETY GATE: does a proposed derivation reproduce + the column's KNOWN (non-blank) values? A formula is only allowed to + fill the blank cells when it matches reality on EVERY observed row + (within a small absolute+relative tolerance for money rounding). A + wrong guess — e.g. 'sum of the other numeric columns' against a + quantity×price Total — fails against the known totals and is never + applied, so blanks can never be filled with fabricated numbers.""" + known = ~_blank_mask(df[col]) + result_num = result.map(_to_number) + known_num = df[col].map(_to_number) + ok = known & result_num.notna() & known_num.notna() + if not ok.any(): + return False # nothing observed to validate against + diff = (result_num[ok] - known_num[ok]).abs() + scale = known_num[ok].abs() + return bool((diff <= tolerance + tolerance * scale).all()) + + +def _auto_generic_rules(df, roles=None) -> list: + """Auto-derived completion rules for ANY dataset, beyond payroll: + generic derived totals recognized from the column names — quantity × + unit price = total (the classic e-commerce/invoice relation), or sum of + the other numeric columns as a fallback — each applied ONLY when it + reproduces the column's known values (see + _validate_formula_against_known), so a misidentified relation can + never fill blanks with invented numbers. Returns (target, formula, + description) tuples, tried in order.""" + import pandas as pd + + roles = roles if roles is not None else _classify_columns(df) + blank = {c for c in df.columns if _blank_mask(df[c]).any()} + rules = [] + total_col = roles.get("total") + if total_col in blank: + qty_col, price_col = roles.get("qty"), roles.get("unit_price") + if qty_col and price_col and _has_values(df, qty_col) and _has_values(df, price_col): + formula = f"{qty_col} * {price_col}" + result, err = _apply_formula(df, formula) + if not err and _validate_formula_against_known(df, total_col, result): + rules.append((total_col, formula, "total = quantity × unit price")) + # Fallback: total = sum of the OTHER numeric columns — only when it + # matches the known totals (so it can never misfire on a + # multiplicative total like qty×price). + numeric = [ + c for c in df.columns + if c != total_col and ( + pd.api.types.is_numeric_dtype(df[c]) + or df[c].map(_to_number).notna().all() + ) + ] + if len(numeric) >= 2: + formula = " + ".join(numeric) + result, err = _apply_formula(df, formula) + if not err and _validate_formula_against_known(df, total_col, result): + rules.append((total_col, formula, + "total = sum of the other numeric columns")) + return rules + + +def _impute_columns(df, blank_cols, changed, lines, filled) -> None: + """Statistical estimation for partially-blank columns — the standard + missing-data treatment that works on ANY dataset: numeric columns are + completed with the MEAN of the observed values, categorical columns + with the MOST COMMON value (mode). Fully-blank columns (no observed + values) are never imputed — there is no basis, and the tool reports + them honestly instead. Imputed cells are clearly labeled as estimates.""" + import pandas as pd + + for col in blank_cols: + if col in filled: + continue + observed = df[col][~_blank_mask(df[col])] + if len(observed) == 0: + continue # fully blank — no basis to estimate + mask = _blank_mask(df[col]) + n = int(mask.sum()) + if n == 0: + continue + coerced = observed.map(_to_number) + if coerced.notna().all(): + mean = float(coerced.mean()) + df.loc[mask, col] = round(mean, 2) + changed |= mask + filled[col] = "statistical estimate" + lines.append( + f"ℹ️ Column '{col}': estimated {n} blank cell(s) as the mean " + f"({mean:.4g}) of the {len(observed)} observed values." + ) + else: + mode_val = observed.mode() + if len(mode_val) == 0: + continue + mode_val = mode_val.iloc[0] + df.loc[mask, col] = mode_val + changed |= mask + filled[col] = "statistical estimate" + lines.append( + f"ℹ️ Column '{col}': estimated {n} blank cell(s) as the most " + f"common value ('{mode_val}') of the {len(observed)} observed " + f"values." + ) + + +def _apply_formula(df, formula): + """Evaluate a per-row formula written with the EXACT column names over + the dataframe (referenced source cells coerced to numbers — commas and + Khmer digits tolerated). Returns (Series, None) on success or + (None, error_msg); the error carries the real cause so the model can + fix the formula instead of guessing.""" + import pandas as pd + + expr = str(formula).replace("×", "*").replace("−", "-").replace("÷", "/") + locals_ = {} + # Longest-first replacement so a column whose name is a PREFIX of + # another (e.g. 'ឈ្មោះ' vs 'ឈ្មោះហាង') can't corrupt the longer one. + for i, col in enumerate(sorted(df.columns, key=lambda c: -len(str(c)))): + token = f"col_{i}" + expr = expr.replace(str(col), token) + locals_[token] = df[col].map(_to_number) + try: + result = pd.eval(expr, local_dict=locals_) + except Exception as e: + return None, f"could not evaluate the formula '{formula}': {e}" + if isinstance(result, pd.Series) and len(result) == len(df): + return result.map(_to_number), None + return None, f"the formula '{formula}' did not produce one value per row" + + +def _fill_blanks(df, col, result) -> int: + """Fill the blank cells of `col` with the computed values where the + formula produced a real number (rounding money to 2 decimals). Returns + the number of cells filled.""" + mask = _blank_mask(df[col]) & result.notna() + n = int(mask.sum()) + if n: + df.loc[mask, col] = result[mask].round(2) + return n + + +def _completion_table(df, changed_rows) -> str: + """Markdown table of the rows where at least one blank cell was filled, + showing the WHOLE row so the completed values read in context. Capped at + 25 rows — the findings text the manager reads must stay compact.""" + if not changed_rows.any(): + return "" + sub = df.loc[changed_rows].head(25) + cols = list(sub.columns) + lines = ["| " + " | ".join(str(c) for c in cols) + " |", + "|" + "---|" * len(cols)] + for _, row in sub.iterrows(): + lines.append("| " + " | ".join(_fmt_cell(v) for v in row) + " |") + total = int(changed_rows.sum()) + if total > 25: + lines.append(f"… showing the first 25 of {total} completed rows") + return "\n".join(lines) + + +@tool +def complete_missing_data(file_path: str, rules: Optional[dict] = None, + impute: bool = True) -> str: + """Detect BLANK (missing/empty) cells and COMPLETE them from the rest + of the data — the general missing-data completion tool that works on + ANY dataset and file type (.csv — comma/tab/semicolon — and .xlsx), + not just payroll sheets. + + Three strategies are applied in order, and each only fills cells it + can honestly compute — nothing is ever invented: + 1. EXPLICIT RULES: rules={'': ''} — applied in dict order, so a later rule can use + values an earlier one just filled (tax before net). English / + Khmer payroll aliases work too ('tax' → កាត់ពន្ធ). + 2. AUTO-DERIVED COLUMNS from the column names: payroll relations + (net = base + bonus − tax, tax = base + bonus − net, gross = base + + bonus, …) AND generic derived totals (quantity × unit price = + total, or the sum of the numeric components) — the generic ones + are applied ONLY when they reproduce the column's KNOWN values + (validated against observed rows), so a wrong guess can never + fill blanks. + 3. STATISTICAL ESTIMATION (impute=True): partially-blank columns + with observed values are completed with the MEAN (numeric) or + the MOST COMMON value (categorical) of those observed values — + the standard missing-data treatment, clearly labeled as + estimates. + + Example for a payroll sheet: + rules={'កាត់ពន្ធ': '(ប្រាក់ខែគោល (USD) + ប្រាក់បន្ថែម) * 0.10', + 'ប្រាក់ខែសុទ្ធ (USD)': 'ប្រាក់ខែគោល (USD) + ប្រាក់បន្ថែម - កាត់ពន្ធ'} + + Fully-blank columns with no observed values and no derivable rule are + reported honestly (never guessed). Numbers tolerate thousands + separators ('1,100.00') and Khmer digits (២២). + + Args: + file_path: Absolute path to the uploaded data file (.csv or .xlsx). + rules: Optional dict {column: formula} of explicit completion + rules. + impute: Whether to statistically estimate partially-blank columns + (default True). + """ + try: + import pandas as pd + + df = _load_dataframe(file_path) + blank_cols = [c for c in df.columns if _blank_mask(df[c]).any()] + if not blank_cols: + return "✅ No missing values found — every column is already complete." + # Strategy 1: explicit rules (in dict order, chained — a later rule + # can use values an earlier one just filled). Rule keys AND + # formulas go through the payroll-role alias resolver: a model + # writing rules={'tax': …} against a កាត់ពន្ធ column (the observed + # E2B failure) is mechanically cured instead of refused. + aliases = _payroll_role_aliases(df) + plan = [] + for raw_col, formula in (rules or {}).items(): + col = _resolve_rule_column(df, aliases, raw_col) + if col is None: + return (f"❌ Rule column '{raw_col}' not found. Available columns: " + f"{list(df.columns)}") + plan.append((col, _substitute_formula_aliases(df, aliases, formula), + f"explicit rule")) + # Strategy 2: auto-derived relations — payroll identities first, + # then the generic validated totals for any other dataset. + plan.extend(_auto_payroll_rules(df)) + plan.extend(_auto_generic_rules(df)) + filled_total = 0 + completed = {} # column -> formula actually used + changed = pd.Series(False, index=df.index) + lines = [] + for col, formula, desc in plan: + result, err = _apply_formula(df, formula) + if err: + lines.append(f"⚠️ Column '{col}': {err}") + continue + before = _blank_mask(df[col]) + n = _fill_blanks(df, col, result) + if n: + filled_total += n + changed |= before & ~_blank_mask(df[col]) + completed[col] = formula + lines.append(f"✅ Column '{col}': filled {n} cell(s) — {desc}: {formula}") + # Strategy 3: statistical estimation of whatever is still partially + # blank (mean / mode of the observed values) — never for + # fully-blank columns. + if impute: + _impute_columns(df, blank_cols, changed, lines, completed) + out = [] + if completed: + out.append(f"✅ complete_missing_data: completed {len(completed)} column(s), " + f"{filled_total} cell(s) filled.") + remaining = [c for c in blank_cols if _blank_mask(df[c]).any()] + if remaining: + out.append( + f"⚠️ {len(remaining)} blank column(s) could not be completed: " + + ", ".join(f"'{c}'" for c in remaining) + + " — no derivable formula and no observed values to estimate " + "from (they are entirely blank). If you know the rule, pass it " + "explicitly, e.g. rules={'កាត់ពន្ធ': '(ប្រាក់ខែគោល (USD) + " + "ប្រាក់បន្ថែម) * 0.10', 'ប្រាក់ខែសុទ្ធ (USD)': 'ប្រាក់ខែគោល " + "(USD) + ប្រាក់បន្ថែម - កាត់ពន្ធ'}." + ) + out.extend(lines) + table = _completion_table(df, changed) + if table: + out.append("\nCompleted rows (values filled / estimated above):\n" + table) + return "\n".join(out) + except Exception as e: + return f"❌ complete_missing_data failed: {e}" + + +# ───────────���────────────────────────────────────────────────────── +# Sub-agent identity (required by smolagents' managed_agents machinery). +# ────────────────────────────────────────────────────────────────── +DATA_WORKER_NAME = "data_worker" +DATA_WORKER_DESCRIPTION = ( + "Runs ONE focused data-analysis sub-task against the user's uploaded " + "data files (load the file, list columns, aggregate/summarize columns, " + "create charts) and returns a concise findings report with the actual " + "numbers and chart filenames. Call with task='' " + "(e.g. data_worker(task='Compute the total of column សរុប (USD)')). It " + "has NO memory of any other call, so every task must be fully " + "self-contained — name the data file(s) and the exact columns to use." +) + +# The `data_worker` sub-agent's step budget for ONE focused sub-task (the +# manager's budget is DATA_AGENT_MAX_STEPS). Scaled down for very large +# models like every other sub-agent (see get_max_steps_for_model). +DATA_WORKER_DEFAULT_MAX_STEPS = 10 + +# How often (in manager steps) the manager stops to re-plan — smolagents' +# own `planning_interval` mechanism, the same one RAG / Deep Research use +# to make a research loop "deep" instead of a single-pass agentic chat. +DATA_MANAGER_PLANNING_INTERVAL = 3 + +# Default per-step Python-execution timeout (seconds) applied when the Data +# tab's "Exec timeout" control is on AUTO. smolagents' own default is 30s, +# which is too tight for the worker's real steps: loading an .xlsx, +# grouping, and rendering a chart can legitimately exceed 30s per step on +# modest hardware (observed end-to-end: "Code execution exceeded the +# maximum execution time of 30 seconds" on a heavy bundled EDA step). The +# footer reports the ACTUAL applied value, so an auto run shows this number. +DATA_EXECUTION_TIMEOUT_DEFAULT = 120 + +# final_answer_checks validator threshold for the manager's report: a +# final answer shorter than this isn't a real data-analysis report. +MIN_FINAL_REPORT_CHARS = 150 + +# ────────────────────────────────────────────────────────────────── +# Manager system instructions (applied once at construction, if this +# smolagents version supports `instructions=`; the per-call task in +# build_data_task() repeats the core rules — belt and braces, the same +# pattern as rag_agent's STRICT_SYSTEM_INSTRUCTIONS / build_strict_task). +# ────────────────────────────────────────────────────────────────── +DATA_MANAGER_INSTRUCTIONS = ( + "You are a data-analysis research manager. You answer the user's data " + "question by DELEGATING the actual work — you never load the data or " + "run Python yourself.\n\n" + "You do NOT have any data tools. The ONLY agent that exists is " + "`data_worker`, which runs the computations for you. There is no " + "list_columns, aggregate, summarize_numeric, save_chart, " + "complete_missing_data, or install_package tool on you — never call " + "anything else.\n" + "Call it from your code block as a plain Python expression, exactly " + "like a tool: worker_result = data_worker(task='...')\n" + "print(worker_result)\n" + "The value it returns is the worker's findings text — read it and " + "include the real numbers from it in your report.\n\n" + "Work like this:\n" + "1. ANALYZE the user's question: what numbers, breakdowns, charts or " + "computations are actually being asked for?\n" + "2. DECOMPOSE it into 1-3 sub-tasks and BUNDLE related computations into " + "as few data_worker calls as possible. Each data_worker call is an " + "expensive fresh worker run, so ONE task can (and should) ask the worker " + "to do several related things together — e.g. 'list the columns, compute " + "the total of column X and column Y, break them down by column Z and by " + "column W, and create a bar chart of X by Z' is a single call, not four. " + "Only split when a sub-task genuinely depends on a previous result.\n" + "3. DELEGATE: call `data_worker` once per sub-task with a fully " + "self-contained task string: name the data file(s) and the EXACT column " + "names to use (e.g. data_worker(task='Compute the total of column " + "សរុប (USD) from the file ...xlsx')). Never invent column names — the " + "worker will list the exact ones; if you are unsure of a column name, " + "delegate a 'list the columns' sub-task first.\n" + "4. RE-CHECK your plan periodically against what the worker actually " + "returned (read its findings from the printed result of each " + "data_worker call): if a finding changes what you still need, adjust " + "instead of blindly finishing the original plan. If a sub-task comes " + "back thin or empty, delegate again with a different angle — never " + "repeat an identical task.\n" + "5. SYNTHESIZE: once you have enough findings, write a well-structured " + "Markdown report using ONLY the numbers and results the `data_worker` " + "actually returned. Include every concrete value (totals, per-group " + "breakdowns, statistics) verbatim from the findings — never estimate, " + "guess, or recompute them yourself, and never write placeholders. " + "Reference each chart by its exact PNG filename the worker reported.\n" + "6. You MUST call `data_worker` at least once — a final answer written " + "without any data_worker call will be REJECTED and sent back to you, so " + "do not describe what you would do; actually delegate the work.\n" + "7. If the system rejects your final answer for formatting or for a " + "missing data_worker call, do NOT start any new worker calls. Keep the " + "same findings, rewrite only the final report so it satisfies the " + "checker, and call `final_answer(...)` again.\n\n" + "TERMINATION REQUIREMENT: you MUST submit your final answer by calling " + "the special `final_answer(report_text)` tool — this is the ONLY way to " + "actually end the task. Simply printing or writing the report as plain " + "text does NOT end the run: without calling `final_answer(...)`, you " + "will be given another step and may end up starting unnecessary new " + "worker calls even though your report was already complete.\n\n" + "The user's actual question is in the Task below — answer THAT, not " + "these instructions. Never repeat, summarize, or reply to the " + "instructions themselves." +) + +# ────────────────────────────────────────────────────────────────── +# Sub-agent system instructions: the exact-column-name rule, tool usage, +# sandbox rules, and the findings-report format the worker must return. +# The data file paths are appended at build time (see +# _build_worker_agent) so the worker always knows what to read without +# relying on the manager remembering to pass them. +# ────────────────────────────────────────────────────────────────── +DATA_WORKER_INSTRUCTIONS = ( + "You are a focused data-analysis worker running inside a local Python " + "sandbox with pandas, matplotlib, and common data-science libraries. " + "The research manager gives you ONE focused sub-task — answer only " + "that task, fully self-contained. You have NO memory of any other call.\n\n" + "★ COLUMN NAMES — ALWAYS USE THE EXACT NAMES FROM THE DATA\n" + " - Column names are EXACTLY as they appear in the file and may be in " + "Khmer or any other language, with spaces/slashes/parentheses (e.g. " + "'បរិមាណ', 'តម្លៃ/ឯកតា (USD)', 'សរុប (USD)', 'កាលបរិច្ឆេទ'). NEVER " + "translate, rename, guess, or invent column names — and never assume " + "English equivalents like 'Quantity', 'Unit Price', 'Date', or " + "'Product'.\n" + " - After loading, ALWAYS run print(df.columns.tolist()) and copy the " + "column names it prints VERBATIM into your code. Access columns with " + "bracket syntax, e.g. df['បរិមាណ'], never df.quantity.\n" + " - If any step raises a KeyError on a column name, STOP guessing — " + "re-print df.columns.tolist(), take the real name, and retry. Do NOT " + "keep using a name the data does not have.\n\n" + "WORKFLOW:\n" + "1. Load the named file with pandas (pd.read_csv for .csv, pd.read_excel " + "for .xlsx/.xls — if a required package like 'openpyxl' is missing, call " + "the install_package tool with its pip name first, then retry the import).\n" + "2. PREFER THE BUILT-IN TOOLS for the operations they cover (they never " + "guess column names and never hit the sandbox's file limits):\n" + " * list_columns(file_path) — exact column names + dtypes + first rows.\n" + " * aggregate(file_path, group_col, value_col, agg) — sum/mean/count/" + "min/max grouped by a column; pass group_col='' for the OVERALL " + "(grand-total) aggregate of the whole column.\n" + " * summarize_numeric(file_path, value_col) — count/mean/std/quartiles/" + "min/max/sum for one numeric column.\n" + " * save_chart(file_path, chart_type, x_col, y_col, title) — line / " + "bar / pie / hist / scatter saved directly into the charts folder; it " + "returns the PNG filename.\n" + " * complete_missing_data(file_path, rules=None, impute=True) — detect " + "and COMPLETE blank (empty) cells in ANY dataset (.csv/.xlsx): explicit " + "rules={{'': ''}} (e.g. a " + "payroll sheet with កាត់ពន្ធ / tax and ប្រាក់ខែសុទ្ធ (USD) / net " + "salary left blank), auto-derived relations from the column names " + "(payroll: net = base + bonus − tax, …; generic: quantity × unit price " + "= total, validated against known rows), and statistical estimation of " + "partially-blank columns (mean for numeric, most common value for " + "categorical). It NEVER invents numbers — every filled cell is computed " + "from real values or clearly labeled as an estimate — and reports " + "honestly which blank cells it could not complete.\n" + " These tools take the FILE PATH as their first argument and return " + "results as text or a ✅ chart confirmation. Hand-written pandas/" + "matplotlib is still allowed for anything the tools don't cover.\n" + "3. Save EVERY chart as a PNG with a descriptive filename (use " + "save_chart, or plt.savefig(...) followed ALWAYS by plt.close(); never " + "call plt.show()).\n" + "4. Do NOT try to write a report or data file — the sandbox blocks raw " + "open()/write(), and there is no file-save tool. (plt.savefig() is " + "whitelisted separately and works fine.)\n\n" + "RETURN — TRANSCRIBE, DO NOT NARRATE: your final_answer MUST contain " + "the EXACT tool outputs you received, copied VERBATIM — the column " + "list from list_columns, the numbers and Markdown tables from " + "aggregate / summarize_numeric, the exact '✅ Chart saved as: " + ".png' line from save_chart. The manager writes the final " + "report from YOUR final_answer, so everything you do not pass to " + "final_answer is lost. NEVER paraphrase, summarize, round, or invent " + "values — and never write prose describing what you did (a narrative " + "with no tool output is rejected). If the sub-task cannot be done " + "(missing file, unknown column, impossible computation), copy the " + "actual tool error message into final_answer instead of guessing.\n\n" + "{files_block}" +) + +DATA_WORKER_FILES_HEADER = ( + "DATA FILES (the uploaded data files — pass one of these absolute paths " + "to the tools' file_path argument):\n" +) + +# Replaces smolagents' default managed-agent task template, which demands a +# three-part narrative final answer ("Task outcome (short version)…") — a +# structure that invites small GGUF workers to write prose with INVENTED +# numbers instead of transcribing their real tool outputs (the root-cause +# failure observed end-to-end: the worker ran aggregate() correctly but +# "reported" totals of 15,234 / 123,456 instead of the real 22 / 3,206). +# The override keeps the {{name}} / {{task}} placeholders populate_template +# requires, but demands verbatim tool outputs instead of a narrative. +DATA_WORKER_MANAGED_TASK_TEMPLATE = ( + "You're a focused data-analysis worker named '{{name}}'.\n" + "You have been submitted this task by your manager.\n" + "---\n" + "Task:\n" + "{{task}}\n" + "---\n" + "Answer ONLY that task by calling the data tools, then submit your " + "findings with the final_answer(...) tool — everything you do not pass " + "to final_answer is LOST, so the manager only sees what you put there.\n\n" + "Your final_answer MUST contain the EXACT tool outputs you received, " + "copied VERBATIM:\n" + "- the full column list returned by list_columns,\n" + "- the numbers and Markdown tables returned by aggregate / " + "summarize_numeric,\n" + "- the exact '✅ Chart saved as: .png' line returned by " + "save_chart.\n" + "Copy them verbatim — never paraphrase, summarize, round, or invent " + "values, and never write prose describing what you did." +) + +# Markers that a REAL data-tool output always carries. A worker final answer +# that called a data tool but contains NONE of these is a narrative with no +# actual findings (the fabrication failure) and is rejected with feedback. +_WORKER_FINDINGS_MARKERS = ( + "Columns (exact names", "**Sum", "count:", "mean:", "saved as:", + "✅", "❌", "|", +) + +# The worker's final answer IS the observation the manager reads (with +# provide_run_summary=False, the observation = the final answer verbatim). +# A 4-8K-char verbatim dump per delegation quickly fills the manager's +# 16K-token window mid-run (the "Requested tokens exceed context window" +# crash observed end-to-end), so the transcription validator also caps the +# findings size: keep the numbers verbatim, drop the fluff. +_WORKER_MAX_FINDINGS_CHARS = 3000 + + +def _step_evidence_text(step) -> str: + """Flatten ONE memory step into searchable text. + + A CodeAgent records EVERY step's tool_calls as ['python_interpreter'] — + the actual tool (data_worker on the manager, aggregate/list_columns/… on + the worker) is invoked INSIDE the executed code, so it only ever appears + in `step.code_action` (the code text) or `step.observations` (the + tool's output). Introspecting `tool_calls` alone (as this module did + initially) can NEVER see a delegation or a data-tool call on the + CodeAgent path — the root-cause bug behind the end-to-end failure where + the manager delegated 4+ times yet every final answer was rejected as + "WITHOUT calling data_worker". This helper unions all three evidence + sources; version-robust (getattr / dict guards).""" + parts = [] + for attr in ("code_action", "observations"): + try: + v = getattr(step, attr, None) + if v is None and isinstance(step, dict): + v = step.get(attr) + if v: + parts.append(str(v)) + except Exception: + pass + try: + for tc in (getattr(step, "tool_calls", None) or []): + name = getattr(tc, "name", None) + if name is None and isinstance(tc, dict): + name = tc.get("name") + if name: + parts.append(str(name)) + except Exception: + pass + return "\n".join(p for p in parts if p) + + +_DATA_TOOLS = ("list_columns", "aggregate", "summarize_numeric", + "save_chart", "complete_missing_data", "install_package") + + +def _steps_reference_data_tools(steps) -> bool: + """True when any memory step shows a real data-tool call: the tool-call + name in `tool_calls` (ToolCallingAgent path) OR a call expression like + `aggregate(` in the executed code / observation text (the CodeAgent + path — see _step_evidence_text).""" + for step in steps: + evidence = _step_evidence_text(step) + if not evidence: + continue + if any(f"{name}(" in evidence for name in _DATA_TOOLS): + return True + return False + + +def _validate_worker_findings(final_answer, memory=None, agent=None) -> bool: + """`final_answer_checks` validator for the `data_worker` sub-agent. + + smolagents invokes it as check(final_answer, memory, agent=self) and + feeds a raised Exception back to the model as the reason its answer was + rejected. Catches the transcription failure: the worker ran the tools + (real outputs in its own memory) but its final_answer is pure narration + with invented numbers. Only enforced when the worker ACTUALLY called a + data tool — a tool-less run has nothing to transcribe. Introspection + failures never block (defensive).""" + text = str(final_answer or "") + called_tool = False + try: + steps = list(getattr(memory, "steps", None) or []) \ + or list(getattr(getattr(agent, "memory", None), "steps", None) or []) + called_tool = _steps_reference_data_tools(steps) + except Exception: + # Never let memory introspection block a run. + return True + if not called_tool: + return True + # Size cap: the manager reads this whole text into its OWN context, so a + # bloated dump is not just noise — it is what overflows the window + # mid-run. Keep the numbers verbatim, drop the fluff. + if len(text) > _WORKER_MAX_FINDINGS_CHARS: + raise ValueError( + f"Your findings are {len(text)} characters — too long (max " + f"{_WORKER_MAX_FINDINGS_CHARS}). The manager reads your entire " + "final_answer into its own context, so return a COMPACT findings " + "block: the exact numbers and Markdown tables from " + "aggregate/summarize_numeric, the column list once, and the exact " + "'✅ Chart saved as: .png' lines. Drop the full first-3-rows " + "dump, repeated table dumps, and any prose." + ) + if not any(m in text for m in _WORKER_FINDINGS_MARKERS): + raise ValueError( + "Your final answer contains no actual tool output even though " + "you called the data tools. Copy the EXACT results of those " + "tool calls into final_answer(...) VERBATIM — the column list, " + "the numbers, the Markdown tables, the '✅ Chart saved as: " + ".png' lines. Do not describe what you did and never " + "invent values; the manager writes the report from your exact " + "tool outputs." + ) + return True + + +# A leaked NATIVE tool-call envelope — `data_worker(task='...')` +# (GLM-4.7-Flash / Qwen native format) or `<|tool_call|>` variants — that a +# tool-calling model writes INSIDE a final_answer("""…""") string instead of +# executing data_worker as a Python expression (the observed end-to-end +# failure: GLM-4.7-Flash's manager emitted its intended delegation as an +# envelope, the validator rejected it, and the model repeated the same leak +# every step until the run died). The opening marker is matched so both +# `` and `<|tool_call|>` (with or without the closing pipe/brace) +# are recognized; the body is captured up to the matching close or end. +_NATIVE_TOOL_CALL_RE = re.compile(r"<\|?tool_call\|?[>|](.*?)(?:<\|?\s*/\s*\|?tool_call\|?>|$)", + re.DOTALL | re.IGNORECASE) + + +def _task_from_envelope(content: str) -> Optional[str]: + """Parse ONE native-envelope body for a `data_worker` task string. + Handles the three shapes seen in the wild: the plain call form + `data_worker(task='...')` (GLM-4.7-Flash observed), the JSON form + `{"name": "data_worker", "arguments": {"task": "..."}}` (Qwen), and + the `call:data_worker{task: "..."}` form (Gemma). Returns None when the + body is not a data_worker call or no task can be extracted.""" + content = (content or "").strip() + if not content: + 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). Strip trailing + # tag-ish garbage so the JSON / call: / plain forms below still parse. + content = re.sub(r"(?:\s*)+$", "", content).rstrip() + if not content: + return None + + # JSON shape: {"name": "data_worker", "arguments": {"task": "..."}} + if content.lstrip().startswith("{"): + try: + import json + + data = json.loads(content) + if str(data.get("name", "")).strip() == DATA_WORKER_NAME: + args = data.get("arguments") or {} + t = args.get("task") + if isinstance(t, str) and t.strip(): + return t.strip() + except Exception: + pass + + # call:data_worker{task: "..."} shape + m = re.search(r"call\s*:\s*data_worker\s*\{.*?task\s*:\s*(['\"])(.*?)\1", + content, re.DOTALL) + if m and m.group(2).strip(): + return m.group(2).strip() + + # Plain / kwargs form: data_worker(task='...') — capture the whole arg + # list (the task may contain commas and nested quotes), then the task= + # value or the first string literal. + m = re.search(r"data_worker\s*\((.*)\)\s*$", content, re.DOTALL) + if m: + args = m.group(1).strip() + tm = re.search(r"task\s*=\s*(['\"])(.*?)\1", args, re.DOTALL) + if tm and tm.group(2).strip(): + return tm.group(2).strip() + sm = re.search(r"(['\"])(.*?)\1", args, re.DOTALL) + if sm and sm.group(2).strip(): + return sm.group(2).strip() + return None + + +def _extract_data_worker_task(text: str) -> Optional[str]: + """Extract the `data_worker` task string from a leaked NATIVE tool-call + envelope in the final-answer text. Returns None when the text carries no + data_worker envelope (a normal report is never touched).""" + if not text or not isinstance(text, str): + return None + for m in _NATIVE_TOOL_CALL_RE.finditer(text): + task = _task_from_envelope(m.group(1)) + if task: + return task + return None + + +# How much of the rescued worker findings the rejection message carries back +# to the model — enough to write the grounded report, without flooding its +# context with a max-length transcript. +_RESCUE_FINDINGS_CHAR_CAP = 2200 + + +def _rescue_leaked_data_worker_call(text, agent) -> Optional[str]: + """When the manager's final answer is a leaked NATIVE tool-call envelope + for `data_worker` — the model wrote `data_worker(task='...')` + INSIDE the final_answer string instead of executing it as a Python + expression (GLM/Qwen native format), so no delegation actually ran — + EXECUTE the delegation on its behalf and return a rejection message that + carries the findings, so the model can write the real report next step. + Returns None when there is nothing to rescue (no envelope, no worker — + the caller falls through to the plain "never delegated" rejection). + + The worker runs at most ONCE per run: a repeat leak reuses the first + rescue's findings instead of re-running the expensive worker, and the + flag is set so the follow-up report passes the delegation check. The + findings are also appended to the executor's printed output so the + grounding check can enforce the REAL numbers on that follow-up report + (mirrors what a real `print(worker_result)` delegation would leave). + Never raises.""" + if agent is None: + return None + task = _extract_data_worker_task(text) + if not task: + return None + findings = getattr(agent, "_data_worker_rescued_findings", None) + if findings is None: + worker = None + try: + worker = (getattr(agent, "managed_agents", None) or {}).get(DATA_WORKER_NAME) + except Exception: + worker = None + if worker is None: + return None + try: + findings = worker(task=task) + except Exception as e: + findings = f"❌ data_worker failed: {e}" + findings = str(findings or "") + agent._data_worker_rescued_findings = findings + agent._data_worker_delegated = True + try: + state = getattr(getattr(agent, "python_executor", None), "state", None) + if state is not None: + printed = str(state.get("_print_outputs", "") or "") + state["_print_outputs"] = printed + "\n" + findings + except Exception: + pass + if len(findings) <= _RESCUE_FINDINGS_CHAR_CAP: + shown = findings + else: + shown = findings[:_RESCUE_FINDINGS_CHAR_CAP] + "\n… (truncated)" + return ( + "You wrote your `data_worker` delegation as a native tool-call envelope " + "(data_worker(...)) INSIDE the final_answer " + "string instead of executing it, so no delegation actually ran. I ran " + "it for you. The worker's findings are:\n\n" + f"{shown}\n\n" + "Now write your FINAL Markdown report: headings and prose plus the real " + "numbers above copied VERBATIM (totals, breakdowns, statistics) and " + "each chart filename, then call final_answer(report_text) again. Do NOT " + "write another envelope — the report must be clean text for " + "the user." + ) + + +def _validate_final_report(final_answer, memory=None, agent=None) -> bool: + """`final_answer_checks` validator for the Data Analysis manager. + smolagents invokes it as check(final_answer, memory, agent=self) and + surfaces a raised Exception back to the model as the reason its answer + was rejected, giving it another step to fix it (same pattern as + rag_agent._validate_final_report). Two checks, both cheap and honest: + + 1. The report isn't too short to be a real analysis. + 2. The run actually DELEGATED to `data_worker` at least once — a + final answer written without a single data_worker call contains + no real numbers (the small-model failure the orchestration exists + to fix: a plan-narrative "final answer" that describes the work + instead of doing it). Introspection failures never block the run + (defensive: a future smolagents that renames the memory shape + must not start rejecting every answer). + + The worker's findings are the source of truth for the numbers, so this + deliberately does not police report content itself. + + First, a RESCUE: a final answer that is a leaked native `` + envelope for data_worker (the model wrote its intended delegation as + text instead of executing it — GLM/Qwen native format) is EXECUTED on + the model's behalf and the findings fed back in the rejection message, + so the model can write the real report next step instead of repeating + the same leak until the run dies (the observed GLM-4.7-Flash failure). + Runs before every other check so even a short envelope is rescued.""" + text = str(final_answer or "").strip() + rescued = _rescue_leaked_data_worker_call(text, agent) + if rescued: + raise ValueError(rescued) + # A final answer that LEAKS planning/code text is not a report — the + # observed end-to-end failure had the manager emit a Gemma-native + # `<|tool_call>` envelope inside `final_answer("""…""")` — the model + # narrated its next delegation instead of executing it, so the run + # "succeeded" with a report that contained no real numbers. The + # delegation check below passes for such an answer (an earlier step + # DID delegate, e.g. list_columns), so this catches what delegation + # alone cannot: user-facing reports never mention the internal agent + # name, never assign its result, and never carry a tool-call envelope + # (both the pipe-less `` GLM form and the `<|tool_call|>` + # Gemma/Qwen form). Runs before the min-length check so even a short + # leaked envelope gets the right guidance. + if _MANAGED_AGENT_RETURN_MARKER in text \ + or re.search(r"worker_result\s*=\s*data_worker\(", text) \ + or re.search(r"<\|?tool_call\|?[>|]", text): + raise ValueError( + "Your final answer contains leaked planning or code text instead " + "of the Markdown report: it must be a clean report FOR THE USER " + "about the data (headings, prose, the real numbers, chart " + "filenames) — never the internal `data_worker` call syntax, " + "never a <|tool_call> envelope, never your plan. Rewrite it as a " + "proper Markdown report built ONLY from the findings the worker " + "returned, then call final_answer(report_text) again." + ) + if len(text) < MIN_FINAL_REPORT_CHARS: + raise ValueError( + f"Your final answer is only {len(text)} character(s) — too " + f"short to be a real data-analysis report (need at least " + f"{MIN_FINAL_REPORT_CHARS}). Write a complete Markdown report " + "(a short introduction, clearly-headed sections covering each " + "sub-task the data_worker ran, the actual numbers it returned, " + "and a brief conclusion), then call final_answer(report_text) " + "again with the FULL report text as the argument." + ) + # Delegation evidence on the CodeAgent path lives in the EXECUTED CODE + # (`data_worker(task='...')` inside code_action) and the observation + # (the worker's findings), NOT in tool_calls (which is always + # ['python_interpreter']) — see _step_evidence_text. A persistent flag + # set by the manager's step callback (see _manager_step_callback) + # records the delegation even when this validator runs before the + # delegating step has been appended to memory (smolagents validates the + # final answer BEFORE memory.steps.append(action_step)). + delegated = bool(getattr(agent, "_data_worker_delegated", False)) + if not delegated: + try: + steps = list(getattr(memory, "steps", None) or []) \ + or list(getattr(getattr(agent, "memory", None), "steps", None) or []) + for step in steps: + # REAL delegation evidence lives in the step's OBSERVATION + # (the worker's actual return), never in code_action — a + # model can quote `data_worker(...)` inside a string without + # the call ever running (the observed plan-narration + # failure). + if _observations_prove_delegation(_step_observations_text(step)): + delegated = True + break + except Exception: + # Introspection must never block a run — treat unreadable memory + # as "delegated" so the min-length check alone governs. + delegated = True + if not delegated: + # Same-block fallback: when the manager delegates AND final-answers in + # ONE code block, the delegating step isn't in memory yet at + # validation time — but the executor's accumulated printed output + # already holds the worker's findings (the manager printed + # worker_result). That text proves the worker actually ran. + try: + state = getattr(getattr(agent, "python_executor", None), "state", None) or {} + printed = str(state.get("_print_outputs", "") or "") + if _observations_prove_delegation(printed): + delegated = True + except Exception: + pass + if not delegated: + raise ValueError( + "Your final answer was written WITHOUT calling the `data_worker` " + "sub-agent even once — every number in the report must come from " + "a data_worker call, never from your own assumptions. Call " + "data_worker(task='...') at least once to list the columns and " + "compute the totals/breakdowns/charts, then call " + "final_answer(report_text) again with the report built ONLY from " + "those findings. Do not write the report from memory or guess." + ) + _validate_report_grounding(text, memory, agent) + return True + + +# How many distinct REAL findings numbers (≥ 10) must be reproduced in the +# manager's final report before the grounding check enforces a match. Small +# datasets / qualitative questions legitimately yield fewer, so below this +# the check is skipped (no false rejections). +REPORT_GROUNDING_MIN_FINDINGS_NUMBERS = 3 + +# Fraction of the distinct real findings numbers the report must contain +# (rounded up), once the check is active. +REPORT_GROUNDING_MIN_FRACTION = 0.4 + +_NUM_TOKEN_RE = re.compile(r"\d+(?:\.\d+)?") +_DTYPE_RE = re.compile(r"(?:int|uint|float|complex)\d+") + +# The grounding check must only compare the report against REAL tool-result +# numbers, never the incidental ones in the worker's column-listing head +# dump. A delegation whose task was "list the columns" returns the column +# names + first 3 rows — which legitimately contain invoice IDs (2026001), +# dates (2026), unit prices (899 / 18.5) and sample quantities that a +# report would never reproduce. Extracting ALL of them (as the first +# version did) made the grounding check falsely reject a valid next step, +# panicking the model into a `final_answer()` error loop (observed +# end-to-end on E4B: the check demanded 2026003/2026002/2026001/2026… and +# the run aborted after 3 consecutive errors). These markers appear on +# every real tool-result line and on NONE of the head-dump lines: aggregate +# tables are pipe-delimited (`| … | 1798 |`) with a `**Sum … = 3206**` +# bold total, summarize_numeric lines start with `count:`/`mean:`/…, and +# save_chart returns `✅ Chart saved as: .png`. +_FINDINGS_NUMBER_LINE_MARKERS = ("**Sum", "count:", "mean:", "saved as:", + "✅", "❌", "|") + + +def _result_lines_only(text: str) -> str: + """Keep only the lines of a worker-findings text that carry a real + tool-result marker (aggregate tables / bold totals / summary stats / + chart confirmations), dropping the incidental column-listing head dump + (whose numbers a report would never reproduce). Empty string when no + line qualifies — the grounding check then stands down (no real results + were returned, so there is nothing to enforce).""" + return "\n".join( + line for line in (text or "").splitlines() + if any(m in line for m in _FINDINGS_NUMBER_LINE_MARKERS) + ) + + + +def _normalize_num(tok: str) -> str: + """'22.0' → '22', '3206.00' → '3206', '4.4' → '4.4' — so the report's + formatting of a real number always matches the findings' formatting of + the same value (aggregate returns '22', the report may write '22.0').""" + try: + f = float(tok) + if f == int(f): + return str(int(f)) + return str(f) + except Exception: + return tok.strip() + + +def _findings_numbers(memory, agent) -> set: + """The distinct REAL numbers the worker returned, extracted from the + findings text — the observations of the delegation step(s) (whose + code_action mentions data_worker) plus the executor's accumulated + printed output (the same-block fallback: the delegation step isn't in + memory yet at validation time). Dtype annotations like 'int64' are + stripped so they can't pollute the number set. Empty set on any + introspection failure (the check is then skipped, never a blocker).""" + parts = [] + try: + steps = list(getattr(memory, "steps", None) or []) \ + or list(getattr(getattr(agent, "memory", None), "steps", None) or []) + for step in steps: + if DATA_WORKER_NAME in _step_evidence_text(step): + obs = getattr(step, "observations", None) + if obs: + parts.append(str(obs)) + except Exception: + pass + try: + state = getattr(getattr(agent, "python_executor", None), "state", None) or {} + printed = str(state.get("_print_outputs", "") or "") + if printed: + parts.append(printed) + except Exception: + pass + text = "\n".join(parts) + text = _DTYPE_RE.sub(" ", text) + # Only the REAL tool-result lines count as findings numbers — the + # incidental column-listing head dump (invoice IDs, dates, sample unit + # prices) is never something a report must reproduce, and demanding it + # falsely rejects valid steps (see _result_lines_only / the E4B false + # rejection this fixes). + text = _result_lines_only(text) + # Strip thousands separators (e.g. 11,825 -> 11825) so number extraction + # matches formatted reports. + text = re.sub(r"(\d),(\d)", r"\1\2", text) + return {_normalize_num(t) for t in _NUM_TOKEN_RE.findall(text)} + + +def _validate_report_grounding(text: str, memory, agent) -> None: + """Grounded-numbers check on the manager's final report: the report must + actually CONTAIN the numbers the `data_worker` returned, not numbers the + manager invented. This is the second half of the delegation contract: + `_validate_final_report` proves a data_worker call happened, this proves + the report USED its findings — the end-to-end failure where Qwen3-4B + delegated correctly but then wrote a report full of fabricated totals + (1500/45000 instead of the real 22/3206) and invented seller names. + + Enforced only when the findings contain enough real numbers (≥ + REPORT_GROUNDING_MIN_FINDINGS_NUMBERS distinct values ≥ 10) that a + grounded report could reasonably reproduce them; a small dataset or a + qualitative question that legitimately yields few numbers is never + rejected. Among those real numbers the report must contain at least + REPORT_GROUNDING_MIN_FRACTION of them — the fabricated report shared + zero, the grounded E4B report shared most. Raises (feeding the rejection + back to the model, same as the other checks) or returns None.""" + try: + findings = _findings_numbers(memory, agent) + big = {n for n in findings if _num_value(n) >= 10} + if len(big) < REPORT_GROUNDING_MIN_FINDINGS_NUMBERS: + return # not enough real numbers to enforce grounding + # Strip thousands separators from report text (e.g. 11,825 -> 11825) + # so human/Khmer-formatted numbers match raw tool findings numbers. + clean_report = re.sub(r"(\d),(\d)", r"\1\2", text) + report_nums = {_normalize_num(t) for t in _NUM_TOKEN_RE.findall(clean_report)} + shared = big & report_nums + need = max(1, int(len(big) * REPORT_GROUNDING_MIN_FRACTION)) + if len(shared) >= need: + return + shown = ", ".join(sorted(big, key=_num_value, reverse=True)[:6]) + raise ValueError( + f"Your final report does not contain the real numbers the " + f"`data_worker` returned. The findings include numbers like " + f"{shown}, but your report used different (invented) values. " + "REWRITE the report so every total, breakdown and statistic is " + "copied EXACTLY from the data_worker findings in your context — " + "never invent, round, or estimate numbers yourself, and never " + "make up product or seller names." + ) + except ValueError: + raise + except Exception: + return # introspection must never block a run + + +def _num_value(n: str) -> float: + try: + return float(n) + except Exception: + return 0.0 + + +def _trim_manager_memory_mid_run(agent) -> None: + """Drop the OLDEST steps of the manager's memory when the accumulated + memory (system prompt + task + every step with its worker observations) + would push the next prompt past the context window — the mid-run safety + net. + + Between-turn compaction (agent_memory.compact_agent_memory) runs BEFORE + each run; a single run that delegates many times can still overflow + DURING the run (the end-to-end "Requested tokens (N) exceed context + window of 16384" crash on a 4+ delegation EDA). Keeps the task step and + the most recent steps (the latest worker findings the manager still + needs to write the report), dropping only the old middle. Never raises. + """ + try: + from agents import agent_memory + + model_obj = getattr(agent, "model", None) + if not agent_memory.is_local_backed_model(model_obj): + return + n_ctx = agent_memory._effective_n_ctx( + model_obj, models._llm_n_ctx or mr.get_saved_context_window() + ) + budget = int(n_ctx * agent_memory.COMPACTION_BUDGET_RATIO) - mr.get_saved_max_new_tokens() + if budget <= 0: + return + tokenizer = agent_memory._get_model_tokenizer(model_obj) + if agent_memory.estimate_text_tokens( + agent_memory._memory_to_text(agent, truncate=False), tokenizer) <= budget: + return + steps = list(getattr(agent.memory, "steps", []) or []) + if not steps: + return + from smolagents.memory import TaskStep + + task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)] + # Keep the task step (the user's question + file list — the manager + # must never lose what it was asked), the most recent 3 steps, AND + # every DELEGATION step (the step whose tool_calls include + # `data_worker`) — its observation carries the worker's REAL + # findings, and the final report is built ONLY from those numbers. + # The observed E2B failure: a trim dropping an older delegation left + # the manager with no real numbers to transcribe, so it wrote an + # f-string TEMPLATE report with {total_quantity} placeholders. + keep = [steps[task_indices[0]]] if task_indices else [] + keep.extend(steps[-3:]) + for s in steps: + calls = getattr(s, "tool_calls", None) or [] + if any(getattr(tc, "name", "") == "data_worker" for tc in calls): + keep.append(s) + seen, dedup = set(), [] + for s in keep: + if id(s) not in seen: + seen.add(id(s)) + dedup.append(s) + if len(dedup) < len(steps): + agent.memory.steps = dedup + print(f"[DataAgent] Mid-run memory trim: {len(steps)} -> " + f"{len(dedup)} steps (budget {budget} tokens)") + except Exception: + pass + + +def _worker_loop_guard_callback(step, agent=None): + """smolagents step callback registered on the `data_worker`'s ActionSteps: + the app's repetition-loop guard applied to the WORKER's INTERNAL run. + + The top-level loop guard lives in agent_streaming.stream_agent_steps, + which wraps the MANAGER's stream — but the worker runs inside smolagents' + own managed-agent machinery (ManagedAgent.__call__ → worker.run()), which + bypasses that wrapper entirely. Without this callback, a worker stuck + repeating the SAME call over and over (observed end-to-end on + Qwen3-4B-Q8_0: ten identical `list_columns` re-runs, then a prose + surrender) burns its whole step budget one slow generation at a time, + returning no findings at all. This callback detects the repeated + tool-call signature (reusing the exact same equality key + threshold as + the top-level guard) and, on the threshold, injects the same corrective + nudge into the worker's memory — the fresh context breaks the + deterministic re-generation, the standard cure. Never raises.""" + if agent is None: + return + try: + sig = agent_streaming._tool_calls_signature(step) + if sig is None: + # No readable tool call — both loop channels stand down. + agent._worker_prev_sig = None + agent._worker_repeat = 0 + return + if sig == getattr(agent, "_worker_prev_sig", None): + agent._worker_repeat = getattr(agent, "_worker_repeat", 0) + 1 + else: + agent._worker_prev_sig = sig + agent._worker_repeat = 1 + if getattr(agent, "_worker_repeat", 0) >= agent_streaming._LOOP_NUDGE_THRESHOLD: + if not getattr(agent, "_worker_nudged", False): + agent._worker_nudged = True + # The nudge text is bilingual in i18n; the worker's internal + # nudge is not user-visible (no stream bubble), but the model + # reads it, so keep it in the UI language like everywhere else. + agent_streaming._inject_loop_nudge(agent, "en") + except Exception: + pass + + +def _manager_step_callback(step, agent=None): + """smolagents step callback (registered on the manager's ActionSteps). + + Two jobs, both running AFTER the step completes (smolagents calls it in + `_finalize_step`, before the step is appended to memory): + + 1. Record delegation evidence on the agent object. A CodeAgent step's + `tool_calls` is always ['python_interpreter'], so the ONLY place a + REAL delegation shows up is the step's OBSERVATION — the worker's + returned findings ("Here is the final answer from your managed + agent…" + the verbatim tool outputs). The executed code + (code_action) is NOT evidence: the observed end-to-end failure had + the manager emit a Gemma-native `<|tool_call>` envelope INSIDE a + final_answer(…) string literal — the text `data_worker(task=…)` + appeared in the code without the call ever running. Requiring the + worker's actual return (managed-agent marker or findings markers) + in the observation keeps the flag honest. Setting a persistent + flag here — rather than introspecting memory in the validator — + also survives the mid-run memory trim below, which drops old + steps whose observations held the evidence. + 2. Trim the manager's memory when it would overflow the context + window (see _trim_manager_memory_mid_run). + + Signature matches smolagents' callback convention (memory_step, agent). + Never raises.""" + if agent is None: + return + try: + if not getattr(agent, "_data_worker_delegated", False) \ + and _observations_prove_delegation(_step_observations_text(step)): + agent._data_worker_delegated = True + except Exception: + pass + _trim_manager_memory_mid_run(agent) + + +def _step_observations_text(step) -> str: + """The OBSERVATION text of a step only (never code_action) — the place a + REAL managed-agent delegation shows up: smolagents wraps the worker's + return in "Here is the final answer from your managed agent '…':" plus + the verbatim tool outputs. Code text mentioning `data_worker(` is NOT + proof (a model can quote the call inside a string without ever + executing it — the observed plan-narration failure).""" + try: + v = getattr(step, "observations", None) + if v is None and isinstance(step, dict): + v = step.get("observations") + return str(v or "") + except Exception: + return "" + + +# The max-steps hand-off transcript cap — a 10-step worker's full tool +# transcript (columns + every aggregate table) stays well under this; the +# cap only guards a pathological run from flooding the manager's context. +_WORKER_OBS_TRANSCRIPT_CAP = 8000 + + +def _collect_worker_observations(worker) -> str: + """The `data_worker`'s run transcript — the verbatim tool outputs it + COMPUTED but never delivered via final_answer. Thin wrapper over the + shared agent_streaming.collect_agent_observations (same helper the + Deep Research search agent uses), with the worker-specific cap. See + agent_streaming for the full rationale: a max-steps worker's REAL + findings live in its ActionStep observations, exactly the verbatim + tool outputs its final_answer contract would have carried.""" + return agent_streaming.collect_agent_observations( + worker, cap=_WORKER_OBS_TRANSCRIPT_CAP) + + +def _worker_max_steps_handoff(self, task): + """The `data_worker`'s max-steps fallback (instance-patched onto the + worker in `_build_data_worker`): prefer the run's REAL findings — the + verbatim tool observations — over smolagents' stock last-ditch + raw-text answer, so the manager receives the computed numbers instead + of a leaked code fence. Thin wrapper over the shared + agent_streaming.max_steps_findings_handoff. NEVER raises.""" + return agent_streaming.max_steps_findings_handoff( + self, task, cap=_WORKER_OBS_TRANSCRIPT_CAP) + + +# smolagents wraps every managed-agent return in this marker (the +# `managed_agent.report` prompt template) — its presence in an observation +# proves the worker ACTUALLY ran and returned. +_MANAGED_AGENT_RETURN_MARKER = "Here is the final answer from your managed agent" + +# Delegation-proof findings markers. NOTE: deliberately EXCLUDES the bare +# `"|"` pipe from _WORKER_FINDINGS_MARKERS — the Gemma-native +# `<|tool_call>` envelope the model leaks when it narrates a plan contains +# pipes, so `|` alone would falsely prove a delegation that never ran. +_DELEGATION_PROOF_MARKERS = ("**Sum", "count:", "mean:", "saved as:", + "✅", "❌") + + +def _observations_prove_delegation(text: str) -> bool: + """True when an observation text carries the worker's REAL return: the + smolagents managed-agent wrapper marker (any return — even an error + message) OR the strong findings markers (a return that actually ran the + data tools).""" + return _MANAGED_AGENT_RETURN_MARKER in text or any(m in text for m in _DELEGATION_PROOF_MARKERS) + + +def _build_worker_agent(llm, model_id: str = "", files: Optional[list] = None, + max_steps: Optional[int] = None, + execution_timeout: Optional[int] = None): + """Build the `data_worker` sub-agent: a plain CodeAgent holding ONLY + the curated data tools, with the data file paths bound into its system + instructions at build time. Registered as a managed_agents entry on the + manager, so smolagents exposes it to the manager as a callable tool.""" + if max_steps is None: + max_steps = mr.get_max_steps_for_model(model_id, DATA_WORKER_DEFAULT_MAX_STEPS) + # AUTO (None) on the Data tab means the tab's own default, NOT + # smolagents' 30s — heavy EDA steps routinely exceed 30s (see + # DATA_EXECUTION_TIMEOUT_DEFAULT). + if execution_timeout is None: + execution_timeout = DATA_EXECUTION_TIMEOUT_DEFAULT + + files_block = "" + if files: + files_block = DATA_WORKER_FILES_HEADER + "\n".join(f"- {p}" for p in files) + "\n\n" + instructions = DATA_WORKER_INSTRUCTIONS.format(files_block=files_block) + + worker = build_smol_agent( + llm, + tools=[install_package, list_columns, aggregate, summarize_numeric, + save_chart, complete_missing_data], + max_steps=max_steps, + execution_timeout=execution_timeout, + # The worker ALWAYS runs a plain CodeAgent (Python execution is its + # whole point) — ToolCallingAgent has no Python executor, so it + # could never run pandas/matplotlib code. The factory's default is + # now use_tool_calling=True (tool calling is the app-wide default), + # so this sub-agent must explicitly opt OUT or it would silently + # become a ToolCallingAgent. additional_authorized_imports=["*"] = + # trusted local machine — full stdlib + installed packages. The + # markdown-fence code_block_tags / executor_kwargs version guards + # live in the shared factory (agents/agent_factory.py). + use_tool_calling=False, + instructions=instructions, + extra_kwargs={ + "name": DATA_WORKER_NAME, + "description": DATA_WORKER_DESCRIPTION, + # The worker's final_answer IS the findings — a run-summary + # blob of its whole transcript would only bloat the manager's + # observation (and bury the numbers under noise for a small + # model). Keep the observation = the verbatim tool outputs only. + "provide_run_summary": False, + "additional_authorized_imports": ["*"], + }, + # The transcription guard: a final answer with no real tool output + # (narration with invented numbers) is rejected and sent back. The + # repetition-loop guard runs after every worker step (see + # _worker_loop_guard_callback) — the top-level guard in + # stream_agent_steps cannot see the worker's internal run. + optional_kwargs={ + "final_answer_checks": [_validate_worker_findings], + "step_callbacks": [_worker_loop_guard_callback], + }, + ) + # Override smolagents' default managed-agent task template (the 3-part + # "Task outcome…" narrative demand that invites invented numbers) with + # the verbatim-transcription contract. Version-guarded: an older + # smolagents without the prompt_templates dict keeps the stock template + # (the instructions + validator still carry the contract). + try: + m_task = worker.prompt_templates["managed_agent"] + if isinstance(m_task, dict): + # Newer smolagents stores the template dict ({'task': ..., 'report': ...}). + if "task" in m_task: + m_task["task"] = DATA_WORKER_MANAGED_TASK_TEMPLATE + elif hasattr(m_task, "task"): + # Older dataclass shape (ManagedAgentPromptTemplate.task). + m_task.task = DATA_WORKER_MANAGED_TASK_TEMPLATE + except Exception: + pass + # Max-steps hand-off (see _worker_max_steps_handoff): when the worker + # burns its whole step budget without ever calling final_answer (the + # Muse Glimmer Data failure — it computed the totals, then surrendered + # with a leaked code fence), the manager would receive that garbage. + # Deliver the run's verbatim tool observations instead — the exact + # content the worker's final_answer contract would have carried. + # Instance-level patch, data_worker ONLY: the Data MANAGER is a + # CodeAgent too, but its observations are "Here is the final answer + # from your managed agent…" wrappers, not a report, so it keeps the + # stock behavior. + try: + worker._orig_handle_max_steps_reached = worker._handle_max_steps_reached + worker._handle_max_steps_reached = types.MethodType( + _worker_max_steps_handoff, worker + ) + except Exception: + pass + print(f"[DataAgent] Building {type(worker).__name__} sub-agent " + f"'{DATA_WORKER_NAME}' on '{model_id or '(shared)'}' …") + return worker + + +def _build_manager_agent(llm, worker, model_id: str = "", + max_steps: Optional[int] = None, + execution_timeout: Optional[int] = None): + """Build the manager agent. It holds NO data tools of its own — only + the managed `data_worker` sub-agent (plus smolagents' auto-added + final_answer tool). Its whole job is to analyze the user's data + question, split it into focused sub-tasks, delegate them, and + synthesize the grounded Markdown report. + + The manager is a CodeAgent (use_tool_calling=False), not a + ToolCallingAgent like the RAG / Deep Research managers. Reason: the + Data tab's verified models are small quantized GGUFs whose reliable + path in this app is the forgiving CODE grammar — the smart parser + (agent_streaming._patch_smolagents_code_parser) executes even + prose-wrapped output, rewrites Qwen/Gemma native `<|tool_call|>` + envelopes into real calls, and the executor environment includes the + managed agents, so `data_worker(task='...')` works as a plain Python + expression. A ToolCallingAgent manager repeatedly failed end-to-end on + Qwen3-4B-Q8_0 by "answering the prompt" with plan narration instead + of emitting structured calls; the code path plus the delegation + validator below is the reliable combination.""" + if max_steps is None: + max_steps = mr.get_max_steps_for_model(model_id, mr.DATA_AGENT_MAX_STEPS) + # Same AUTO default as the worker (see DATA_EXECUTION_TIMEOUT_DEFAULT). + if execution_timeout is None: + execution_timeout = DATA_EXECUTION_TIMEOUT_DEFAULT + + manager = build_smol_agent( + llm, + tools=[], + max_steps=max_steps, + execution_timeout=execution_timeout, + # The manager delegates via `data_worker(task='...')` Python + # expressions (see DATA_MANAGER_INSTRUCTIONS) — it never runs + # data tools itself, but the code grammar is the reliable one for + # this tab's small models (see the docstring above). + use_tool_calling=False, + instructions=DATA_MANAGER_INSTRUCTIONS, + # Deep-research strategy: re-plan every few steps instead of + # blindly executing the initial delegation plan. final_answer_checks + # is attached only when this smolagents version's __init__ accepts + # it (optional_kwargs guard). + extra_kwargs={ + "managed_agents": [worker], + # Per-model override: models flagged planning-incompatible + # (Muse Glimmer — it echo-loops the re-plan prompt) get None + # (planning off), everyone else keeps the default interval. + "planning_interval": mr.planning_interval_for_model(model_id, DATA_MANAGER_PLANNING_INTERVAL), + }, + # The delegation flag + mid-run memory trim run after every manager + # step (see _manager_step_callback) — CodeAgent delegation evidence + # lives in code_action/observations, not tool_calls, so the flag is + # the validator's source of truth. Version-guarded through + # optional_kwargs: an older smolagents without step_callbacks skips + # it (the validator's memory-scan fallback still works). + optional_kwargs={ + "final_answer_checks": [_validate_final_report], + "step_callbacks": [_manager_step_callback], + }, + ) + print(f"[DataAgent] Building {type(manager).__name__} manager on " + f"'{model_id or '(shared)'}' …") + return manager + + +def get_data_agent(model_id: Optional[str] = None, + max_steps: Optional[int] = None, + worker_max_steps: Optional[int] = None, + execution_timeout: Optional[int] = None, + provider: Optional[str] = None, + n_ctx: Optional[int] = None, + files: Optional[list] = None): + """Lazily build (or rebuild, if the model or the uploaded file set + changed) the manager + `data_worker` sub-agent pair. + + `max_steps` is the MANAGER's step budget and `worker_max_steps` the + `data_worker` sub-agent's — the UI's per-tab "Max Steps" / "Sub-agent + steps" controls. Both None = AUTO (the model-scaled defaults: + DATA_AGENT_MAX_STEPS / DATA_WORKER_DEFAULT_MAX_STEPS). + + `files` (the staged upload paths) is part of the cache key because the + worker's system instructions carry the data file paths — a new/changed + dataset must rebuild the pair so the worker reads the right files + (mirrors RAG's `sources` cache key). Rebuilding is cheap: the LLM is + shared/cached via models.get_llm(). + """ + global _data_agent, _data_worker, _data_agent_model_id + global _data_agent_max_steps, _data_agent_worker_max_steps + global _data_agent_execution_timeout, _data_agent_n_ctx + global _data_agent_files + target = model_id or models._llm_model_id + files_key = tuple(sorted(str(p) for p in (files or []))) + + if (_data_agent is not None + and target == _data_agent_model_id + and max_steps == _data_agent_max_steps + and worker_max_steps == _data_agent_worker_max_steps + and execution_timeout == _data_agent_execution_timeout + and n_ctx == _data_agent_n_ctx + and files_key == _data_agent_files): + return _data_agent + + with _data_agent_lock: + if (_data_agent is not None + and target == _data_agent_model_id + and max_steps == _data_agent_max_steps + and worker_max_steps == _data_agent_worker_max_steps + and execution_timeout == _data_agent_execution_timeout + and n_ctx == _data_agent_n_ctx + and files_key == _data_agent_files): + return _data_agent + + print(f"[DataAgent] Building manager + {DATA_WORKER_NAME} on '{target}' …") + llm = models.get_llm(target, provider=provider, n_ctx=n_ctx) + worker = _build_worker_agent(llm, target, files_key, worker_max_steps, execution_timeout) + _data_worker = worker + _data_agent = _build_manager_agent(llm, worker, target, max_steps, execution_timeout) + _data_agent_model_id = target + _data_agent_max_steps = max_steps + _data_agent_worker_max_steps = worker_max_steps + _data_agent_execution_timeout = execution_timeout + _data_agent_n_ctx = n_ctx + _data_agent_files = files_key + # Standard smolagents behaviour: a freshly-built agent starts + # with empty memory. This only happens on first use, or after a + # model/dataset switch or reset via reset_agent() below — + # dataset changes are ALSO handled by reset_if_context_changed() + # in run_data_analysis(), which clears an EXISTING manager's + # memory in place rather than rebuilding it (see + # agent_memory.py's module docstring for why rebuilding-to-reset + # used to reintroduce the very stale memory it was meant to drop). + return _data_agent + + +def reset_agent(): + """Drop the manager + worker pair. It references the shared LLM managed + by models.get_llm(), whose memory is released there when the underlying + model actually changes. Rebuilding is cheap since it reuses get_llm(target). + + Also called whenever the LLM is reloaded/unloaded elsewhere (the agents + hold their own reference to that same model and would otherwise keep an + unloaded model alive). + """ + global _data_agent, _data_worker, _data_agent_model_id + global _data_agent_max_steps, _data_agent_worker_max_steps + global _data_agent_execution_timeout, _data_agent_n_ctx + global _data_agent_files + _data_agent = None + _data_worker = None + _data_agent_model_id = None + _data_agent_max_steps = None + _data_agent_worker_max_steps = None + _data_agent_execution_timeout = None + _data_agent_n_ctx = None + _data_agent_files = () + + +def save_data_files(files) -> list: + """Copy uploaded CSV/XLSX files into the persistent data-analysis workspace.""" + Path(mr.DATA_UPLOAD_DIR).mkdir(parents=True, exist_ok=True) + paths = [] + if not files: + return paths + if not isinstance(files, list): + files = [files] + for f in files: + src = get_file_path(f) + if not src: + continue + dest = Path(mr.DATA_UPLOAD_DIR) / Path(src).name + try: + shutil.copy(src, dest) + paths.append(str(dest)) + except Exception: + pass + return paths + + +def build_data_task(question: str, file_list_str: str, lang_key: str = "kh") -> str: + """Build the Data Analysis MANAGER's task prompt. + + Prepends the UI-language output directive (i18n._output_lang_instruction) + so a Khmer UI gets Khmer answers and an English UI gets English ones — + the same shared contract as every other chat/agent tab. The directive + is at the very START of the prompt, before any other instruction, so + small models see it first. + + The manager does not touch the data itself — it decomposes the user's + request into focused sub-tasks and delegates each to the `data_worker` + sub-agent (whose own instructions carry the exact-column-name rule and + the tool usage). This task tells the manager how to orchestrate, what + the worker can do, and that the final report must be built ONLY from + the worker's findings. + + The user's request is placed as the LAST line of the task (the task + text is the user turn the manager model sees), so a small GGUF model + anchors on the request rather than the instruction block — the same + question-last hardening as the other agentic task builders. + """ + return f"""{i18n._output_lang_instruction(lang_key)}You are a data analysis assistant and research manager. +Data file(s) provided by the user: +{file_list_str} + +You do NOT run Python or touch the data yourself — the ONLY agent that +exists is `data_worker`, a focused worker holding the list_columns, +aggregate, summarize_numeric, save_chart, complete_missing_data and +install_package tools. Call it +from your code block as a plain Python expression and print the result: +worker_result = data_worker(task='...') +print(worker_result) +The printed value is the worker's findings — read it and copy its real +numbers into your report. It has NO memory of other calls, so each task +must name the data file(s) and the EXACT column names to use. + +BUNDLE related computations into as FEW data_worker calls as possible: +each call is a fresh, expensive worker run, so ONE task can ask the worker +to list the columns, compute all totals, do all breakdowns AND create all +the charts together. Do not split related work into many calls. + +★ COLUMN NAMES — ALWAYS USE THE EXACT NAMES FROM THE DATA + - Column names are EXACTLY as they appear in the file and may be in Khmer + or any other language (e.g. 'បរិមាណ', 'តម្លៃ/ឯកតា (USD)', 'សរុប (USD)', + 'កាលបរិច្ឆេទ'). NEVER translate, rename, guess, or invent column names — + and never assume English equivalents like 'Quantity', 'Unit Price', + 'Date', or 'Product'. + - Instruct `data_worker` to print df.columns.tolist() after loading and + copy the names VERBATIM; on a KeyError it must re-print + df.columns.tolist(), take the real name, and retry. + +Write a well-structured Markdown report built ONLY from the worker's +findings — include the ACTUAL numbers it returned (totals, breakdowns, +statistics) verbatim, reference each chart by its exact PNG filename, and +never invent or estimate values. For a default EDA, structure it as a +Dataset Overview, Statistical Summary, and an Analysis Report with Key +Metrics and Trends. If the request involves payroll/salary data, delegate +computing gross pay, deductions, tax and net pay and report those totals. If +the data has BLANK (missing/empty) cells or columns — e.g. កាត់ពន្ធ / tax +and ប្រាក់ខែសុទ្ធ (USD) / net salary left empty, or a few missing values +scattered anywhere — delegate completing them via complete_missing_data, +which works on ANY dataset: it auto-derives relations from the column +names (payroll identities; generic totals like quantity × unit price, +validated against known rows), accepts explicit +rules={{'': ''}} when the user states one (e.g. a 10% tax +rate), and statistically estimates partially-blank columns (mean / most +common value, clearly labeled). It never invents numbers, so if a blank +column has no rule, no derivable relation and no observed values, report +that it stayed blank. + +As your FINAL ANSWER, return the full Markdown report or the direct answer +to the user's request below. REMEMBER: you MUST call `data_worker` at least +once before final_answer — a final answer with no data_worker call is +rejected and sent back to you. + +--- +The user's request to fulfil: +{question}""" + + +def _pretty_chart_name(name: str) -> str: + """The display caption for a chart card: the filename stem with + underscores turned into spaces ('Sales_Trend.png' → 'Sales Trend').""" + stem = Path(str(name)).stem + return stem.replace("_", " ").strip() or str(name) + + +def _chart_gallery_html(chart_files, lang_key: str = "kh") -> str: + """The chart gallery block appended under a data-analysis run's final + answer bubble. It shows EVERY chart the run produced — the model's + report markdown may reference some or none of them (small models often + write Windows paths or prose instead of `![alt](file.png)` refs), so the + gallery always displays the real set. Images are served by the backend's + /api/data/chart/ endpoint (percent-encoded, so Khmer/space + filenames survive). Only basenames are ever used — a stray path in the + list cannot leak an arbitrary file into the bubble, and the caption / + alt text are HTML-escaped. Returns '' when there are no charts. NEVER + raises.""" + try: + from urllib.parse import quote + + names = [] + for p in chart_files or []: + name = Path(str(p)).name + if name and name.lower().endswith(".png") and name not in names: + names.append(name) + if not names: + return "" + title = ("📊 ក្រាហ្វិកដែលបានបង្កើត" if lang_key == "kh" + else "📊 Generated charts") + cards = "\n".join( + f'
' + f'' + f'
{html.escape(_pretty_chart_name(name), quote=True)}
' + f"
" + for name in names + ) + return ( + f'\n\n" + ) + except Exception: + return "" + + +def run_data_analysis(files, question: str, model_label: str, history: list, + use_memory: bool = True, lang_key: str = "kh", + max_steps: Optional[int] = None, + worker_max_steps: Optional[int] = None, + execution_timeout: Optional[int] = None, + n_ctx: Optional[int] = None): + """Hand uploaded data + the user's question to the data manager and collect its report. + + `use_memory` controls the "🧠 Conversation Memory" checkbox: when on, + the manager remembers earlier turns about the SAME dataset (capped — + see DATA_AGENT_MEMORY_TURNS) and old memory is dropped automatically + if a different file is uploaded. When off, every question is answered + from a clean slate regardless of what file is uploaded. + + A GENERATOR: yields (history, gallery_update, report_update) once per + live agent step as the analysis runs (see agent_streaming.py), using + None no-op placeholders for the gallery outputs during those + intermediate yields so charts don't flicker to "empty" mid-run — then + one final time with the real chart list (the report slot stays None: + the report markdown lives in the final answer bubble and is exported + to .docx on demand via the UI's 💾 Save Report button, never + auto-saved). This is easily the longest-running single call in the + app (a full EDA — load, chart, correlate, write a report), so live + progress matters here more than almost anywhere else. + """ + history = history or [] + + paths = save_data_files(files) + if not paths: + history.append({"role": "user", "content": question or "(no file)"}) + history.append({"role": "assistant", "content": "⚠️ Please upload a CSV or XLSX file first."}) + yield history, None, None + return + + question = (question or "").strip() or ( + "Perform a full exploratory data analysis (EDA) on this dataset and " + "generate a thorough Markdown report with multiple charts." + ) + provider = mr.get_saved_provider("data") + model_id = mr.resolve_model_id(model_label, provider=provider) + n_ctx = n_ctx if n_ctx is not None else mr.get_saved_context_window("data") + history.append({"role": "user", "content": f"📎 {', '.join(Path(p).name for p in paths)}\n\n{question}"}) + + try: + stamp = datetime.datetime.now().strftime("report-%Y-%m-%d-%H%M%S") + report_base = Path(mr.REPORT_DIRS["data"]) + report_dir = report_base / stamp + report_dir.mkdir(parents=True, exist_ok=True) + set_active_report_dir(report_dir) + + out_dir = Path(mr.DATA_OUTPUT_DIR) + out_dir.mkdir(parents=True, exist_ok=True) + + # Snapshot pre-existing .png files in cwd to detect newly created charts + t0_cwd_pngs = {p.resolve() for p in Path.cwd().glob("*.png")} + + # Now that a run can produce many charts (full EDA, not just one), + # clear out PNGs left over from a previous analysis first — otherwise + # they'd pile up and get mixed into this run's gallery below. + for stale_png in out_dir.glob("*.png"): + try: + stale_png.unlink() + except OSError: + pass + # The pair is rebuilt automatically when the model OR the uploaded + # file set changes (the worker's instructions carry the file paths). + agent = get_data_agent(model_id, max_steps=max_steps, worker_max_steps=worker_max_steps, execution_timeout=execution_timeout, provider=provider, n_ctx=n_ctx, files=paths) + # The agent object is CACHED across turns, so the delegation flag + # from a previous turn's run must not leak into this one (a stale + # True would let a no-delegation answer pass the validator). The + # step callback re-sets it during THIS run's delegation steps. + # Same for the leaked-envelope rescue state: a stale rescued + # findings blob must not be replayed into a new turn's rejection + # message (and a stale `_data_worker_delegated` must not skip the + # rescue entirely). + try: + agent._data_worker_delegated = False + agent._data_worker_rescued_findings = None + except Exception: + pass + # New/changed dataset → old manager memory (referencing whatever the + # previous file's columns/stats were) is no longer relevant, so + # drop it even though the model itself hasn't changed. Only + # relevant when memory is on — when it's off, reset=True below + # already makes every run stateless regardless of dataset. + # Clears agent.memory.steps directly on the SAME agent object — + # see agent_memory.reset_if_context_changed()/reset_memory()'s + # docstrings for why this (rather than tearing down and rebuilding + # the agent, as an earlier version of this file did) is required + # for the reset to actually stick. + if use_memory: + agent_memory.reset_if_context_changed(agent, _last_data_context, tuple(sorted(paths))) + file_list_str = "\n".join(f"- {p}" for p in paths) + + task = build_data_task(question, file_list_str, lang_key) + + # See chat.py's chat_general_direct() matching comment — a no-op + # unless the "🧠 Enable Model Reasoning" toggle (⚙️ Model Settings) + # is off. Data Analysis's task prompt is already long, so a heavy + # thinking-tuned model has even less MAX_NEW_TOKENS headroom left + # for its actual code — this is one of the tabs most likely to + # benefit from turning reasoning off. + task = mr.apply_reasoning_toggle(task) + t0 = time.time() + # reset=False keeps this manager's memory across turns on the + # SAME dataset (e.g. "now also break that down by region" after an + # initial EDA) — see + # https://huggingface.co/docs/smolagents/tutorials/memory. Capped + # right after via agent_memory.cap_agent_memory(), and fully reset + # above whenever the uploaded file(s) change. reset=True (memory + # checkbox off) makes every question stateless instead. + # Live step streaming — see agent_streaming.stream_agent_steps()'s + # docstring / chat.py's matching usage in the other agentic tabs. + # Token-budget-aware memory compaction (see agent_memory.py): before + # this run, if the accumulated memory would push the next prompt past + # the context window, condense the older turns into a rolling summary + # instead of just dropping them — the fixed turn-cap below stays as + # the post-run safety net. Dataset changes reset memory (and the + # rolling summary) upstream via reset_if_context_changed(). + if use_memory and agent_memory.compact_agent_memory( + agent, model_id=model_id, + n_ctx=models._llm_n_ctx or mr.get_saved_context_window(), + keep_recent_turns=mr.get_saved_memory_keep_recent("data"), + budget_ratio=mr.get_saved_memory_compaction_ratio(), + lang_key=lang_key): + comp_msg = ("🧹 កំពុងបង្រួមអង្គចងចាំសន្ទនា…" if lang_key == "kh" + else "🧹 Compacting conversation memory…") + history.append({"role": "assistant", "content": comp_msg}) + yield history, None, None + history.pop() + result = None + diag = None # snapshot from the stream's final yield — the abort badge below reads it (every stream path ends with one) + for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory, lang_key=lang_key): + if not is_final: + if step_msg is not None: + history.append(step_msg) + yield history, None, None + continue + result = final_output + if use_memory: + agent_memory.cap_agent_memory(agent, max_turns=DATA_AGENT_MEMORY_TURNS) + elapsed = time.time() - t0 + + report_text = str(result) + # Surface compaction activity in the footer (see agent_memory.py). + compacted_n = getattr(agent, "_compaction_count", 0) or 0 + memory_txt = "on" if use_memory else "off" + if use_memory and compacted_n: + memory_txt = f"on (compacted {compacted_n}×)" + # The effective step budget the agent ACTUALLY ran with (the + # DATA_AGENT_MAX_STEPS default when the Max Steps control is on + # auto) — same 'what actually ran' footer segment as the chat tabs + # (see agent_streaming._agent_steps_budget_txt). The managed + # `data_worker` sub-agent's budget is included too. Kept in this + # tab's existing '|'-separated style (vs the chat tabs' '·'). + steps_txt = agent_streaming._agent_steps_budget_txt(agent) + steps_seg = f" | {steps_txt}" if steps_txt else "" + # The effective per-step execution timeout too — the manager itself + # is a ToolCallingAgent (no Python executor), so the shared helper + # finds the timeout on the managed `data_worker` CodeAgent (whose + # executor the timeout actually caps). Same 'what actually ran' + # semantics: the value the factory applied, or smolagents' own 30s + # default when the Exec timeout control is on auto. + exec_txt = agent_streaming._agent_exec_timeout_txt(agent) + exec_seg = f" | {exec_txt}" if exec_txt else "" + + # Collect any .png files created in cwd (e.g. if the worker called plt.savefig('salary_by_department.png')) + for p in Path.cwd().glob("*.png"): + if p.resolve() not in t0_cwd_pngs: + try: + dst = report_dir / p.name + if not dst.exists(): + shutil.move(str(p), str(dst)) + else: + p.unlink(missing_ok=True) + except OSError: + pass + + # Sync all PNGs between out_dir and report_dir + for p in out_dir.glob("*.png"): + try: + dst = report_dir / p.name + if not dst.exists(): + shutil.copy2(str(p), str(dst)) + except OSError: + pass + for p in report_dir.glob("*.png"): + try: + dst = out_dir / p.name + if not dst.exists(): + shutil.copy2(str(p), str(dst)) + except OSError: + pass + + chart_files = sorted(str(p) for p in report_dir.glob("*.png")) + # The chart gallery rides AFTER the
footer so the .docx export + # (chat.chat_data splits on the first
) stays clean markdown — + # the gallery is bubble-only, never part of the saved report. + response = agent_streaming.sanitize_surrogates( + report_text + + agent_streaming._agent_abort_html(lang_key, diag) + + f"\n\n
⏱ {elapsed:.1f}s | model: {model_id} " + f"({DEVICE.upper()}){steps_seg}{exec_seg} | memory: {memory_txt}" + + _chart_gallery_html(chart_files, lang_key) + ) + history.append({"role": "assistant", "content": response}) + + # No report file is ever auto-saved — the report markdown lives in the + # final answer bubble (the export-text source); the user's 💾 Save + # Report button converts it on demand into a .docx under + # user_data/reports/data_analysis/. + yield history, (chart_files or None), None + return + + except Exception as e: + import traceback + history.append({"role": "assistant", "content": f"❌ {e}\n\n{traceback.format_exc()}"}) + yield history, None, None + return