Running Python-Based Analysis Through the OpenAI SDK
Running Python-Based Analysis Through the OpenAI SDK
Anatomy of a Code Interpreter Request
Running an analysis through the SDK is a normal client.responses.create() call with code_interpreter added to tools. The difference from a plain text request shows up on the way out, not the way in: the response's output list can now contain a mix of item types instead of a single text block.
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.6-terra",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
input=(
"Compute the first 15 Fibonacci numbers, then report their sum "
"and the ratio of the last two numbers."
),
)
for item in response.output:
print(item.type)
Running this typically prints something like code_interpreter_call followed by message. The code_interpreter_call item represents the tool call the model made — it carries the actual Python source the model wrote and the result the sandbox produced. The message item is the model's natural-language answer, built after it read that result. This matters because the final answer text (response.output_text) is only a summary; the full computational trail lives in the code_interpreter_call item, which is what you inspect when you need to verify what actually happened (a technique this unit returns to in Lesson 9).
Reading the Code Interpreter Call
You rarely need to parse every field of a code_interpreter_call item, but knowing it is there — and how to get at the code — is essential for debugging.
for item in response.output:
if item.type == "code_interpreter_call":
print("Code executed by the model:")
print(item.code)
print("Status:", item.status)
item.code is the literal Python the model generated. item.status reports whether the execution completed, failed, or is still in progress (relevant mainly for streaming responses, discussed below). Printing this during development is one of the fastest ways to understand why a model produced a particular number — you can copy the code out, run it yourself, and confirm it does what you expect.
Note: The exact attribute names on the
code_interpreter_calloutput item (code,status, and any nested result fields) are specific to the current API version. Verify the current schema in the official Responses API reference before writing code that depends on precise field names.
Containers: Ephemeral vs. Reused
Every code interpreter call runs inside a container — the actual sandboxed environment with its own filesystem and Python process. {"type": "auto"} tells the platform to create one for you automatically. For a single, one-off analysis question, this is exactly right and requires no extra bookkeeping.
The moment you need more than one exchange against the same data — "load this file, now show me a summary, now filter by region, now plot it" — you want the same container reused across calls, so that the loaded dataframe and any intermediate variables persist. Two things make that possible: the Responses API's built-in conversation state, and an explicit container ID.
The straightforward approach uses previous_response_id, which tells the platform to continue the same logical conversation, including reusing the container from the prior turn when code interpreter is involved:
first = client.responses.create(
model="gpt-5.6-terra",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
input="Create a Python list called `sales` with 12 monthly values: [120, 135, 150, 90, 80, 95, 110, 130, 140, 160, 175, 190].",
)
second = client.responses.create(
model="gpt-5.6-terra",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
previous_response_id=first.id,
input="Using the `sales` list from before, compute the month-over-month percentage change for each month.",
)
print(second.output_text)
The second call refers to sales without redefining it. Because previous_response_id chains the two requests, the platform routes the second request to the same underlying container where sales is still an in-memory variable from the first execution. Without that chaining, the second call would run in a brand-new container where sales was never defined, and the model would either fail or have to reconstruct the list from the conversation text — losing the benefit of a persistent session entirely.
Explicit Container Reuse
For workflows where you manage container lifecycle yourself — for example, a long-lived data-analysis session in a web application — you can capture the container ID from a response and pass it explicitly on later calls instead of relying on previous_response_id:
response = client.responses.create(
model="gpt-5.6-terra",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
input="Define x = 42 in Python and confirm.",
)
container_id = None
for item in response.output:
if item.type == "code_interpreter_call":
container_id = item.container_id
follow_up = client.responses.create(
model="gpt-5.6-terra",
tools=[{"type": "code_interpreter", "container": {"id": container_id}}],
input="What is x squared?",
)
print(follow_up.output_text)
This pattern is useful when your application needs to track container identity independently of the response-chaining mechanism — for instance, if you store container_id in your own session database alongside a user's analysis session, so you can resume it hours later without replaying the entire conversation history.
Note: Container reuse has time-based limits — an idle container is eventually recycled by the platform. Confirm current expiration behavior in the official documentation before designing a workflow that assumes a container stays alive indefinitely.
Streaming Output
For interactive applications, waiting for the entire analysis (code generation, execution, and final message) to finish before showing anything to the user produces a noticeably sluggish experience. Streaming lets you surface progress as it happens:
with client.responses.stream(
model="gpt-5.6-terra",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
input="Simulate rolling two six-sided dice 10,000 times and report the empirical probability of rolling a 7.",
) as stream:
for event in stream:
if event.type == "response.code_interpreter_call_code.delta":
print(event.delta, end="", flush=True)
elif event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
final_response = stream.get_final_response()
print("\n\nFinal answer:", final_response.output_text)
This prints the Python code as the model writes it, followed by the natural-language explanation as it streams in. stream.get_final_response() gives you the same complete response object you would have gotten from a non-streaming call, so streaming does not cost you access to any data — it only changes when you see it.
Note: Streaming event type names (such as
response.code_interpreter_call_code.delta) are specific to the current SDK version. Check the current event type reference before building production streaming logic around exact string matches.
Common Mistakes
Forgetting to re-attach tools on every call. The Responses API does not remember tool configuration from a previous turn just because you passed previous_response_id. If you omit code_interpreter from tools on the follow-up call, the model loses the ability to execute code for that turn even though the conversation continues.
Treating response.output_text as the complete story. It is a convenience property that concatenates the text portions of the output. It silently omits the executed code and any generated files, both of which often matter for a data-analysis feature. Always inspect response.output directly when you need the full trail.
Assuming a fresh {"type": "auto"} container on every call preserves state. It does not — each "auto" container is independent unless you chain requests with previous_response_id or pass the same container ID explicitly.
Best Practices
Log the executed code and the container ID for every analysis request in a production system. This is inexpensive to do and pays for itself the first time a user reports an unexpected number — you can immediately see what code ran instead of trying to reproduce the issue blind.
Chain related analysis turns with previous_response_id rather than re-sending the full dataset context in every prompt. This is both cheaper and more reliable, since the model works against actual persisted variables instead of re-parsing a restated summary of prior results.
Use streaming for any user-facing analysis feature with a visible latency budget. Code interpreter calls can take several seconds once a real dataset and a plotting library are involved; streaming the code and explanation keeps the interface feeling responsive even when the underlying computation is not instantaneous.