# Code Execution

> Use the Claude API code execution tool so the model runs Bash and Python in an Anthropic-hosted sandbox during a response — for calculation, data analysis, file generation, and checking its own work. Covers tool versions, file upload, retrieving generated files, container reuse, limits, and data-retention constraints. Use this skill when building features where Claude must actually run code (not just write it), when choosing a code execution tool version, or when debugging missing output files or expired containers. Activate when: Claude code execution, code_execution tool, Python sandbox, run code tool, data analysis agent, code interpreter, container_upload, container reuse, OUTPUT_DIR.

- Skill: `latestaiagents/code-execution-2` (Agent Skill)
- Install (CLI): `npx get-skill add latestaiagents/code-execution-2`
- Raw SKILL.md: https://api.skillmd.com/api/skills/latestaiagents/code-execution-2/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: latestaiagents (https://skillmd.com/u/latestaiagents)
- Updated: 2026-11-14
- Page: https://skillmd.com/skills/latestaiagents/code-execution-2

---


# Code Execution Tool

**The code execution tool runs Bash commands and file operations in a sandboxed container on Anthropic's infrastructure. Use it when the answer is "whatever the code prints", not when you only need code written.**

## When to Use

- Data analysis on uploaded files (CSV, JSON, Excel, PDF)
- Charts, reports, and other generated files returned through the Files API
- Math or statistics the model should verify by running, not estimate
- Running tests or scripts the model just wrote, inside an isolated environment

## When NOT to Use

- Pure text tasks: the tool adds latency and cost for nothing
- Work that needs the internet or packages that are not pre-installed: the container has no internet access
- Long-running jobs (training, crawling): use your own compute
- Workloads that require zero data retention: the docs list code execution as not ZDR-eligible (container data is retained up to 30 days)

## Workflow

### Step 1: Pick a tool version

The tool is a server tool: declare it in `tools` and results arrive in the same response. Current versions need no beta header.

| Tool `type` | Adds | Use when |
|-------------|------|----------|
| `code_execution_20250825` | Bash commands and file operations | Plain analysis and file generation |
| `code_execution_20260120` | REPL state persistence and programmatic tool calling | Claude should call your tools from inside code |
| `code_execution_20260521` | Same runtime as `20260120`; tells Claude about the per-cell time limit in programmatic tool calling | Programmatic tool calling with long-running cells |

`code_execution_20250522` was the original Python-only version; the docs include a migration section for it. Tool types are dated identifiers, so re-check the tool-version table whenever you adopt a new model and prefer the newest version your integration supports. To check support programmatically, read `capabilities.server_tools.code_execution.supported` from the Models API.

```ts
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();
const MODEL = process.env.ANTHROPIC_MODEL!; // a current model ID from the models overview page

const response = await client.messages.create({
  model: MODEL,
  max_tokens: 16000,
  tools: [{ type: "code_execution_20250825", name: "code_execution" }],
  messages: [{ role: "user", content: "Compute the mean and standard deviation of [1,2,3,4,5,6,7,8,9,10]." }],
});
```

### Step 2: Upload input files

Upload with the Files API, then reference the file in a `container_upload` content block. The Files API is generally available; current SDKs expose it as `client.files`. Older code used `client.beta.files` with a `files-api-2025-04-14` beta header; check your SDK changelog before migrating, because the beta namespace changed shape.

```ts
import fs from "node:fs";

const file = await client.files.upload({ file: fs.createReadStream("sales.csv") });

const response = await client.messages.create({
  model: MODEL,
  max_tokens: 16000,
  tools: [{ type: "code_execution_20250825", name: "code_execution" }],
  messages: [{
    role: "user",
    content: [
      { type: "text", text: "Compute year-over-year growth from this CSV." },
      { type: "container_upload", file_id: file.id },
    ],
  }],
});
```

### Step 3: Read results correctly

The response interleaves `server_tool_use` blocks with result blocks. The current versions expose two sub-tools, `bash_code_execution` and `text_editor_code_execution`, so the result blocks are `bash_code_execution_tool_result` and `text_editor_code_execution_tool_result`, not the legacy `code_execution_tool_result`.

```ts
for (const block of response.content) {
  if (block.type === "bash_code_execution_tool_result") {
    const result = block.content;
    if (result.type === "bash_code_execution_result") {
      console.log("stdout:", result.stdout);
      if (result.return_code !== 0) console.error("stderr:", result.stderr);
    }
  }
}
```

Always check `return_code`. A model can describe results confidently even when the command failed.

### Step 4: Retrieve generated files

Each `bash_code_execution` call gets a fresh directory exposed as `$OUTPUT_DIR`. Only files at the top level of that directory are captured and returned as `file_id` entries; files written elsewhere stay in the container. If your application depends on a file, prompt Claude to copy it there and list the directory in the same command:

```bash
python /tmp/make_report.py && cp /tmp/report.pdf "$OUTPUT_DIR/" && ls "$OUTPUT_DIR"
```

Download returned files through the Files API.

### Step 5: Reuse the container for multi-turn work

The response includes a top-level `container` object with an `id`. Pass it back as the top-level `container` parameter to keep files (and, with `20260120` or later, Python interpreter state) across requests.

```ts
const second = await client.messages.create({
  model: MODEL,
  max_tokens: 16000,
  container: first.container!.id,
  tools: [{ type: "code_execution_20250825", name: "code_execution" }],
  messages: [/* full history plus the new question */],
});
```

The docs state that containers expire 30 days after creation and are checkpointed after a few minutes of inactivity. An expired container cannot be restored: retry without `container` to get a new one. The `expires_at` value in the response is a shorter rolling value, not the 30-day limit.

## Sandbox Facts (as documented)

| Property | Documented value |
|----------|------------------|
| Internet access | None; only pre-installed libraries are available |
| Python | 3.11 |
| Memory / disk / CPU | 5 GiB RAM, 5 GiB workspace, 1 CPU |
| Container lifetime | 30 days after creation |

Re-check the "Containers" section of the tool page before relying on these for capacity planning.

## Pricing Notes

Code execution has its own pricing, except that the docs state it carries no extra charge in requests that also include the dynamic-filtering versions of web search or web fetch (`web_search_20260209`, `web_fetch_20260209`, or later). Look up current rates on the pricing page rather than hard-coding them.

## Anti-Patterns

1. Declaring code execution alongside dynamic-filtering web search or fetch: those tools provision code execution themselves
2. Asking the model to "describe the chart" instead of downloading the file it produced
3. Ignoring `return_code` and `stderr`
4. Starting a new container every turn for iterative analysis
5. Uploading very large files when a sample would answer the question

## Best Practices

1. Enable the tool only on routes that need computation
2. Use the simplest version that covers your needs, and re-check versions on every model upgrade
3. Reuse the container for multi-turn analysis; handle expiry by starting fresh
4. Instruct Claude to write deliverables to `$OUTPUT_DIR` and list it
5. Treat outputs as untrusted: scrub secrets before you log or persist stdout
6. Confirm data-retention requirements before sending regulated data

## References

- Code execution tool: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool
- Programmatic tool calling: https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling
- Files API: https://platform.claude.com/docs/en/build-with-claude/files
- Pricing: https://platform.claude.com/docs/en/about-claude/pricing

