Neural Tech Daily
ai-tutorials

Anthropic Code Execution Tool With Pandas: End-to-End Python Tutorial (May 2026)

Upload a CSV, ask Claude to analyse it with pandas in the sandbox, retrieve the generated chart, and validate cost-per-query — full Python walkthrough.

~9 min read
Share
Anthropic platform docs page for the code execution tool showing the sandboxed-container overview and the code_execution_20250825 tool type

Image: Anthropic platform docs — Code execution tool (platform.claude.com), used for editorial coverage of the API surface walked through below.

TL;DR

This tutorial walks through a working Python script that uploads a CSV file to Anthropic via the Files API, asks Claude Opus 4.7 to analyse it with pandas inside Anthropic’s sandboxed container, prints the model’s narrative reply, and downloads the matplotlib chart Claude generated. The tool surface is the server-side code_execution_20250825 tool documented on the Anthropic platform 1 , paired with the files-api-2025-04-14 beta header for input and output files 2 . The container ships pre-installed pandas, numpy, matplotlib, and seaborn 3 , so no extra pip install step runs. Total walk-through time is roughly 30 minutes for a developer comfortable with pip, environment variables, and the Anthropic SDK.

Per Anthropic’s pricing page, code execution is billed by container-hours rather than per-call: each organisation gets 1,550 free container-hours per month, and additional usage is $0.05 per hour per container, with a 5-minute minimum per session 4 . That makes the cost-per-query analysis later in this tutorial straightforward — most single-CSV queries fall comfortably inside the free monthly allowance.

What you’ll need

  • Python 3.11 or newer with pip on PATH.
  • An Anthropic API key from console.anthropic.com; the billing page shows whatever prepaid trial credit the workspace currently carries.
  • The anthropic Python SDK, version 0.40.0 or newer (the Files API helpers ship under client.beta.files).
  • A small CSV file to analyse. The example below uses a 9-row sales dataset, but anything under the 500 MB per-file Files API ceiling works 2 .

Step 1 — Install the SDK and set the API key

Create a fresh virtual environment and install the SDK:

python -m venv .venv
source .venv/bin/activate
pip install "anthropic>=0.40.0"

Export the API key in the same shell session:

export ANTHROPIC_API_KEY="sk-ant-..."

The Python SDK reads ANTHROPIC_API_KEY from the environment by default, so the constructor stays empty in the snippets below.

Step 2 — Prepare a CSV to analyse

Save the following as sales.csv next to the script. It’s small on purpose: the goal is to see the round-trip behaviour first, then scale up.

date,region,product,units,revenue_usd
2026-04-01,north,widget,12,1440
2026-04-02,north,gadget,8,1600
2026-04-03,south,widget,15,1800
2026-04-04,south,gadget,5,1000
2026-04-05,east,widget,20,2400
2026-04-06,east,gadget,11,2200
2026-04-07,west,widget,7,840
2026-04-08,west,gadget,9,1800
2026-04-09,north,widget,18,2160

Step 3 — Upload the CSV via the Files API

Per Anthropic’s Files API reference, file uploads require the anthropic-beta: files-api-2025-04-14 header, and CSV files are referenced through the container_upload content-block type 2 . The Python SDK handles the beta header when the betas=["files-api-2025-04-14"] parameter is passed to either client.beta.files.upload or client.beta.messages.create.

Anthropic platform docs page for the Files API showing the upload endpoint, the files-api-2025-04-14 beta header, and the container_upload content-block reference

Image: Anthropic platform docs — Files API (platform.claude.com), used for editorial coverage of the upload mechanics.

import anthropic

client = anthropic.Anthropic()

uploaded = client.beta.files.upload(
    file=("sales.csv", open("sales.csv", "rb"), "text/csv"),
)
print("file_id:", uploaded.id)

The response includes a file_id shaped like file_011CNha8iCJcU1wXNR6q4V8w. Hold onto that string — it’s what the Messages call references next.

Step 4 — Ask Claude to analyse the CSV

Now send a Messages request that wires together three pieces: the uploaded file as a container_upload content block, the code_execution_20250825 tool definition, and a prompt asking Claude to run pandas against the data 1 .

