---
title: "Code Interpreter Agent"
category: 05-code
level: intermediate
stability: stable
description: "Use a sandboxed code execution tool to run Python, analyse data, and produce charts inside an agent workflow."
added: "2026-04"
version: v2
---

# Code Interpreter Agent
Category: code | Level: intermediate | Stability: stable | Version: v2

## Description
Code interpreter gives agents a sandboxed Python environment where they can write, run, and iterate on code in response to user requests. In the OpenAI Agents SDK it is available as `CodeInterpreterTool()`. The agent can upload files, execute data analysis, generate plots, and return file outputs — all within a single run. The sandbox is isolated per session, preventing cross-contamination between users.

## Inputs
- `code`: Python code string generated by the agent
- `files`: optional list of uploaded file IDs to make available in sandbox
- `tool`: `CodeInterpreterTool()` attached to the agent

## Outputs
- `stdout` / `stderr` from code execution
- Generated files (CSV, PNG, etc.) as downloadable outputs
- Agent's natural-language interpretation of results

## Example
```python
from agents import Agent, Runner, CodeInterpreterTool

agent = Agent(
    name="DataAnalyst",
    instructions="Analyse data using Python and explain your findings.",
    tools=[CodeInterpreterTool()]
)

result = Runner.run_sync(agent, "Calculate the mean and standard deviation of [4,7,13,2,8].")
print(result.final_output)
```

## Failure Modes
| Cause | Symptom | Mitigation |
|---|---|---|
| Infinite loop in generated code | Sandbox timeout | Set execution timeout; instruct agent to avoid loops over large datasets |
| Missing library in sandbox | ImportError | Inform agent of available libraries in system prompt |
| Large file upload | Slow or failed execution | Chunk large files before upload |

## Prompt Patterns
**Basic:** `"Write and run Python code to answer this question."`

**Chain-of-Thought:** `"Plan the analysis steps, write the code, run it, interpret output, then explain."`

**Constrained Output:** `"Always print your final numeric result with a label so it can be parsed."`

## Model Comparison
| Capability | GPT-4o | Claude 3.7 Sonnet | Gemini 2.0 Flash |
|---|---|---|---|
| Code generation quality | ✅ High | ✅ Very High | ✅ Good |
| Native code interpreter | ✅ Built-in | ⚠️ Requires custom | ⚠️ Requires custom |
| Debugging iterations | ✅ Strong | ✅ Strong | ⚠️ Limited |
| Data viz quality | ✅ Good | ✅ Good | ⚠️ Basic |
| Cost per run | High | Moderate | Low |

## Related
- `code-execution.md` · `code-review.md` · `tool-use-loop.md` · `agent-as-tool.md`

## Changelog
- v2 (2026-04): Full expansion
