Spaces:
Paused

assistant / agents /agent_factory.py
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
20.3 kB
"""
agent_factory.py β€” Shared smolagents agent-construction helpers.
Every agentic tab in the app (General Chat, RAG Chat, Deep Research, Data
Analysis) builds its smolagents agent(s) with the same version-compat
dance:
1. Pick ToolCallingAgent vs CodeAgent (either explicitly, or via a
per-tab tool-calling heuristic).
2. Sniff the installed smolagents version's `__init__` parameters with
`inspect.signature()` to learn which OPTIONAL kwargs it accepts
(`code_block_tags`, `instructions`, `executor_kwargs`,
`final_answer_checks`, ...) so a missing parameter silently no-ops
instead of crashing with an unexpected-keyword error.
3. Construct the agent.
Centralizing that here means a smolagents API change is fixed in ONE
place instead of four β€” see also AGENTS.md's "the app must always launch,
on any environment, and degrade gracefully" guidance.
"""
import importlib.resources
import inspect
import re
from typing import Optional
import yaml
from smolagents import CodeAgent, ToolCallingAgent
def reject_leaked_or_empty_final_answer(final_answer, *_, **__) -> bool:
"""Shared `final_answer_checks` validator attached to EVERY agent built
here (merged with any per-tab checks, e.g. Deep Research's report
validator). Rejects a final answer that is:
1. empty/blank β€” the model produced nothing usable;
2. a leaked raw ReAct 'Action: {…}' tool-call envelope (the failure
mode the agent_streaming parser recovery fixes at parse time β€”
this check catches any that slip through to the answer);
3. the repr of an internal object (ToolCall(...) / '<...>') instead
of real answer text;
4. chat-template control-token garbage (e.g. Muse Glimmer's
"to=user<|eot|>" channel-close fragment) β€” an answer that is
pure template tokens, i.e. becomes empty once the known control
tokens are stripped, is not an answer;
5. degenerate token repetition ("skills skills skills …" forever β€”
the broken-generation loop observed when a text request landed
on an EMBEDDING model through a shared llama-server port). An
answer that IS the loop is not an answer.
6. a pure execution-planning monologue β€” the GLM Deep Research leak
where the manager called final_answer() with its INTERNAL PLAN
("The user wants me to proceed with the plan I outlined. Let me
execute the plan step by step … Let me start with searching …")
instead of an actual report. A SHORT answer opening with
first-person execution-planning phrasing is meta-commentary,
not findings.
smolagents runs each check against the proposed final answer before
accepting it and feeds a rejection back to the model for one more
attempt, so this guards answer quality at the source for every agentic
tab. Signature matches smolagents' invocation
`check_function(final_answer, memory, agent=self)`."""
text = str(final_answer or "").strip()
if not text:
return False
if re.match(r"^\s*Action:?\s*\{", text, re.DOTALL | re.IGNORECASE):
return False
if (text.startswith("ToolCall(") or text == "None"
or text.startswith("<smolagents")
or text.startswith("<class ") or text.startswith("<built-in ")):
return False
# Chat-template control-token garbage (the Muse Glimmer leak observed
# end-to-end: the model wrote its template's channel-close fragment
# "to=user<|eot|>" as the WHOLE final-answer payload). Strip the known
# tokens (agent_streaming.strip_template_tokens); an answer that
# becomes EMPTY was pure template garbage and is rejected β€” smolagents
# then feeds the rejection back for one more attempt β€” never shipped
# as the answer bubble.
try:
from agents.agent_streaming import strip_template_tokens, _strip_deliberation_preamble
cleaned = strip_template_tokens(text).strip()
cleaned = _strip_deliberation_preamble(cleaned).strip()
except Exception:
cleaned = text
if not cleaned:
return False
# The strip can also leave a bare role word ("<|im_start|>user<|im_end|>"
# β†’ "user") β€” still not an answer.
if cleaned.lower() in ("user", "assistant", "system", "tool", "self"):
return False
# Degenerate token repetition (case 5): reject so smolagents feeds the
# rejection back for another attempt instead of shipping thousands of
# repeated tokens as the answer.
try:
from agents.agent_streaming import is_degenerate_repetition
if is_degenerate_repetition(cleaned):
return False
except Exception:
pass
# Pure execution-planning / deliberation monologue (case 6): the GLM
# ("The user wants me to proceed with the plan I outlined. Let me
# execute …", or Khmer meta-plan "αž‚αŸ„αž›αž€αžΆαžšαžŽαŸαžŠαžΎαž˜αŸ’αž”αžΈαžŠαŸ„αŸ‡αžŸαŸ’αžšαžΆαž™ ... αž”αŸ’αžšαžΎαž§αž”αž€αžšαžŽαŸ summarize_theme")
# and Muse-Glimmer ("We need more detailed info … Let's call web_search_agent for host cities …")
# leaks β€” the manager called final_answer() with its INTERNAL DELIBERATION
# or SOLVING PLAN instead of a report. Detectors:
# a) the text OPENS with first-person execution-planning phrasing;
# b) the text contains explicit meta-planning headings/sections
# (e.g. αž‚αŸ„αž›αž€αžΆαžšαžŽαŸαžŠαžΎαž˜αŸ’αž”αžΈαžŠαŸ„αŸ‡αžŸαŸ’αžšαžΆαž™, αž•αŸ‚αž“αž€αžΆαžšαžŠαŸ„αŸ‡αžŸαŸ’αžšαžΆαž™, Facts survey:, Plan of action:);
# c) the text discusses CALLING or using sub-agent/retriever tools in prose
# (e.g. let's call knowledge_searcher, αž”αŸ’αžšαžΎαž§αž”αž€αžšαžŽαŸ summarize_theme);
# d) short unstructured text mentioning sub-agent names.
if len(cleaned) < 4000:
low = cleaned.lower()
planning_openers = (
"the user wants", "the user is asking", "the user asked", "the user's question is",
"the user asked for",
"we need to", "we need more", "we need who", "we have retrieved", "we have findings",
"we have some info", "we have search results",
"let me execute", "let me proceed", "let me start", "let me search", "let me break down",
"let's call", "lets call", "let's search", "let's list", "lets list",
"i'll start by", "i will start by", "first, i need to", "first, i'll", "first i need to",
"i will compile the answer", "i will write the response", "the search results provide",
"the task:", "the task is",
"αžŠαŸ†αž”αžΌαž„ αžαŸ’αž‰αž»αŸ†αžαŸ’αžšαžΌαžœ", "αž‡αžΆαžŠαŸ†αž”αžΌαž„ αžαŸ’αž‰αž»αŸ†αžαŸ’αžšαžΌαžœ", "αžαŸ’αž‰αž»αŸ†αž“αžΉαž„αž…αžΆαž”αŸ‹αž•αŸ’αžαžΎαž˜", "αž™αžΎαž„αžαŸ’αžšαžΌαžœαžαŸ‚", "αž™αžΎαž„αžαŸ’αžšαžΌαžœαž€αžΆαžš",
"αž’αŸ’αž“αž€αž”αžΆαž“αžŸαž½αžšαžαžΆ", "αžŸαŸ†αžŽαž½αžšαžšαž”αžŸαŸ‹αž’αŸ’αž“αž€αž”αŸ’αžšαžΎαŸ–",
)
if any(low.startswith(op) for op in planning_openers):
return False
# Meta-planning sections in Khmer or English (e.g. GLM-4.7-Flash plan leak)
meta_plan_markers = (
"αž‚αŸ„αž›αž€αžΆαžšαžŽαŸαžŠαžΎαž˜αŸ’αž”αžΈαžŠαŸ„αŸ‡αžŸαŸ’αžšαžΆαž™", "αž•αŸ‚αž“αž€αžΆαžšαžŠαŸ„αŸ‡αžŸαŸ’αžšαžΆαž™", "αž•αŸ‚αž“αž€αžΆαžšαžŸαž€αž˜αŸ’αž˜αž—αžΆαž–", "αž•αŸ‚αž“αž€αžΆαžšαž’αž“αž»αžœαžαŸ’αž",
"facts survey:", "plan of action:", "facts to look up:", "facts to derive:",
"part 1 (facts survey)", "part 2 (plan)", "analyze the request:",
)
if any(marker in low for marker in meta_plan_markers):
return False
# Tool calling deliberation / invocation phrases in prose
tool_deliberation_markers = (
"let's call knowledge_searcher", "let's call web_search_agent",
"lets call knowledge_searcher", "lets call web_search_agent",
"we can use knowledge_searcher", "could summarize documents or search",
"better to search", "possibly search for", "we should diversify queries",
"calling tools:", "calling tool:",
"αž”αŸ’αžšαžΎαž§αž”αž€αžšαžŽαŸ summarize_", "αž”αŸ’αžšαžΎαž§αž”αž€αžšαžŽαŸ knowledge_searcher",
"αž”αŸ’αžšαžΎαž§αž”αž€αžšαžŽαŸ retriever", "αž”αŸ’αžšαžΎαž§αž”αž€αžšαžŽαŸ list_",
)
if any(marker in low for marker in tool_deliberation_markers):
return False
if len(cleaned) < 2500:
sub_agent_tools = (
"web_search_agent", "knowledge_searcher", "data_worker",
"playwright_visualizer",
)
if any(name in low for name in sub_agent_tools):
if any(verb in low for verb in ("call", "calling", "invoke", "use", "task:", "agent", "αž”αŸ’αžšαžΎ")):
if not (any(marker in cleaned for marker in ("\n#", "\n-", "\n*")) and ("### references" in low or "## references" in low or len(cleaned) > 1500)):
return False
return True
def supports_native_tool_calls(llm) -> bool:
"""Default tool-calling policy: prefer ToolCallingAgent for every model.
TransformersModel, LlamaCppModel, LiteLLMModel and InferenceClientModel
all get reliable structured tool execution without code-parsing errors;
CodeAgent remains the choice for Data Analysis where Python execution is
required. Tabs with a stricter heuristic pass their own predicate via
build_smol_agent(tool_calling_predicate=...).
"""
return True
# ──────────────────────────────────────────────────────────────────
# Trimmed default prompt templates.
#
# smolagents' default CodeAgent / ToolCallingAgent system prompts ship a
# ~5-8K-char block of five worked examples using NOTIONAL tools
# (`document_qa`, `image_generator`, `translator`, `wikipedia_search`, …)
# that don't exist on any of this app's agents. For small quantized GGUF
# models (e.g. Gemma-4-E2B QAT q4_0 β€” this app's default) run through
# llama-cpp-python, that huge instruction blob β€” not any provider-specific
# template rendering, which is byte-identical across backends (verified
# against the transformers `apply_chat_template` render) β€” is the main
# reason a weak model gets overwhelmed and starts "answering the system
# prompt" instead of the user question. The strip below drops the worked
# examples while keeping the essential agent grammar: the
# Thought/Code/Observation cycle, the tools code-block, the rules, and the
# `custom_instructions` slot (where the app's per-tab instructions land).
#
# `prompt_templates=` REPLACES the whole default dict (smolagents asserts
# all keys present), so the trim operates on a copy of the real default
# YAML and returns the full dict β€” keeping `planning` / `managed_agent` /
# `final_answer` templates intact so planning and managed-agent prompts
# are untouched. The strip is defensive: if a future smolagents renames
# the example markers, the unmatched text is returned unchanged (the
# agent then uses the stock template rather than crashing).
# ──────────────────────────────────────────────────────────────────
_EXAMPLES_HEADER = "Here are a few examples using notional tools:"
# Both default YAMLs close the examples block with a line like
# "Above example(s) were using notional tools ... You only have access
# to these tools ..." β€” cut up to (not including) that line so the tools
# list intro stays put.
_EXAMPLES_CLOSE_RE = re.compile(r"\n\s*Above examples? were using notional tools", re.IGNORECASE)
def trim_worked_examples(system_prompt: str) -> str:
"""Strip smolagents' default worked-examples block from a system prompt.
Keeps the header/cycle description and everything from the "Above
examples were using notional tools" line onward (the tools block, the
rules, and the `{{custom_instructions}}` slot). Returns the text
unchanged if the example markers aren't found (future smolagents
template change β€” degrade gracefully).
"""
start = system_prompt.find(_EXAMPLES_HEADER)
if start == -1:
return system_prompt
close = _EXAMPLES_CLOSE_RE.search(system_prompt[start:])
if not close:
return system_prompt
end = start + close.start()
return system_prompt[:start].rstrip() + "\n\n" + system_prompt[end:].lstrip()
# smolagents' code_agent.yaml is chosen by CodeAgent (unless
# use_structured_outputs_internally, which this factory never sets);
# toolcalling_agent.yaml by ToolCallingAgent. Mirrors the exact resource
# loading in each class's `__init__`.
_TRIMMED_TEMPLATES_CACHE: dict = {}
def build_trimmed_prompt_templates(agent_class) -> Optional[dict]:
"""The default smolagents prompt-templates dict for `agent_class`,
with the worked-examples block stripped from its system prompt.
Returns the FULL dict (system_prompt + planning + managed_agent +
final_answer) so passing it as `prompt_templates=` satisfies
smolagents' required-keys assertion. Cached per class β€” the YAML is
read once. Returns None only for an unknown agent class (callers then
fall back to smolagents' stock templates).
"""
cached = _TRIMMED_TEMPLATES_CACHE.get(agent_class)
if cached is not None:
return cached
if issubclass(agent_class, CodeAgent):
yaml_name = "code_agent.yaml"
elif issubclass(agent_class, ToolCallingAgent):
yaml_name = "toolcalling_agent.yaml"
else:
_TRIMMED_TEMPLATES_CACHE[agent_class] = None
return None
templates = yaml.safe_load(
importlib.resources.files("smolagents.prompts")
.joinpath(yaml_name)
.read_text(encoding="utf-8")
)
assert isinstance(templates, dict), "smolagents prompt YAML must be a dict"
templates["system_prompt"] = trim_worked_examples(templates["system_prompt"])
_TRIMMED_TEMPLATES_CACHE[agent_class] = templates
return templates
def init_params(agent_class) -> dict:
"""All `__init__` parameter names accepted by `agent_class`, INCLUDING
those declared on base classes ({} if uninspectable).
smolagents subclasses (CodeAgent / ToolCallingAgent) accept inherited
arguments such as `instructions` (declared on MultiStepAgent.__init__) by
forwarding **kwargs to the base, so inspecting only the subclass's own
`__init__` signature would MISS them β€” and the version-compat guard below
would silently drop the system prompt. Unioning the whole MRO keeps the
sniff correct across smolagents versions: a parameter declared directly
on the subclass (older versions) or on a base (1.26+) is detected either
way.
Also used directly by callers that build a kwargs dict themselves but
still want the single shared signature-sniffing implementation (e.g.
Deep Research's search sub-agent)."""
if not isinstance(agent_class, type):
agent_class = type(agent_class) # tolerate instances (getmro needs a class)
params = {}
for klass in inspect.getmro(agent_class):
try:
params.update(inspect.signature(klass.__init__).parameters)
except (TypeError, ValueError):
continue
return params
def build_smol_agent(llm, *,
tools=None,
max_steps: int,
agent_class=None,
use_tool_calling: bool = True,
tool_calling_predicate=supports_native_tool_calls,
instructions=None,
execution_timeout=None,
verbosity_level: int = 1,
extra_kwargs=None,
optional_kwargs=None):
"""Build a smolagents CodeAgent or ToolCallingAgent with the shared
version-compat guards.
Tool calling is the DEFAULT for every agent (ToolCallingAgent) β€”
structured function-calling avoids the code-parsing failure modes of
CodeAgent (e.g. "Code parsing failed ... invalid character 'β€”'" on
small GGUF models copying scraped prose into Python blocks).
Args:
llm: the smolagents-compatible Model (from models.get_llm()).
tools: iterable of tools to attach to the agent.
max_steps: step budget.
agent_class: force a specific class (e.g. ToolCallingAgent for the
Deep Research search sub-agent); defaults to picking from
use_tool_calling + tool_calling_predicate.
use_tool_calling: prefer ToolCallingAgent when True (the default).
Set False ONLY for tabs that require Python code execution
(Data Analysis) β€” see data_analysis.py.
tool_calling_predicate: per-tab heuristic deciding whether the
model supports native tool calling.
instructions: system instructions β€” attached ONLY when this
smolagents version's __init__ exposes an `instructions=` param.
execution_timeout: per-step code-executor timeout in seconds,
passed as `executor_kwargs` when supported and > 0.
verbosity_level: smolagents verbosity (default 1).
extra_kwargs: additional kwargs merged UNCONDITIONALLY
(e.g. name/description/planning_interval/managed_agents).
optional_kwargs: additional kwargs merged only for keys this
smolagents version actually accepts (e.g. final_answer_checks).
"""
if agent_class is None:
use_tc = use_tool_calling and tool_calling_predicate(llm)
agent_class = ToolCallingAgent if use_tc else CodeAgent
params = init_params(agent_class)
kwargs = dict(
model=llm,
tools=list(tools or []),
max_steps=max_steps,
verbosity_level=verbosity_level,
)
if extra_kwargs:
kwargs.update(extra_kwargs)
# Version-guarded optional kwargs:
# - CodeAgent expects fenced ```python blocks by default; the
# markdown-fence convention is more broadly compatible with the
# outputs of GGUF / "thinking"-tuned models.
# - Trimmed prompt templates: smolagents' default system prompt ships
# ~5-8K chars of worked examples using NOTIONAL tools that don't
# exist on this app's agents. For small quantized GGUF models the
# huge instruction blob is the main cause of the model "answering
# the system prompt" β€” strip it at construction, uniformly for every
# provider/backend (llama-cpp-python, llama-server, transformers,
# HF API, LiteLLM) since all agents are built through this factory.
if agent_class is CodeAgent and "code_block_tags" in params:
kwargs["code_block_tags"] = "markdown"
if "prompt_templates" in params:
trimmed = build_trimmed_prompt_templates(agent_class)
if trimmed is not None:
kwargs["prompt_templates"] = trimmed
if instructions is not None and "instructions" in params:
kwargs["instructions"] = instructions
if execution_timeout is not None and execution_timeout > 0 and "executor_kwargs" in params:
kwargs["executor_kwargs"] = {"timeout_seconds": execution_timeout}
if optional_kwargs:
for k, v in optional_kwargs.items():
if k not in params or k == "final_answer_checks":
continue # final_answer_checks is merged separately below
kwargs[k] = v
# Shared final-answer hygiene check on EVERY agent, merged with any
# per-tab checks the caller passed (e.g. Deep Research's report
# validator) so both run. smolagents feeds a rejection back to the
# model for one more attempt, so a leaked/empty answer costs a step
# (bounded by the fail-fast guard in agent_streaming) instead of
# silently becoming the result.
if "final_answer_checks" in params:
checks = [reject_leaked_or_empty_final_answer]
if optional_kwargs and optional_kwargs.get("final_answer_checks"):
checks += list(optional_kwargs["final_answer_checks"])
kwargs["final_answer_checks"] = checks
return agent_class(**kwargs)