response = client.beta.messages.create(
    model="claude-opus-4-7",
    max_tokens=4096,
    betas=["files-api-2025-04-14"],
    tools=[
        {
            "type": "code_execution_20250825",
            "name": "code_execution",
        }
    ],
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "container_upload",
                    "file_id": uploaded.id,
                },
                {
                    "type": "text",
                    "text": (
                        "Load sales.csv with pandas. "
                        "Report total revenue by region "
                        "and the top-selling product. "
                        "Then save a bar chart of "
                        "revenue-by-region as chart.png."
                    ),
                },
            ],
        }
    ],
)

for block in response.content:
    if block.type == "text":
        print(block.text)

What happens server-side: Claude receives the prompt and the preloaded CSV, writes Python against pandas inside the sandbox, runs the script, observes the output, and either iterates or returns. The response.content array carries a mix of text blocks (Claude’s narrative reply) and bash_code_execution_tool_result blocks (the sandbox’s stdout, stderr, and any generated files).

Anthropic platform docs page for the code execution tool showing the sandboxed-container resource limits and the pre-installed libraries list including pandas, numpy, matplotlib, and seaborn

Image: Anthropic platform docs — Code execution tool (platform.claude.com), used for editorial coverage of the container-upload + tool-result flow.

Step 5 — Retrieve the generated chart

The generated chart.png lives inside the sandbox container as a new file. Anthropic’s docs surface its file_id inside the bash_code_execution_tool_result block, and the file is downloadable through the same Files API used for uploads 2 .

output_file_ids = []
for block in response.content:
    if block.type == "bash_code_execution_tool_result":
        for item in block.content.content:
            if getattr(item, "file_id", None):
                output_file_ids.append(item.file_id)

for fid in output_file_ids:
    metadata = client.beta.files.retrieve_metadata(fid)
    content = client.beta.files.download(fid)
    content.write_to_file(metadata.filename)
    print(f"Downloaded: {metadata.filename}")

The content.write_to_file(...) helper writes the bytes straight to disk. Open chart.png locally to confirm the rendered matplotlib bar chart matches what Claude described in its text reply.

Step 6 — Handle the container lifecycle

Per Anthropic’s docs, each sandboxed container has fixed resource limits — 5 GiB RAM, 5 GiB workspace storage, 1 CPU, Python 3.11.12, and no outbound internet access 3 . Containers expire 30 days after creation, and the workspace is scoped to the API key’s workspace 3 .

Two practical implications:

  • Container reuse for stateful workflows. The first response carries a response.container.id field. Passing that ID back as the container parameter on a follow-up Messages request reuses the same container, so files written in step one stay visible in step two 1 .
  • No outbound internet. Code running inside the sandbox cannot reach external APIs, package mirrors, or your own database. Whatever the analysis needs must be uploaded through the Files API or generated inside the container 3 .
container_id = response.container.id
print("container_id:", container_id)

followup = client.beta.messages.create(
    model="claude-opus-4-7",
    max_tokens=2048,
    betas=["files-api-2025-04-14"],
    container=container_id,
    tools=[
        {
            "type": "code_execution_20250825",
            "name": "code_execution",
        }
    ],
    messages=[
        {
            "role": "user",
            "content": (
                "Using the same dataframe, "
                "compute revenue per unit by product "
                "and save the result as summary.csv."
            ),
        }
    ],
)

Because the second request reuses container_id, Claude can re-pd.read_csv("sales.csv") (or, on code_execution_20260120, keep the live REPL state) without a second upload 1 .

Anthropic platform docs page for the tool-use overview showing the distinction between server-side and client-side tool patterns

Image: Anthropic platform docs — Tool use overview (platform.claude.com), used for editorial coverage of the server-tool vs client-tool surface.

Step 7 — Validate cost-per-query

Per Anthropic’s published billing terms, code execution is free when bundled with a web_search or web_fetch tool call in the same request; standalone code-execution sessions are billed by container-hour, with a 5-minute minimum per session and a 1,550- hour monthly free tier per organisation 4 . Beyond the free tier, the unit cost is $0.05 per container-hour per container 4 .

The response surface tracks both token usage and code-execution calls. Inspect them together:

usage = response.usage
print("input_tokens:", usage.input_tokens)
print("output_tokens:", usage.output_tokens)
print(
    "code_execution_requests:",
    usage.server_tool_use.code_execution_requests,
)

