Skip to main content

What it does

The Run Code tool (execute_python) runs code in a secure sandboxed environment. Perfect for data analysis, calculations, visualizations, and any computational tasks your agents need to perform.
Run Code is pre-checked when you create an agent. It’s a default-on baseline because it pairs so closely with attachments and knowledge-base files — reading, parsing, and transforming uploaded data. It behaves like any other tool — you can uncheck it at any time. See Default-on tools.

Key features

  • Execute Python code in isolated Jupyter notebook cells
  • Support for popular libraries (pandas, numpy, matplotlib, etc.)
  • Enhanced output display with separate sections for different output types
  • Smart output categorization - stdout, stderr, results, and text outputs are displayed distinctly
  • Automatic error handling with detailed tracebacks
  • Persistent session state across multiple executions

Parameters

Timeouts, waiting, and restarting Python

If the Python service is unavailable, the agent can call:
This checks the existing workspace’s Python service for up to 55 seconds, plus the final bounded check. It waits outside Python and does not execute code, import files, restart anything, or replay earlier work. The agent can wait again if the service is still recovering. jupyter_api reports reachable, unreachable, or unknown; a reachable API does not prove the kernel is healthy or that earlier execution finished. Inspect saved files before rerunning work. Waiting cannot retrieve output from an earlier disconnected execution. Failure and wait receipts can also include a provider memory sample under resources, with its observation time and age. An old sample is not current usage, and high memory usage alone does not prove an out-of-memory kill. Unknown metrics do not mean zero usage. Resource observation can add up to three seconds. The tool waits up to five minutes for Python. If that wait times out, it returns partial output and leaves the sandbox intact. Python may still be running; the timeout does not establish success or failure. Later output is not retrievable through this tool, and another Python call can queue behind the running code. Do not blindly rerun work that may have already written files or changed external systems. To stop stuck Python execution, the agent can explicitly restart its session:
Restart preserves workspace files and clears Python variables, imports, and in-memory state. It does not undo earlier writes or external side effects, and separate subprocesses may remain running. Inspect existing files before continuing. Restart neither imports files nor executes new code; use a separate call afterward. If the existing workspace or Python session cannot be identified safely, restart returns an error instead of creating or replacing a sandbox. Sandbox expiration and infrastructure failures remain separate limits; a preserved sandbox is not a durable backup of unpublished files. On execution or restart failures, the tool reports the failed stage, the known workspace, and any output received before the failure. execution_status distinguishes code that did not start, returned a Python error, completed before an export failure, or has an unknown outcome. A failed restart reports restart_status; an unknown restart outcome does not establish whether variables survived. Infrastructure failures also include a bounded, read-only check of the Jupyter service. diagnostics.jupyter_api is reachable, unreachable, or unknown. This checks service availability, not successful execution or kernel health. An unreachable service may be recovering; repeated immediate execution/restart attempts can fail during that interval. Wait before trying again, then inspect existing files. The tool does not automatically restart services or replay code.

Output types & display

The tool now intelligently categorizes and displays different types of output:

📤 Output (stdout)

Print statements and console output appear in a clean gray section:

📊 Result (expression results)

The final expression result is highlighted in a blue section:

⚠️ Warnings/Errors (stderr)

Non-fatal warnings and errors appear in an orange warning section:

🎨 Rich Media (charts, images, etc.)

Visual outputs like charts and images are displayed with full formatting:

Common use cases

Data analysis with clear output

Create visualizations with status updates

Mathematical calculations with explanations

Error handling demonstration

Knowledge base file access

Knowledge base files appear in the sandbox at /home/user/kb/{kb_id}/ only when you request them via the kb_files parameter on the execute_python call (format kb/{kb_id}/{filename}). They are not pre-loaded — the directory does not exist until you request a file into it, so os.listdir('/home/user/kb/{kb_id}/') without a prior request will fail. Use list_kb_files to discover exact filenames first, then pass them in kb_files. You can request files from any knowledge base in your organization — the KB does not need to be in the agent’s accessible-KB list. Requesting a file mounts both the original binary and its .md companion.

What’s available in the sandbox

When to use local files vs KB tools

Performance tip for bulk operations: Reading .md files directly in Python is instant. Each read_file tool call requires a round-trip. For agents that process many files (financial analysis, document comparison, portfolio reviews), guide your agent to read files locally instead of making dozens of tool calls.

Example: bulk processing with local KB files

Working files and input imports

An input is imported once per sandbox, after its download and write succeed. Later calls preserve edits, renames, and deletions made by your code. Adding an attachment does not reload earlier inputs. If a new input would occupy an existing path, the tool preserves the existing file and returns import_warnings. It does not rename either file automatically. To replace it, explicitly move or delete the existing file, then call the tool again (include kb_files again for a requested KB file). Failed imports remain retryable. Python writes and explicit app reloads retain their normal overwrite behavior. The import record lives at /home/user/.aster/imported-inputs.json. It is workspace bookkeeping, not version history or a backup. Tool results identify the sandbox and whether it was newly created; a new sandbox does not contain the old workspace’s unsaved files or variables.

Available libraries

Common Python libraries are pre-installed including:
  • Data Science: pandas, numpy, scipy, scikit-learn
  • Visualization: matplotlib, seaborn, plotly
  • Web: requests, beautifulsoup4
  • Utilities: json, csv, datetime, os, sys

Output formats

The tool supports rich output including:
  • Text: Standard print output and string representations
  • Images: PNG, JPEG, SVG graphics from matplotlib, plotly, etc.
  • HTML: Rich HTML content and tables
  • Charts: Interactive visualizations
  • Markdown: Formatted text with markdown syntax

Visual improvements

✨ New in latest version:
  • Color-coded output sections for easy identification
  • Collapsible code view to focus on results
  • Success indicators for code that runs without visible output
  • Enhanced error display with structured error information
  • Rich media rendering for charts, images, and formatted data

Best practices

  • Use print() statements to show progress and intermediate results
  • Structure your code with clear steps and explanations
  • Handle errors gracefully with try/except blocks
  • Break complex operations into smaller, trackable steps
  • Import libraries at the beginning of your code

Troubleshooting

“Module not found” errors
  • Check if the library is in the available libraries list
  • Try importing alternative libraries with similar functionality
  • Use built-in Python modules when possible
“Code execution timeout”
  • Simplify complex operations
  • Avoid infinite loops or very long-running processes
  • Break large datasets into smaller chunks
“Memory errors”
  • Reduce dataset size or use sampling
  • Clear variables you no longer need with del variable
  • Use more memory-efficient data structures
“No output displayed”
  • Use print() statements to generate stdout output
  • Ensure your final line is an expression (not assignment) to see results
  • Check that your code doesn’t have syntax errors