Running Python-Based Analysis Through the OpenAI SDK

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 87 of 224

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_call output 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.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Running Python-Based Analysis Through the OpenAI SDK and get answers drawn from it.

Signed-in readers only.