A back-of-envelope cost-per-query for the workflow in this tutorial:

  • Tokens. A 9-row CSV + the prompt above runs roughly 1,500 input tokens and 800 output tokens against Claude Opus 4.7, which lists at $15 per million input and $75 per million output on Anthropic’s pricing page (re-verify before relying on any specific figure) 5 . That’s about $0.022 + $0.060 = $0.082 in token cost.
  • Container time. The 5-minute minimum applies once per session 4 . At $0.05 per hour per container, 5 minutes maps to roughly $0.004 per query in the paid tier — effectively zero inside the 1,550-hour free band most teams stay within.

Logging both numbers per request gives a clean per-query budget the team can compare against. The token cost dominates; the container cost matters mostly at scale or with long-running multi-turn sessions.

Anthropic platform docs page for the Messages API reference showing the request structure used when wiring a tool-enabled call

Image: Anthropic platform docs — Messages API reference (platform.claude.com), used for editorial coverage of the request shape used in this tutorial.

Step 8 — Clean up uploaded files

Files uploaded through the Files API persist until explicitly deleted, and they count against the 500 GB per-workspace storage ceiling 2 . Delete the input file once the analysis is finished:

client.beta.files.delete(uploaded.id)

Output files generated by the sandbox (the chart.png and summary.csv from above) also live in the Files API surface and can be deleted the same way once downloaded.

What can go wrong

A few failure modes show up routinely:

  • container_expired error. Sandbox containers expire 30 days after creation 3 . A retry without the container parameter creates a fresh one; the cached files have to be re-uploaded.
  • Wrong content-block type. Referencing the CSV via a document block instead of container_upload returns an invalid_request_error from the Messages API; CSVs only flow into the code-execution sandbox through container_upload 2 .
  • Forgotten beta header. Calls to client.beta.files.* or Messages requests that reference a file_id need the files-api-2025-04-14 beta flag 2 . The Python SDK accepts betas=[...] on both surfaces.
  • Internet access in code blocks. Generated code that calls requests.get(...) against an external URL fails — the sandbox has no outbound connectivity 3 . Refactor the prompt to pass any needed reference data via an additional Files-API upload.

Where this fits in the broader Claude tool surface

The code execution tool sits alongside Claude’s other server-side tools (web_search, web_fetch) and the client-side custom tools documented in Anthropic’s tool-use overview 6 . The neutral framing: server tools run inside Anthropic’s infrastructure and the response already includes their result; client tools require your code to execute the call and post the result back. The code execution tool’s value is letting Claude write and run the analysis code itself against your data rather than delegating that step to your own backend.

How this article was made: an autonomous AI pipeline researched, drafted, fact-checked, and reviewed this piece, aggregating publicly-available information from the sources consulted below. AI (artificial intelligence) can make mistakes, so please cross-check the consulted sources before acting on anything here. Neural Tech Daily is not liable for decisions or outcomes based on this article.

Sources consulted

Cited Sources

  1. 1. Anthropic platform docs — Code execution tool (tool type `code_execution_20250825`; container reuse via `container.id`; supported model list) (accessed )
  2. 2. Anthropic platform docs — Files API (beta header `files-api-2025-04-14`; 500 MB per file; 500 GB per workspace; `container_upload` content-block type) (accessed )
  3. 3. Anthropic platform docs — Code execution containers (Python 3.11.12; 5 GiB RAM; 5 GiB disk; 1 CPU; no internet; 30-day expiry; pre-installed pandas, numpy, scipy, scikit-learn, matplotlib, seaborn) (accessed )
  4. 4. Anthropic platform docs — Code execution usage and pricing (1,550 free container-hours per organisation per month; \$0.05 per hour per container above the free tier; 5-minute minimum per session; free when combined with web_search or web_fetch) (accessed )
  5. 5. Anthropic platform docs — Pricing (per-million-token rates for Claude Opus 4.7; re-verify on the live pricing page before any budget commitment) (accessed )
  6. 6. Anthropic platform docs — Tool use overview (server-side vs client-side tool patterns) (accessed )

Further Reading

Anonymous · no cookies set

Report a problem with this article

Articles are produced by an autonomous AI pipeline; mistakes do happen. Tell us what's wrong and the editorial review will revisit the claim.

Category

Found this useful? Share it.