huggingface/smolagents · error · InterpreterError
Code parsing failed on line {e.lineno} due to: {type(e).__na
Error message
Code parsing failed on line {e.lineno} due to: {type(e).__name__}: {str(e)}\n{e.text}{' ' * (e.offset or 0)}^ What it means
evaluate_python_code first parses the code string with ast.parse; if the LLM or caller supplies syntactically invalid Python, the SyntaxError is re-raised as InterpreterError including line number, message, the offending line, and a caret marker. This gives precise feedback that can be fed back to the model for self-correction. It fires before any execution begins.
Source
Thrown at src/smolagents/local_python_executor.py:1617
code (`str`):
The code to evaluate.
static_tools (`Dict[str, Callable]`):
The functions that may be called during the evaluation. These can also be agents in a multiagent setting.
These tools cannot be overwritten in the code: any assignment to their name will raise an error.
custom_tools (`Dict[str, Callable]`):
The functions that may be called during the evaluation.
These tools can be overwritten in the code: any assignment to their name will overwrite them.
state (`Dict[str, Any]`):
A dictionary mapping variable names to values. The `state` should contain the initial inputs but will be
updated by this function to contain all variables as they are evaluated.
The print outputs will be stored in the state under the key "_print_outputs".
timeout_seconds (`int`, *optional*, defaults to `MAX_EXECUTION_TIME_SECONDS`):
Maximum time in seconds allowed for code execution. Set to `None` to disable timeout.
"""
try:
expression = ast.parse(code)
except SyntaxError as e:
raise InterpreterError(
f"Code parsing failed on line {e.lineno} due to: {type(e).__name__}: {str(e)}\n"
f"{e.text}"
f"{' ' * (e.offset or 0)}^"
)
if state is None:
state = {}
static_tools = static_tools.copy() if static_tools is not None else {}
custom_tools = custom_tools if custom_tools is not None else {}
state["_print_outputs"] = PrintContainer()
state["_operations_count"] = {"counter": 0}
if "final_answer" in static_tools:
previous_final_answer = static_tools["final_answer"]
def final_answer(*args, **kwargs): # Allow arbitrary arguments to be passed
raise FinalAnswerException(previous_final_answer(*args, **kwargs))
View on GitHub (pinned to 30bb116109)
Solutions
- Feed the error message back to the LLM to regenerate corrected code (standard self-correction loop)
- Increase max_tokens or retry to avoid truncated code actions
- Strip markdown fences and validate code with ast.parse (or compile()) before calling evaluate_python_code
- Check e.lineno and the caret position to fix the offending line manually when running ad-hoc code
Example fix
# before
output = executor("def f(:\n pass")
# after
import ast
code = "def f(:\n pass"
try:
ast.parse(code)
except SyntaxError as e:
code = regenerate_code_with_llm(f"Fix syntax error: {e}")
output = executor(code) Defensive patterns
Strategy: validation
Validate before calling
import ast
def is_parseable(code: str) -> bool:
try:
ast.parse(code)
return True
except SyntaxError:
return False
if not is_parseable(code_action):
code_action = ask_llm_to_fix(code_action) Type guard
def valid_python_source(code: str) -> bool:
try:
compile(code, '<action>', 'exec')
return True
except SyntaxError:
return False Try / catch
from smolagents.local_python_executor import InterpreterError
try:
executor(code_action)
except InterpreterError as e:
if str(e).startswith('Code parsing failed'):
code_action = regenerate_with_feedback(code_action, str(e)) Prevention
- Strip markdown fences before passing code to the executor
- Set max_tokens high enough to avoid truncated code actions
- Validate with ast.parse before executing
When it happens
Trigger: Passing code with syntax errors (unbalanced brackets, bad indentation, truncated output) to evaluate_python_code, LocalPythonExecutor.__call__, or an agent run whose code_action is malformed.
Common situations: LLM output truncated by max_tokens producing incomplete code; code blocks wrapped in stray markdown fences; tab/space indentation mixing in generated code.
Related errors
- Error in code parsing: {e} Make sure to provide correct code
- Code execution failed at line '{ast.get_source_segment(code,
- Tool call needs to have a key '{tool_name_key}'. Got keys: {
- The JSON blob you used is invalid due to the following error
- Error during jinja template rendering: {type(e).__name__}: {
AI-assisted analysis of huggingface/smolagents@30bb116109 (2026-08-28).
Data as JSON: /api/errors/ebdc8a4a941a3684.
Report an issue: GitHub.