Skip to main content
The code_execution (or code_interpreter) tool provides agents with a secure, sandboxed Python environment. This allows them to go beyond text generation and perform computational tasks, data analysis, and visualization by writing and executing real code. It is designed to be iterative: the agent can write code, see the output (or errors), and then refine its code in a loop until the task is complete.

When to Use This Tool

Use code_execution when you need to:
  • Analyze Data: Process CSVs, Excel files, or JSON data to find insights.
  • Visualize Information: Create charts, graphs, and plots using libraries like matplotlib or seaborn.
  • Perform Math: Solve complex algebraic equations or financial calculations accurately.
  • Transform Files: Convert data formats or clean up messy datasets.
Security & IsolationEvery execution runs in a completely isolated, ephemeral sandbox. The environment cannot access your local filesystem, ensuring complete safety. Files must be explicitly passed into the sandbox via document_ids to be available in the sandbox.
Configuration & TuningYou can customize the behavior of the code execution tool in your User Preferences. Specifically, you can select which model provider should be used for the code generation tasks, allowing you to optimize for speed, cost, or reasoning capability.

Input Parameters

The tool accepts the following parameters:

Output Structure

The tool returns a structured object containing the execution results, logs, and any generated artifacts.

Example Usage

Scenario: analyzing Sales Data

Input:
Result: The agent will:
  1. Plan: Create a multi-step plan (Load data -> Group by region -> Plot).
  2. Execute: Write Python code using pandas to read the CSV (uploaded to /home/uploaded_files/).
  3. Visualize: Use matplotlib to create the chart and save it as an image.
  4. Return: The final response will include the calculated numbers in the logs and the chart in the artifacts array.

How It Works

  1. Planning: The agent first breaks down your request into a logical, step-by-step coding plan.
  2. Iterative Coding: It executes the plan one step at a time.
    • It writes code for Step 1.
    • It runs the code in the sandbox.
    • It observes the output (stdout/stderr).
    • If there’s an error, it self-corrects and retries.
  3. State Persistence: Variables and dataframes defined in Step 1 are available in Step 2, allowing for complex, multi-stage workflows.
  4. Finalization: Once all steps are complete, it packages the logs, files, and images into the final response.
Iterative RefinementBecause the sandbox_id is returned, you can continue the conversation! You can ask follow-up questions like “Now filter that data for Q4 only,” and the agent will resume exactly where it left off, with all the data still loaded in memory.