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