Sub topic 8
Code execution: letting the model compute
Language models predict text. They do not calculate. Ask a model for the sum of the squares of 1 to 1000 and it may produce a plausible but wrong number. The code execution tool fixes this. The model writes Python, the provider runs it in a sandbox, and the model reads the real output before it answers.
This chapter assumes you can call the Responses API with an API key, read JSON response bodies, and write basic Python. It also assumes you know the basic idea of tool calling. Earlier chapters covered declaring tools and reading output items. This chapter applies both to code execution.
What the tool does
Code execution is a built-in tool. The provider hosts it, so your code does not execute anything. The model decides it needs to compute something, writes a Python program, and the provider runs that program in an isolated container. The output goes back to the model. The model can then write more code or give the final answer. All of this happens inside one API call.
This is the server-side tool loop from earlier chapters, with a code runner as the tool. The difference from a function tool is that you do not write a handler and you do not send tool results back.
Declaring the tool
Add a tool of type code_interpreter to the tools list. It needs a container setting. With {"type": "auto"}, the provider creates a container for the request, or reuses the one from earlier in the conversation.
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions="When a question involves arithmetic, write and run code to answer it.",
input="What is the sum of the squares of the integers from 1 to 1000?",
)
print(response.output_text)The instructions line matters. Without it, the model may answer from memory when it feels confident. The correct answer here is 333,833,500. You can check it yourself with sum(i*i for i in range(1, 1001)).
Reading the output items
output_text shows only the final answer. To audit what the model ran, look at the items in response.output. A code run appears as an item of type code_interpreter_call. It records the code the model wrote and the container it used.
for item in response.output:
if item.type == "code_interpreter_call":
print("container:", item.container_id)
print("code:\n", item.code)
elif item.type == "message":
print("answer:", item.content[0].text)Check this field on your SDK version. The names of fields on the call item, such as code, outputs, and container_id, can differ between SDK releases. You can get the raw outputs of the run by adding include=["code_interpreter_call.outputs"] to the request. Without that, the item holds the code but not the results.
Logging the code is the best way to debug. When an answer looks wrong, read the code the model wrote. The fault is usually in the code, not in the arithmetic.
What the sandbox is
The container is a temporary Linux environment with Python and common data libraries such as NumPy and pandas. The model writes code. The sandbox runs it. A few properties shape how you design around it:
- No internet access. Code cannot call APIs or download packages. Do not ask it to fetch data. Use web search for that.
- Limited, temporary state. Files and variables live in the container. Containers expire after a period of inactivity, so do not treat one as storage.
- Limited resources. Memory and run time are capped. Heavy jobs can fail or time out.
- Only what is uploaded. The code can read files you attach to the container and files it creates itself.
Check the current limits in your provider's documentation, since they change.
Files in and out
The next chapter covers files in detail. Here is the short version. You can place input files in the container, and the code can read them from disk. When the code writes a file, such as a chart or a CSV, the answer message carries a container_file_citation annotation. It names the container and file, and you download the bytes with a separate call.
for item in response.output:
if item.type == "message":
for part in item.content:
for ann in getattr(part, "annotations", []) or []:
if ann.type == "container_file_citation":
print(ann.container_id, ann.file_id, ann.filename)Fetch the file promptly. If the container expires first, the file is gone.
Steering the model
The model chooses whether to run code. You can influence that in three ways.
- Instructions. State when to use code, as in the example above. "Always compute numeric answers with code" is a common rule.
- Tool choice. You can require a tool call through the
tool_choiceparameter. Forcing the tool guarantees a run, but the model then runs code even for questions that do not need it. - Prompt wording. Asking for a calculation, a table, or a chart nudges the model toward code.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Number is wrong and no code item appears | Model answered from memory | Add an instruction to compute with code, or force the tool |
| Code fails with a network error | Sandbox has no internet | Fetch data elsewhere and pass it in as input or a file |
| File citation returns an error later | Container expired | Download files soon after the response |
| `ModuleNotFoundError` in the run | Library is not preinstalled | Ask for a standard-library approach, or use a different library |
| Slow response, many tokens | Model retried failing code | Read the code items, simplify the task, cap tool calls |
Cost, latency and risk
Code execution adds cost in two ways. The code and its output count as tokens, and the provider may charge a fee per container session. A model that loops on failing code can run up both. Read the code items when a request is slow or expensive, and consider a cap on tool calls where your provider offers one.
Model-written code is untrusted. The sandbox protects your systems, because the code runs on the provider's side and cannot reach your network. It does not protect your data. Anything you upload is readable by the code, and the model can print it into the answer. Upload only what the task needs. If uploaded files contain text from outside sources, that text can carry instructions aimed at the model. Treat it as untrusted input.
When to use code execution
Use it for arithmetic, statistics, data cleaning on small files, format conversion, and charts. Do not use it when the code needs your private systems, a database connection, or a secret. For those, use a function tool, so your own code runs with your own access controls.
Exercise
A request with the codeinterpreter tool returns a wrong total, and response.outputtext gives no hint why. What do you inspect, and what do you check there?
Show answer
Inspect the codeinterpretercall items in response.output. Read the code the model wrote and, if you requested outputs with the include option, the results of the run. Check whether the code was correct and whether it ran at all. If no such item exists, the model answered from memory, so add an instruction to use code or force the tool.
Exercise
Your task needs the model to download a CSV from a public URL and summarize it. Why does the plain code interpreter fail here, and what are two ways to fix it?
Show answer
The sandbox has no internet access, so the code cannot download the file. One fix is to fetch the CSV in your own code and upload it to the container or pass its contents in the input. Another is to enable web search so the model can read the page, though that suits text better than large files.