aiagent.org logo aiagent.org
⚡ Code-as-Action • Hugging Face Smolagents • AST Whitelist Sandbox

Smolagents: Code-as-Action (CodeAgent) Architecture

Why having LLMs emit executable Python action blocks (`CodeAgent`) instead of rigid JSON tool-call envelopes cuts multi-step reasoning turns by 60%—and how to secure execution with AST walkers and Pyodide/MicroVM sandboxes.

⚡ CodeAgent vs. JSON ToolCallingAgent Benchmark
Dimension CodeAgent (Python Code-as-Action) ToolCallingAgent (JSON Schema RPC)
Control Flow & Composability Native Python: `for` loops, list comprehensions, `if/else`, and variable chaining in 1 turn. Sequential Round-Trips: Requires a new LLM completion after every single tool output to transform data.
Avg LLM Turns (5-Tool Pipeline) 1 – 2 LLM turns (60% fewer tokens) 5 – 6 LLM turns (cumulative context re-read)
Security & Isolation Boundary Requires AST import allowlisting + E2B Firecracker MicroVM or Pyodide WASM sandbox. Strict JSON Schema argument validation + OAuth 2.1 scope check at gateway.

01 Building an AST-Guarded CodeAgent Executor in 35 Lines of Python

import ast

ALLOWED_AST_NODES = {
    ast.Module, ast.Assign, ast.Expr, ast.Call, ast.Name, ast.Load, ast.Store,
    ast.Constant, ast.List, ast.Dict, ast.ListComp, ast.comprehension,
    ast.For, ast.If, ast.Compare, ast.BinOp, ast.Add, ast.Sub, ast.Mult, ast.Div
}

def execute_safe_code_action(code_snippet: str, bound_tools: dict):
    tree = ast.parse(code_snippet, mode="exec")
    for node in ast.walk(tree):
        if type(node) not in ALLOWED_AST_NODES:
            raise SecurityError(f"AST_VIOLATION: Forbidden syntax node {type(node).__name__}")
        if isinstance(node, ast.Name) and node.id.startswith("__"):
            raise SecurityError("AST_VIOLATION: Dunder attribute access blocked")

    sandbox_locals = {}
    safe_globals = {"__builtins__": {"len": len, "min": min, "max": max, "sum": sum, "sorted": sorted}, **bound_tools}
    exec(compile(tree, filename="", mode="exec"), safe_globals, sandbox_locals)
    return sandbox_locals.get("final_answer")