Download agents/agent_streaming.py from localailb/assistant: direct link, hf CLI and curl.
- Browser
- Download file 161 kB
-
https://huggingface.co/spaces/localailb/assistant/resolve/main/agents/agent_streaming.py
- Command line
-
hf download hf://spaces/localailb/assistant/agents/agent_streaming.py
-
curl -L -o agent_streaming.py https://huggingface.co/spaces/localailb/assistant/resolve/main/agents/agent_streaming.py
161 kB
"""
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>β¦</ο½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 ('|</DSML|python|>'), so an optional
# pipe before the closing '</' is accepted. `python`/`py` (or no language
# tag) is allowed inside the markers.
_DSML_FENCE_RE = re.compile(
r"<\s*[\uFF5C|]\s*DSML\s*[\uFF5C|]\s*(?:python|py)?\s*[\uFF5C|]?\s*>"
r"(.*?)"
r"\s*[\uFF5C|]?\s*</\s*[\uFF5C|]?\s*DSML\s*[\uFF5C|]\s*(?:python|py)?\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: <value>}" 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. `</arg_value></tool_call>`,
`<tool_call>`, `<|tool_call|>`, `</tool_call>`, `</arg_value>`, 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. </arg_value></tool_call>, </tool_call>)
cleaned = re.sub(r"(?:\s*</?[a-zA-Z0-9_\-|:]+>\s*)+$", "", text).rstrip()
# Strip leading XML/tool-call tags (e.g. <tool_call><arg_name>...</arg_name><arg_value>)
cleaned = re.sub(r"^(?:\s*</?[a-zA-Z0-9_\-|:]+>\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)
# </ο½DSMLο½python>
#
# 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>β¦</ο½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')<tool_call|>
#
# 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 <tool_call|> β 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 `</tool_call>`-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<whole program>` β 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 `</arg_value>` XML fragment AFTER the call's close paren, before
# the `</tool_call>` 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"(?:</?[a-zA-Z_][a-zA-Z0-9_]*>\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")\|?>|</s>",
re.IGNORECASE,
)
# Muse Glimmer's channel markers ("to=user" / "to=assistant" / "to=self" /
# "to=<tool>"). 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"(?<![^\s])to=(?:user|assistant|self|<[a-z_][a-z0-9_]*>)(?![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|>, </s>, 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 <tool>
channel form to=<tool> 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
# ("</s>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 <think> 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 <think> 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 <think> 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<whole program>` β 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 `</tool_call>` 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 <toolname> 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. </arg_value></tool_call> 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'<div class="tool-header"><b>{exec_label}</b> <code>{name_esc}</code></div>\n'
f'<pre class="obs-code"><code>{args_esc}</code></pre>'
)
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 (
'<details class="agent-step-details">\n'
f'<summary class="agent-step-summary"><b>{planning_label}</b></summary>\n'
'<div class="agent-log-block">\n'
f'<div class="agent-plan-box"><div class="plan-header">{strategy_label}</div><div>{plan_esc}</div></div>\n'
'</div>\n</details>'
)
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' <span class="step-timing">({", ".join(durs)})</span>'
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'<div class="agent-thought-box"><b>{reasoning_label}</b>\n{cleaned_esc}</div>')
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'<div class="agent-tool-box">{tc_str}</div>')
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'<div class="agent-obs-box">\n'
f'<div class="obs-header">{obs_label}</div>\n'
f'<pre class="obs-code"><code>{obs_esc}</code></pre>\n'
'</div>'
)
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'<div class="agent-err-box">\n'
f'<div class="err-header">{err_label}</div>\n'
f'<div>{err_esc}</div>\n'
'</div>'
)
if not parts:
return None
body_html = "\n".join(parts)
rendered = (
f'<details class="agent-step-details">\n'
f'<summary class="agent-step-summary">{header_text}{timing_badge}</summary>\n'
f'<div class="agent-log-block">\n{body_html}\n</div>\n'
'</details>'
)
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=<code text>)], 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 <label>)' (label derived from the managed agent's name:
'search' for the RAG/Deep Research searchers, 'data worker' for Data
Analysis), or '' when the agent exposes no budget (never breaks a
footer on an odd/None agent). Shared by the General / RAG / Deep
Research / Data Analysis footers (the chat.py call sites keep the
same-name alias for continuity)."""
if agent is None:
return ""
steps = getattr(agent, "max_steps", None)
if steps is None:
return ""
txt = f"steps: {steps}"
subs = []
# smolagents 1.26 stores managed_agents as {name: agent}; guard the shape
# anyway so a hand-built/older agent can never turn the footer into an
# error (the helper is called inside each chat path's try/except).
managed = getattr(agent, "managed_agents", None)
if not isinstance(managed, dict):
return txt
# The label comes from the managed agent's NAME (the dict key β smolagents
# 1.26+ stores managed_agents as {name: agent}): RAG's
# knowledge_searcher / Deep Research's web_search_agent read as 'search',
# Data Analysis's data_worker reads as 'data worker', and an unknown
# name falls back to the generic 'worker'. The same helper serves all
# four agentic tabs, so the footer stays accurate now that a non-search
# managed agent exists.
for sub_name, sub in managed.items():
s = getattr(sub, "max_steps", None)
if s is not None:
name_l = str(sub_name or "").lower()
if "search" in name_l:
label = "search"
elif "data" in name_l:
label = "data worker"
else:
label = "worker"
subs.append(f"{s} {label}")
if subs:
txt += f" (+{'/'.join(subs)})"
return txt
def _agent_exec_timeout_txt(agent) -> str:
"""The EFFECTIVE per-step execution timeout (seconds) the built agent
actually runs with β read off the agent's Python executor
(agent.python_executor.timeout_seconds), which ONLY exists on a
CodeAgent. A ToolCallingAgent never executes Python, so it has no
executor and the footer must not claim a timeout β gating on the
executor's presence is exactly the 'when the tab runs a CodeAgent'
condition. Exception: the Data Analysis MANAGER is a ToolCallingAgent
whose Python executor lives on its managed `data_worker` CodeAgent β
when the agent itself has no executor, the helper falls through to its
managed agents before giving up. The executor's timeout_seconds is the
value the factory really applied: the explicit per-tab Exec timeout, or
smolagents' own 30s default when the control is on auto. Returns
'exec timeout: Ns' or '' when there is no executor / no timeout (never
breaks a footer on an odd/None agent)."""
if agent is None:
return ""
executor = getattr(agent, "python_executor", None)
if executor is None:
# A ToolCallingAgent manager whose Python executor lives on a
# managed CodeAgent sub-agent (the Data Analysis manager + its
# data_worker): surface the worker's executor timeout. All other
# tabs' managed agents are ToolCallingAgents too (no executor), so
# the fallthrough only ever fires for the Data Analysis tab.
managed = getattr(agent, "managed_agents", None)
if isinstance(managed, dict):
for sub in managed.values():
executor = getattr(sub, "python_executor", None)
if executor is not None:
break
if executor is None:
return ""
seconds = getattr(executor, "timeout_seconds", None)
if seconds is None:
return ""
return f"exec timeout: {int(seconds)}s"
# ββ Managed-sub-agent max-steps findings hand-off ββββββββββββββββββββββ
# When a managed sub-agent (Data Analysis's `data_worker`, Deep Research's
# `web_search_agent`, β¦) burns its whole step budget without emitting a
# real final_answer, smolagents' `_handle_max_steps_reached` fallback
# takes the model's RAW last-ditch text as the sub-agent's return β the
# manager then receives a leaked code fence / channel marker instead of
# the findings the sub-agent actually COMPUTED/GATHERED (the Muse Glimmer
# Data-leg failure; the same runs' DR search agent shipped `to=user<|eot|>`
# as its "final answer"). The REAL findings live in the sub-agent's
# ActionStep observations (the verbatim tool outputs). The two helpers
# below are the shared cure: collect the run's observations, and prefer
# them over the model's surrender at max steps. Both the data worker and
# the DR search agent instance-patch their `_handle_max_steps_reached`
# onto `max_steps_findings_handoff` at build time (see the *_agent.py
# builders).
def collect_agent_observations(agent, cap: int = 8000) -> str:
"""A managed sub-agent's run transcript β the verbatim tool outputs it
COMPUTED/GATHERED but never delivered via final_answer. Joins every
non-empty ActionStep observation in run order (list-shaped
observations flattened, exact duplicates dropped), capped at `cap`
chars. Returns '' when there is nothing meaningful. NEVER raises.
Shared by the Data Analysis `data_worker` (cap 8000 β its findings
are compact tables) and the Deep Research `web_search_agent` (larger
cap β its findings are verbatim search results / page contents)."""
try:
memory = getattr(agent, "memory", None)
steps = getattr(memory, "steps", None)
if not steps:
return ""
parts = []
seen = set()
for step in steps:
obs = getattr(step, "observations", None)
if isinstance(obs, list):
text = "\n".join(str(o) for o in obs if str(o).strip())
else:
text = str(obs or "")
text = text.strip()
if not text or text in seen:
continue
seen.add(text)
parts.append(text)
transcript = "\n\n".join(parts)
if len(transcript) > cap:
transcript = transcript[:cap]
return transcript.strip()
except Exception:
return ""
def max_steps_findings_handoff(self, task, cap: int = 8000):
"""The managed-sub-agent max-steps fallback (instance-patched onto the
sub-agent's `_handle_max_steps_reached` at build time): when
smolagents' stock handler produces the model's last-ditch raw-text
answer, prefer the run's REAL findings β the verbatim tool
observations β so the manager receives the computed/gathered content
instead of a leaked envelope or channel marker. Falls back to the
stock answer when there are no meaningful observations. NEVER raises."""
orig = getattr(self, "_orig_handle_max_steps_reached", None)
try:
model_answer = orig(task) if orig is not None else None
except Exception:
model_answer = None
findings = collect_agent_observations(self, cap=cap)
if findings:
return findings
return model_answer
def _build_abort_message(lang_key: str = "kh", diagnostics: Optional[dict] = None) -> str:
"""Bilingual fail-fast guidance message (see i18n 'agent_error_abort').
When the run's diagnostics carry a captured `last_error`, the ACTUAL
failing error (e.g. `KeyError: 'Quantity'`) is appended so the user sees
what really went wrong instead of a generic model-size guess β the
concrete cause is far more actionable than "try a bigger model"."""
l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
d = diagnostics or {}
if d.get("loop_detected"):
# Repetition-loop abort (see the loop guard section): the model
# kept re-emitting the SAME tool call even after the corrective
# nudge β surface the repeated call instead of an error guess.
msg = l.get("agent_loop_abort",
"β οΈ The model kept calling the same tool over and over β the run was stopped to save time.")
call = (d.get("loop_call") or "").strip()
if call:
label = l.get("agent_loop_abort_last_call", "Repeated tool call: {call}")
try:
label = label.format(call=call)
except (KeyError, ValueError):
label = f"Repeated tool call: {call}"
msg = f"{msg}\n\n{label}"
return msg
msg = l.get("agent_error_abort",
"β οΈ The model kept failing β the run was stopped to save time.")
err = d.get("last_error")
if err:
label = l.get("agent_abort_last_error", "Last error: {err}")
try:
label = label.format(err=err)
except (KeyError, ValueError):
label = f"Last error: {err}"
msg = f"{msg}\n\n{label}"
return msg
def _agent_abort_html(lang_key: str = "kh",
diagnostics: Optional[dict] = None) -> str:
"""Bilingual fail-fast abort badge + "Why did this happen?" expander
rendered by the chat handlers (chat.py / data_analysis.py) when the
fail-fast guard STOPPED the run. Returns '' for clean runs and for runs
that merely stumbled β those get chat.py's soft `_agent_failure_hint()`
footer instead. The abort message itself (`_build_abort_message`)
already carries the base guidance; this adds the visible badge and a
deeper explanation using the run's ACTUAL failure numbers
({max_consecutive_errors} consecutive errored steps out of
{total_steps}).
Shared here (not in chat.py) because Data Analysis also consumes the
streamed diagnostics and renders the same badge β one helper, one
place to update the UI treatment."""
d = diagnostics or {}
if not d.get("aborted"):
return ""
l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
if d.get("loop_detected"):
# Repetition-loop variant of the badge β the run was stopped because
# the model repeated the same tool call, not because steps failed.
badge = l.get("agent_loop_abort_badge", "β οΈ Loop detected β run stopped")
why = l.get("agent_abort_why", "π€ Why did this happen?")
explanation = l.get("agent_loop_abort_explanation", "")
if explanation:
try:
explanation = explanation.format(
steps=d.get("total_steps", 0) or 0,
call=d.get("loop_call") or "",
)
except (KeyError, ValueError):
# A future translation edit that leaves a stray {...} must
# never nuke the whole chat response into a traceback β keep
# the raw template text instead.
pass
last_call = (d.get("loop_call") or "").strip()
last_call_html = ""
if last_call:
label = l.get("agent_loop_abort_last_call", "Repeated tool call: {call}")
try:
label = label.format(call=last_call)
except (KeyError, ValueError):
label = f"Repeated tool call: {last_call}"
last_call_html = (
f'\n<div class="agent-err-box"><b>{label}</b></div>'
)
return (
"\n\n" +
f'<div class="abort-badge">{badge}</div>\n'
f'<details class="abort-details">\n'
f'<summary class="agent-step-summary">{why}</summary>\n'
f'<div class="agent-log-block">\n'
f'<div class="agent-err-box">{explanation}</div>\n'
f'{last_call_html}\n'
f'</div>\n</details>'
)
badge = l.get("agent_abort_badge", "β οΈ Run stopped early")
why = l.get("agent_abort_why", "π€ Why did this happen?")
explanation = l.get("agent_abort_explanation", "")
if explanation:
try:
explanation = explanation.format(
errors=d.get("max_consecutive_errors", 0) or 0,
steps=d.get("total_steps", 0) or 0,
)
except (KeyError, ValueError):
# A future translation edit that leaves a stray {...} must never
# nuke the whole chat response into a traceback β keep the raw
# template text instead.
pass
last_error = (d.get("last_error") or "").strip()
last_error_html = ""
if last_error:
err_label = l.get("agent_abort_last_error", "Last error: {err}")
try:
err_label = err_label.format(err=last_error)
except (KeyError, ValueError):
err_label = f"Last error: {last_error}"
last_error_html = (
f'\n<div class="agent-err-box"><b>{err_label}</b></div>'
)
return (
"\n\n" +
f'<div class="abort-badge">{badge}</div>\n'
f'<details class="abort-details">\n'
f'<summary class="agent-step-summary">{why}</summary>\n'
f'<div class="agent-log-block">\n'
f'<div class="agent-err-box">{explanation}</div>\n'
f'{last_error_html}\n'
f'</div>\n</details>'
)
def chunk_final_text(response: str, min_chars: int = 400,
chunk_chars: int = 320) -> list:
"""Split a long final response into display chunks for a progressive
(streamed-looking) reveal in the chatbot β the generation itself
completes before the reveal, but rendering the finished text in
growing slices makes long answers feel substantially faster. Short
responses return a single chunk (no change). Newline-aware so
markdown structure isn't shredded; a single over-long line (no
newlines) falls back to hard slicing."""
if not response:
return [""]
if len(response) <= min_chars:
return [response]
lines = response.split("\n")
chunks, cur = [], ""
for i, ln in enumerate(lines):
# Keep the trailing newline on each piece (except the very last
# line) so "".join(chunks) reconstructs the original exactly β
# dropping it at flush boundaries would shred the markdown.
piece = ln + ("" if i == len(lines) - 1 else "\n")
if cur and len(cur) + len(piece) > chunk_chars:
chunks.append(cur)
cur = piece
else:
cur += piece
if cur:
chunks.append(cur)
if len(chunks) == 1 and len(chunks[0]) > min_chars:
return [chunks[0][i:i + chunk_chars]
for i in range(0, len(chunks[0]), chunk_chars)]
return chunks
def stream_agent_steps(agent, task: str, reset: bool = True,
lang_key: str = "kh"):
"""Run `agent` on `task`, yielding live steps as they happen.
See this module's docstring for the full (step_msg, is_final,
final_output, diagnostics) contract every caller in this app relies on.
In addition to that contract, this run is guarded by the fail-fast
mechanism: `_ERROR_ABORT_THRESHOLD` consecutive errored steps abort the
run early with bilingual guidance (yielded as the final message). A second guard, the repetition-loop guard, catches the model that repeats
the SAME successful tool call over and over: on `_LOOP_NUDGE_THRESHOLD`
identical consecutive calls it first injects a corrective reminder into
the agent's memory (nudging the model to use the data it already has),
and aborts with bilingual guidance if the same call repeats after that.
A second detector within the same guard keys on the coarser
same-tool + same-file fingerprint (parsed from the code / call
arguments, paths normalized), so a model that keeps re-reading the SAME
data file with the SAME tool while varying the surrounding code is
caught too β each variant's full signature differs, but the file
fingerprint collapses them.
Each FINAL yield carries a snapshot of the run's diagnostics dict
(total_steps / max_consecutive_errors / aborted / last_error) as its
4th element,
so callers never need to read `get_last_run()` after the loop β see
chat.py's `_agent_failure_hint()`. Intermediate yields carry None
there. The thread-local `get_last_run()` remains the internal backing
store (and a debugging surface), updated in place as steps arrive.
"""
# Reset the per-thread diagnostics FIRST, before any code path (including
# the no-streaming TypeError fallback below) so a run can never leave or
# inherit stale failure data from a previous run on this thread.
last_run = get_last_run()
last_run.update({"total_steps": 0, "max_consecutive_errors": 0, "aborted": False,
"last_error": "", "loop_detected": False, "loop_call": ""})
try:
run_result = agent.run(task, reset=reset, stream=True)
except TypeError:
# Installed smolagents version doesn't accept stream= at all β
# fall back to a single blocking call. No live steps, but the
# caller still gets a real final answer.
try:
result = agent.run(task, reset=reset)
except Exception as e:
err_msg = {"role": "assistant", "content": _step_error_bubble(e, lang_key)}
yield err_msg, True, _step_error_text(e, lang_key), dict(last_run)
return
yield None, True, result, dict(last_run)
return
# Tracks the most recent item that did NOT look like a full memory
# step (ActionStep/PlanningStep/...). smolagents' own convention is
# that the plain final answer is the last thing the stream yields
# (see module docstring) β but some smolagents versions ALSO stream
# finer-grained intermediate objects mid-run (e.g. raw ToolCall
# objects, or streamed text-delta chunks) that are NOT the final
# answer either, just noise to skip rather than display. A single
# item's type alone can't tell us which case we're in β only once
# the generator is fully exhausted do we know "the very last thing
# it ever yielded" is genuinely the final answer, rather than a
# preview of a step still to come. Finalizing on the FIRST
# unrecognized item (an earlier version of this function did this)
# incorrectly ended runs the moment ANY such intermediate object
# appeared β sometimes after a single step β producing garbage like
# a raw "ToolCall(name=..., arguments=...)" repr as the "final
# answer" instead of letting the agent actually finish researching.
candidate_final = None
consecutive_errors = 0
# Repetition-loop guard state (see the fail-fast section above): the
# signature of the most recently executed tool call, how many
# consecutive times it has repeated, and which signature has already
# received the corrective nudge β a signature may only be nudged once;
# a repeat AFTER the nudge means the model is truly stuck β abort.
prev_call_sig = None
call_repeat_count = 0
nudge_sent_for = None
# Same-tool + same-file channel state (the coarser second detector):
# which (tool, file) fingerprint the previous step touched, how many
# consecutive times it has repeated, and which fingerprint already
# received the corrective nudge β a fingerprint may only be nudged
# once; a repeat AFTER the nudge means the model is truly stuck.
prev_file_fp = None
file_repeat_count = 0
file_nudge_sent_for = None
last_item = None
try:
try:
for item in run_result:
last_item = item
# FinalAnswerStep (present in some newer smolagents
# versions) is an EXPLICIT, unambiguous signal β it wraps
# the actual completed final answer, so it's safe to act
# on immediately instead of waiting for the generator to
# end.
if item.__class__.__name__ == "FinalAnswerStep":
final_answer = getattr(item, "final_answer", None)
if final_answer is None:
final_answer = getattr(item, "output", item)
# The max-steps fallback (provide_final_answer) can
# deliver the model's RAW tool-call text as the final
# answer (e.g. `call:final_answer{answer: "β¦"}`) with no
# parsing β unwrap the leaked envelope so the bubble
# shows the report, not the call syntax.
yield None, True, _unwrap_leaked_final_answer(final_answer), dict(last_run)
return
if _is_memory_step(item):
last_run["total_steps"] += 1
msg_text = _format_step(item, lang_key)
if msg_text is not None:
yield {"role": "assistant", "content": msg_text}, False, None, None
# Fail-fast guard: consecutive errored steps mean the
# model is stuck (parse failures, tool exceptions,
# rejected final answers) β abort with guidance instead
# of burning the remaining step budget.
if getattr(item, "error", None):
consecutive_errors += 1
last_run["max_consecutive_errors"] = max(
last_run["max_consecutive_errors"], consecutive_errors)
last_run["last_error"] = _error_snippet(item.error)
if consecutive_errors >= _ERROR_ABORT_THRESHOLD:
last_run["aborted"] = True
abort_msg = _build_abort_message(lang_key, dict(last_run))
yield ({"role": "assistant", "content": abort_msg},
True, abort_msg, dict(last_run))
return
else:
consecutive_errors = 0
# Repetition-loop guard: identical consecutive tool
# calls (SUCCESSFUL ones β the error guard above owns
# failed steps) mean the model is in the degenerate
# repeat-the-same-call loop that burns the whole step
# budget one slow generation at a time before
# surrendering with meta-commentary. Nudge once (the
# fresh context breaks the deterministic
# re-generation); abort if it still repeats after that.
sig = _tool_calls_signature(item)
if sig is None:
# No readable tool call (final-answer step, parse
# failure) β BOTH loop channels stand down.
prev_call_sig = None
call_repeat_count = 0
prev_file_fp = None
file_repeat_count = 0
file_nudge_sent_for = None
else:
# The coarser same-tool + same-file fingerprint is
# computed up front so the exact channel can hand
# its nudge off to it (see below).
ffp = _file_access_fingerprint(item)
if sig == prev_call_sig:
call_repeat_count += 1
else:
prev_call_sig = sig
call_repeat_count = 1
nudge_sent_for = None
if call_repeat_count >= _LOOP_NUDGE_THRESHOLD:
if nudge_sent_for != sig:
nudge_sent_for = sig
# The exact nudge covers this repeated file
# operation too β record it so the file
# channel below treats a later same-file
# repeat as 'after the nudge' β abort,
# instead of nudging twice for the same
# underlying loop.
if ffp is not None:
file_nudge_sent_for = ffp
if _inject_loop_nudge(agent, lang_key):
yield ({"role": "assistant",
"content": _loop_nudge_bubble(lang_key)},
False, None, None)
else:
last_run["aborted"] = True
last_run["loop_detected"] = True
last_run["loop_call"] = _signature_call_names(sig)
abort_msg = _build_abort_message(lang_key, dict(last_run))
yield ({"role": "assistant", "content": abort_msg},
True, abort_msg, dict(last_run))
return
else:
# Same-tool + same-file channel: a model stuck
# re-reading the SAME data file with the SAME
# tool while varying the surrounding code (each
# variant's full signature differs, so the
# exact channel above can't see the loop) is
# caught here by the coarser
# (tool, path, effective-args) fingerprint.
# Same nudge-once-then-abort lifecycle.
if ffp is None:
prev_file_fp = None
file_repeat_count = 0
else:
if ffp == prev_file_fp:
file_repeat_count += 1
else:
prev_file_fp = ffp
file_repeat_count = 1
file_nudge_sent_for = None
if file_repeat_count >= _LOOP_NUDGE_THRESHOLD:
if file_nudge_sent_for != ffp:
file_nudge_sent_for = ffp
if _inject_loop_nudge(agent, lang_key):
yield ({"role": "assistant",
"content": _loop_nudge_bubble(lang_key)},
False, None, None)
else:
last_run["aborted"] = True
last_run["loop_detected"] = True
last_run["loop_call"] = _file_fp_call_names(ffp)
abort_msg = _build_abort_message(lang_key, dict(last_run))
yield ({"role": "assistant", "content": abort_msg},
True, abort_msg, dict(last_run))
return
# Intra-run memory guard: a long single-run research
# (many web-search observations) can grow the manager's
# memory past the model's context window MID-RUN β
# llama-server then 400s every further step
# (exceed_context_size_error) and the run dies without
# an answer. Trim older/bloated steps BEFORE the next
# prompt is built when the estimate crosses the budget.
try:
from agents.agent_memory import guard_memory_within_run
guard_memory_within_run(agent)
except Exception:
pass
# A genuine step just happened β the agent is clearly
# still going, so any unrecognized "final answer
# candidate" picked up right before this was just
# noise from an earlier in-progress step, not the
# real final answer. Discard it.
candidate_final = None
continue
# Not a recognized memory-step type. Could be the plain
# final answer (the normal end-of-stream case), or it
# could be an intermediate delta/tool-call object some
# smolagents versions stream mid-step. Don't decide yet β
# remember it and keep iterating; see candidate_final's
# declaration above for why.
candidate_final = item
# The generator is genuinely exhausted now β whatever the
# LAST unrecognized item was (if any) is the real final
# answer.
if candidate_final is not None:
final_text = _unwrap_leaked_final_answer(candidate_final)
if _rejected_at_delivery(final_text):
# The max-steps fallback (or a leaked non-answer) β
# never ship it; see _rejected_at_delivery's docstring.
last_run["aborted"] = True
last_run["last_error"] = "final answer rejected at delivery"
bubble = _rejected_answer_bubble(lang_key)
yield ({"role": "assistant", "content": bubble},
True, bubble, dict(last_run))
return
yield None, True, final_text, dict(last_run)
elif last_item is not None:
# Every single item the whole run ever yielded was a
# recognized memory step (no bare final answer ever
# appeared, unusual but possible on some versions) β
# fall back to that last step's own text rather than
# yielding nothing.
fallback_text = _format_step(last_item, lang_key) or ""
if _rejected_at_delivery(fallback_text):
last_run["aborted"] = True
last_run["last_error"] = "final answer rejected at delivery"
bubble = _rejected_answer_bubble(lang_key)
yield ({"role": "assistant", "content": bubble},
True, bubble, dict(last_run))
return
yield None, True, fallback_text, dict(last_run)
else:
yield None, True, "", dict(last_run)
except Exception as e:
err_msg = {"role": "assistant", "content": _step_error_bubble(e, lang_key)}
yield err_msg, True, _step_error_text(e, lang_key), dict(last_run)
return
finally:
# See this function's matching comment above the `try:` this is
# attached to (module docstring section on version compatibility)
# β proactively close the underlying smolagents step generator
# ourselves, synchronously, rather than leaving it for CPython's
# garbage collector to close at some later, unpredictable point.
# If `run_result` was abandoned mid-iteration (an early `return`
# above, after an error or once the final answer arrived), Python
# will eventually GC it and call its own `.close()`, sending it a
# GeneratorExit. Some smolagents versions' internal
# `MultiStepAgent._run_stream` generator doesn't handle that
# cleanly β it keeps yielding instead of stopping β which raises
# "RuntimeError: generator ignored GeneratorExit", printed by the
# interpreter as a scary but harmless "Exception ignored in: ..."
# warning during cleanup (it does not propagate into this app's
# own control flow or crash the run β the real answer above has
# already been yielded by this point). Closing it here instead,
# while we still hold a live reference to it, and swallowing that
# specific error, prevents the noisy warning entirely.
try:
run_result.close()
except RuntimeError:
pass
except Exception:
pass
"""
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 = ()