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
Usecode_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
matplotliborseaborn. - 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.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:- Plan: Create a multi-step plan (Load data -> Group by region -> Plot).
- Execute: Write Python code using
pandasto read the CSV (uploaded to/home/uploaded_files/). - Visualize: Use
matplotlibto create the chart and save it as an image. - Return: The final response will include the calculated numbers in the
logsand the chart in theartifactsarray.
How It Works
- Planning: The agent first breaks down your
requestinto a logical, step-by-step coding plan. - 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.
- State Persistence: Variables and dataframes defined in Step 1 are available in Step 2, allowing for complex, multi-stage workflows.
- Finalization: Once all steps are complete, it packages the logs, files, and images into the final response.

