Sub topic 9
Sandbox containers, input files, and generated files
The code execution tool runs model-written Python in a provider-managed sandbox. This chapter covers the part of that tool that holds state: the container. It explains how a container is created, how your files get into it, how files the model creates get out, and what limits apply along the way.
This chapter assumes you have already declared a code_interpreter tool in a request and read code_interpreter_call items in the response. Examples use the OpenAI Responses API. The last section covers how other providers differ.
What a container is
A container is a short-lived, isolated Linux environment with a Python runtime and a scratch filesystem. The model's code runs inside it. Three properties matter in practice:
- It is created by the provider. You never start or stop a process yourself.
- It keeps state between code runs. Files and variables written in one step are visible in later steps of the same container.
- It expires. With OpenAI, a container is discarded after about 20 minutes without use. Anything not downloaded by then is lost.
The tool declaration decides how the container is created. There are two modes.
| Mode | Declaration | When to use it |
|---|---|---|
| Auto | `"container": {"type": "auto"}` | One-off requests. The provider creates a container, or reuses one from earlier in the conversation. |
| Explicit | `"container": "cntr_..."` (an ID) | You need the same filesystem across several separate requests, or you want to inspect and download files yourself. |
Getting files in
The model cannot read files from your machine. You upload a file first, then attach its ID to the container. With an auto container, put the ID in file_ids.
from openai import OpenAI
client = OpenAI()
with open("sales.csv", "rb") as f:
uploaded = client.files.create(file=f, purpose="user_data")
response = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "code_interpreter",
"container": {"type": "auto", "file_ids": [uploaded.id]},
}
],
instructions=(
"You are a data analyst. Use Python to read the attached file, "
"compute the answer, and save any chart as a PNG."
),
input="Which month had the highest total revenue? Plot revenue by month.",
)
print(response.output_text)The file appears in the container's working area, typically under /mnt/data. The model learns the file exists from the request, so naming the file in your prompt is useful. For example: "Read sales.csv and ...". Without a hint, the model sometimes writes code that searches the filesystem, which wastes a step.
Edge cases to plan for:
- Format. Text-like files (CSV, JSON, TXT) and common office or image formats work. Unusual binary formats may fail inside the sandbox even though the upload succeeds.
- Size. Large files count toward provider upload limits, and loading a huge file into memory can exceed the container's memory limit. Check the current limits in the provider's documentation.
- Privacy. The file is stored by the provider. Do not upload data you are not allowed to send to a third party.
Getting files out
When the model's code saves a file and mentions it in the final message, the response carries an annotation that points at the file. For OpenAI, that annotation has type container_file_citation and includes container_id, file_id, and filename. You use those values to download the bytes.
import os
for item in response.output:
if item.type != "message":
continue
for part in item.content:
for ann in getattr(part, "annotations", []) or []:
if ann.type == "container_file_citation":
data = client.containers.files.content.retrieve(
file_id=ann.file_id,
container_id=ann.container_id,
)
name = os.path.basename(ann.filename or ann.file_id)
with open(name, "wb") as out:
out.write(data.read())
print("saved", name)The os.path.basename call matters. A returned filename can be a sandbox path such as /mnt/data/revenue.png. Writing it directly would try to create that path on your machine.
The flow looks like this:
A file only gets a citation if the model mentions it. If the code writes a file but the final text never refers to it, you will not see an annotation. You can ask for it explicitly: "Save the result as report.csv and tell me the filename." You can also list the container's files directly, as the next section shows.
Reusing a container across requests
An auto container is convenient, but it is hard to find again later. For multi-step workflows, create a container yourself and pass its ID.
container = client.containers.create(name="analysis-session")
first = client.responses.create(
model="gpt-4.1",
tools=[{"type": "code_interpreter", "container": container.id}],
input="Write the numbers 1 to 10 and their squares to squares.csv.",
)
second = client.responses.create(
model="gpt-4.1",
tools=[{"type": "code_interpreter", "container": container.id}],
input="Read squares.csv and tell me the sum of the second column.",
)
print(second.output_text)
for f in client.containers.files.list(container_id=container.id):
print(f.id, f.path)The second request finds squares.csv because it shares the container with the first. Each code_interpreter_call item in the response also carries a container_id, so you can recover the ID from an auto-created container and keep using it, provided it has not expired.
Container reuse has three consequences:
- State is shared. A leftover file from an earlier run can change the result of a later one. Give files distinct names or use a new container per task.
- Expiry is silent until you use it. A request that references an expired container fails. Catch the error and recreate the container, re-uploading any input files.
- Billing follows containers. Providers typically charge per container session in addition to tokens, so many tiny sessions can cost more than one reused session.
Common errors
- "File not found" inside the sandbox. The file was uploaded but not attached to the container in
file_ids, or the container is a different one from the one you uploaded to. - No annotations in the response. The model did not mention the file in its final message, or the code failed before saving. Inspect the
code_interpreter_callitems for the code and its outputs. - Download works once, then fails. The container expired. Download files immediately after the response arrives.
- Wrong working directory. Code that writes to a relative path may save somewhere you did not expect. Telling the model to save under
/mnt/dataremoves the guesswork.
Provider differences
Other providers offer the same idea with different names and flows. Anthropic's code execution tool is also a server-side sandbox, and it uses its Files API to move files in and out. The tool type string is versioned and may require a beta header, so copy it from the current documentation. The concepts carry over: upload first, reference the file in the request, and download generated files before the sandbox expires. The exact fields, retention times, and limits differ, so treat any numbers in this chapter as examples to verify.
Security notes
The sandbox has no access to your machine, but it can still be a data path. Uploaded files are readable by model-written code, and the model's code is influenced by the prompt, including any untrusted text you pass in. Do not attach files containing secrets. Treat downloaded files as untrusted output: do not open or execute them automatically.
Exercise
Your app runs a code interpreter step to build a PDF report, and a second request an hour later should append a section to the same PDF. The second request fails. What are two likely causes, and what do you change?
Show answer
The container probably expired after about 20 minutes of inactivity, so the PDF no longer exists in it. A second possible cause is that the second request used a different (auto) container from the first. Change the workflow to download the PDF right after the first response, then upload it again with file_ids on the second request. Alternatively, create an explicit container and reuse it, but only if the requests happen within the expiry window.
Exercise
The model's code saved chart.png, but your loop over annotations prints nothing. How do you find out whether the file exists?
Show answer
Check the code_interpreter_call items to see whether the code ran without error, then list the files in the container with client.containers.files.list(container_id=...). If the file is there, the model simply did not mention it in the final message. Retrieve it by its file ID, and next time instruct the model to state the filename in its answer.