Code Interpreter: Run Code in the API
On this page
Updated November 2, 2026 based on the official Code Interpreter guide and the
openaiSDK: the tool requires acontainerparameter (missing from all previous examples, which would have failed), generated files appear incontainer_file_citationannotations and are downloaded via the Containers API (notclient.files.content), and call outputs are namedoutputs(notresults). Input text parts use the typeinput_text. Files attached to a message are uploaded with theuser_datapurpose, which OpenAI recommends for model inputs (File inputs). Sources: Code Interpreter · File inputs.
Code Interpreter: Run Code in the API
A language model predicts text; it doesn’t calculate. Ask it for the square root of 1764, and it will produce the most likely result based on its training—often correct, sometimes wrong, with no way to tell the difference. Code Interpreter removes this uncertainty by giving the model a Python interpreter: it writes the calculation, executes it, and returns an obtained result, not a guess.
The shift is deeper than it appears. The model sees the output of its own code, including errors, so it can correct itself and retry. On a data file where no one knows the exact structure, this loop beats any pre-written instruction.
Enable Code Interpreter
You enable it by adding the tool to the tools array—nothing to install, no environment to provision. The model decides when to write code: it answers factual questions directly, but switches to execution for calculations or data manipulation.
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.6-terra",
input="Calculate the Fibonacci sequence up to the 20th term",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}]
)
print(response.output_text)
The model writes the Python code, executes it in a sandbox, and integrates the results into its response.
Inspect the Executed Code
Get in the habit of reading this code, at least during development. It’s the only way to distinguish a good result from one that’s right by chance: an average calculated while silently ignoring missing values is numerically correct but analytically false. The response won’t tell you that; the code will.
The response contains the generated code and its results:
response = client.responses.create(
model="gpt-5.6-terra",
input="What is the square root of 1764? Verify by squaring the result.",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
include=["code_interpreter_call.outputs"], # to receive produced logs and images
)
for item in response.output:
if item.type == "code_interpreter_call":
print("--- Executed Code ---")
print(item.code)
print("--- Outputs ---")
for output in item.outputs or []:
print(output.logs if output.type == "logs" else output.url)
Provide Files as Input
The tool delivers its full value when working with files. You upload, reference the file in the call, and the model actually opens it—it reads the real columns, real types, and real outliers, instead of reasoning about a description you might have provided.
# Upload the file
with open("sales_2025.csv", "rb") as f:
file_obj = client.files.create(file=f, purpose="user_data")
# Use Code Interpreter with the file
response = client.responses.create(
model="gpt-5.6-terra",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "Analyze this sales file. "
"Give me the total by category and the best-performing month."},
{"type": "input_file", "file_id": file_obj.id}
]
}
],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}]
)
print(response.output_text)
Retrieve Generated Files
The reverse path works too: the code produces a cleaned CSV, a chart, or an Excel workbook, and these files are returned to you. They stay in the container, and the response message cites them in its annotations of type container_file_citation, including the container ID, file ID, and filename. You then download them via the Containers API. Two small functions, reused in later lessons, encapsulate this flow:
def generated_files(response):
"""Files created by Code Interpreter, cited in message annotations."""
for item in response.output:
if item.type == "message":
for part in item.content:
for ann in getattr(part, "annotations", None) or []:
if ann.type == "container_file_citation":
yield ann
def download(client, ann, path):
"""Downloads a file from the container and returns its local path."""
content = client.containers.files.content.retrieve(ann.file_id, container_id=ann.container_id)
with open(path, "wb") as out:
out.write(content.read())
return path
Files you provide as input (input_file) are automatically copied into the container: you don’t need to upload anything else.
response = client.responses.create(
model="gpt-5.6-terra",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "Create a chart of sales by month "
"and export the cleaned data as a CSV."},
{"type": "input_file", "file_id": file_obj.id}
]
}
],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}]
)
# Retrieve generated files
for ann in generated_files(response):
print(f"Generated file: {ann.filename}")
download(client, ann, ann.filename)
Container and Environment
Knowing the container rules saves time debugging what can’t work. According to OpenAI’s documentation:
- it’s a fully isolated virtual machine (sandbox) where the model executes Python;
- the tool requires a
containerparameter:{"type": "auto"}creates a container (or reuses one from a previous call present in the context), while an ID obtained viaclient.containers.create(...)forces a specific container; - memory is set with
memory_limit:1g(default),4g,16g, or64g, with higher tiers billed at integrated tool rates; - a container expires after 20 minutes of inactivity; its data is then lost, so download any files you want to keep while it’s active.
Don’t count on network access from the code: provide data as input, or delegate research to the Web Search tool.
# Example: the model can use pandas directly
response = client.responses.create(
model="gpt-5.6-terra",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "Load this CSV with pandas, "
"calculate descriptive statistics, and identify outliers."},
{"type": "input_file", "file_id": file_obj.id}
]
}
],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}]
)
Chain Multiple Executions
Successive executions share the same session: variables, DataFrames, and imports from the first block remain available in the next, exactly like in a notebook. The model leverages this naturally—it loads, inspects, then processes—making multi-step analysis possible without reloading everything at each stage.
response = client.responses.create(
model="gpt-5.6-terra",
input="1. Generate 1000 random points from a normal distribution. "
"2. Calculate the mean and standard deviation. "
"3. Create a histogram. "
"4. Perform a Shapiro-Wilk normality test.",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}]
)
# The model executes 4 code blocks sequentially
# Each block has access to variables from previous ones
Combine with Other Tools
The most useful combination pairs a data source with the ability to process it: File Search finds the relevant passage in your documents, Web Search brings in market data, and Code Interpreter compares the two in a table or chart. None of these tools can do the others’ jobs.
response = client.responses.create(
model="gpt-5.6-terra",
input="Search the web for French GDP data from the last 10 years, "
"then create a trend chart with a linear regression.",
tools=[
{"type": "web_search"},
{"type": "code_interpreter", "container": {"type": "auto"}}
]
)
Pattern: Full Analysis Pipeline
The final example chains everything above into a realistic case: an input file, multi-step analysis, and output deliverables. Focus especially on the prompt format—numbered, explicit about the expected output—because that, far more than the accompanying Python code, determines the quality of the result.
def analyze_data(file_path: str, questions: list[str]) -> dict:
"""Data analysis pipeline with Code Interpreter."""
# Upload
with open(file_path, "rb") as f:
file_obj = client.files.create(file=f, purpose="user_data")
results = {}
for question in questions:
response = client.responses.create(
model="gpt-5.6-terra",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": question},
{"type": "input_file", "file_id": file_obj.id}
]
}
],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions="Write clean, commented Python code. "
"Display intermediate results."
)
results[question] = response.output_text
return results
# Usage
results = analyze_data("sales.csv", [
"Give descriptive statistics for each numeric column",
"What are the top 5 best-selling products?",
"Is there seasonality in sales?"
])
Key Takeaways
- Code Interpreter runs Python in an isolated container; the
containerparameter is required ({"type": "auto"}or an ID) - Files provided as
input_fileare automatically copied into the container - Generated files are cited as
container_file_citationand downloaded viaclient.containers.files.content.retrieve - A container expires after 20 minutes of inactivity: download what you want to keep
- Combine with Web Search and File Search for enriched analysis