Skip to main content
Lesson 14 of 20 · API Tools: Search, Files, and Code Interpreter

Data Workflows with Code Interpreter

Lesson 14 of 20 Updated November 2, 2026 Developer
On this page
  1. Data Workflows with Code Interpreter
  2. Workflow 1: Automated Financial Report
  3. Workflow 2: Cohort Analysis
  4. Workflow 3: Scoring and Segmentation
  5. Workflow 4: Forecasting and Trends
  6. Orchestrating a Multi-Step Workflow
  7. Key Takeaways

Lesson updated November 2, 2026 based on OpenAI documentation: the Code Interpreter tool requires a container parameter (added to all examples), text parts of the input are of type input_text, and web search uses the web_search tool (web_search_preview is now a legacy tool without domain filters). Generated files are retrieved using the fichiers_generes and telecharger functions from Lesson 10. Files attached to the message are uploaded with the user_data purpose, which OpenAI recommends for model inputs (File inputs). Sources: Code Interpreter · Web search.

Data Workflows with Code Interpreter

Previous lessons covered individual tasks one by one. Real analysis chains them together: you import, clean, calculate, visualize, and export. It’s the chain—not each isolated step—that consumes time when done manually.

The four workflows below are real-world cases, deliberately varied: periodic reporting, behavioral analysis over time, segmentation, and forecasting. Read them less for the code and more for the prompt structure—numbered, explicit about expected deliverables, and precise about format. This structure turns a vague request into an actionable report, and you can apply it directly to your own data.

Workflow 1: Automated Financial Report

Periodic reporting is the best candidate for automation for a simple reason: the files change, but the report structure doesn’t. Once you write and validate the prompt for one month, it works for the next eleven. Note the final instruction, which requests an Excel export per section. This makes the result directly shareable, rather than leaving you with text that needs reformatting.

from openai import OpenAI

client = OpenAI()

# Upload source files
files = {}
for name in ["revenus_2025.xlsx", "depenses_2025.xlsx", "budget_previsionnel.xlsx"]:
    with open(name, "rb") as f:
        file_obj = client.files.create(file=f, purpose="user_data")
        files[name] = file_obj.id

content = [
    {"type": "input_text", "text": (
        "Generate a complete financial report from these 3 files: "
        "1. SUMMARY: Total revenue, gross margin, net income "
        "2. MONTHLY ANALYSIS: Month-over-month evolution with variations "
        "3. BUDGET VARIANCES: Actual vs. forecast comparison, significant variances "
        "4. CHARTS: "
        "   - Revenue and expenses evolution (dual axis) "
        "   - Budget variance waterfall "
        "   - Expense breakdown by category "
        "5. EXPORT: Excel file with one tab per section"
    )}
]
for fid in files.values():
    content.append({"type": "input_file", "file_id": fid})

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[{"role": "user", "content": content}],
    tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
    instructions=(
        "Produce a professional report. "
        "Display figures with thousands separators. "
        "Use European format (decimal comma). "
        "Comment on each significant variance (> 5%)."
    )
)

# Retrieve all generated files
for ann in fichiers_generes(response):
    telecharger(client, ann, f"sortie_{ann.filename}")
    print(f"Generated: {ann.filename}")

Workflow 2: Cohort Analysis

Cohort analysis tracks groups formed at the same entry date over time. Few teams perform this calculation regularly because setting it up is tedious. That’s precisely why it pays to delegate it: the logic is standard; only the data changes.

with open("utilisateurs.csv", "rb") as f:
    file_obj = client.files.create(file=f, purpose="user_data")

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_text", "text": (
                "Perform a cohort analysis on this user data: "
                "1. Define cohorts by signup month "
                "2. Calculate retention rate per cohort (month 1, 2, ..., 12) "
                "3. Create a retention heatmap "
                "4. Identify the cohort with the best retention "
                "5. Estimate LTV per cohort "
                "6. Export the retention table as CSV"
            )},
            {"type": "input_file", "file_id": file_obj.id}
        ]
    }],
    tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
    instructions=(
        "Show the code step by step. "
        "Display intermediate results. "
        "For the heatmap, use a green palette (dark = good, light = low). "
        "Annotate each cell with the percentage."
    )
)

Workflow 3: Scoring and Segmentation

Here, the model doesn’t just describe the data; it builds a score and forms groups. This requires a precaution: always ask for the method in addition to the result. A segment like “at-risk customers” without the criteria that produced it is unusable: no one can challenge, reproduce, or correct it.

def segmenter_clients(file_path: str) -> dict:
    """Segments customers using RFM and clustering."""
    with open(file_path, "rb") as f:
        file_obj = client.files.create(file=f, purpose="user_data")

    response = client.responses.create(
        model="gpt-5.6-terra",
        input=[{
            "role": "user",
            "content": [
                {"type": "input_text", "text": (
                    "Perform RFM customer segmentation: "
                    "1. Calculate Recency, Frequency, Monetary for each customer "
                    "2. Assign an RFM score from 1 to 5 for each dimension "
                    "3. Create segments: Champions, Loyal, At Risk, Lost "
                    "4. Apply K-Means (k=4 to 8, choose the best k using elbow method) "
                    "5. Visualize segments in 2D (PCA or t-SNE) "
                    "6. Profile each segment: size, average revenue, frequency "
                    "7. Export: CSV with segment per customer + PDF-like report"
                )},
                {"type": "input_file", "file_id": file_obj.id}
            ]
        }],
        tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
        instructions=(
            "Use sklearn for clustering. "
            "Normalize variables before clustering. "
            "Display the elbow plot to justify the choice of k. "
            "Create a radar chart per segment."
        )
    )

    output_files = []
    for ann in fichiers_generes(response):
        telecharger(client, ann, ann.filename)
        output_files.append(ann.filename)

    return {
        "analysis": response.output_text,
        "files": output_files
    }

Forecasting is the workflow where caution matters most. The container can run a regression or seasonal decomposition, and it will do so even when your data isn’t suitable—twenty data points are enough to produce a perfectly presentable curve that is completely meaningless. Demand the confidence interval and the model assumptions: this is what distinguishes a projection from an extrapolation.

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_text", "text": (
                "Based on this monthly sales data: "
                "1. Decompose the time series (trend, seasonality, residual) "
                "2. Apply exponential smoothing (Holt-Winters) "
                "3. Forecast the next 6 months with a 95% confidence interval "
                "4. Compare with a simple linear regression "
                "5. Generate a chart with history + forecasts "
                "6. Calculate error metrics (MAE, RMSE, MAPE)"
            )},
            {"type": "input_file", "file_id": file_obj.id}
        ]
    }],
    tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
    instructions=(
        "Use statsmodels for decomposition and forecasting. "
        "Color the confidence interval in transparent blue. "
        "Clearly mark the separation between history and forecasts."
    )
)

Orchestrating a Multi-Step Workflow

Beyond a certain size, a single prompt hits its limits: the analysis drifts, an intermediate instruction gets forgotten, and you lose track of which step you’re on. Breaking the process into successive calls, all working within the same container where files from the previous step remain available, restores what you lost—a checkpoint after each step, and the ability to resume from the faulty step instead of restarting everything.

class WorkflowData:
    def __init__(self):
        self.client = OpenAI()
        # An explicit container: files produced remain available from one step to the next
        self.container = self.client.containers.create(name="workflow-data")
        self.intermediate_files = []

    def step(self, instruction: str, file_ids: list[str] | None = None) -> str:
        """Executes a workflow step in the shared container."""
        content = [{"type": "input_text", "text": instruction}]
        for fid in file_ids or []:
            content.append({"type": "input_file", "file_id": fid})

        response = self.client.responses.create(
            model="gpt-5.6-terra",
            input=[{"role": "user", "content": content}],
            tools=[{"type": "code_interpreter", "container": self.container.id}],
        )

        # Memorize generated files to download at the end
        self.intermediate_files.extend(fichiers_generes(response))
        return response.output_text

    def download_results(self, output_folder: str):
        """Downloads generated files before the container expires."""
        import os
        os.makedirs(output_folder, exist_ok=True)
        for ann in self.intermediate_files:
            telecharger(self.client, ann, os.path.join(output_folder, ann.filename))

# Usage
wf = WorkflowData()

# Step 1: Import and clean
with open("donnees_brutes.csv", "rb") as f:
    file_obj = client.files.create(file=f, purpose="user_data")

wf.step(
    "Clean this CSV: remove duplicates, handle missing values, "
    "normalize types. Export the result.",
    [file_obj.id]
)

# Step 2: Analysis
wf.step("Calculate key KPIs and identify trends.")

# Step 3: Visualization
wf.step("Create 4 key charts for an executive report.")

# Step 4: Export
wf.step("Compile everything into an Excel file with tabs and embedded charts.")

wf.download_results("./sortie_workflow/")

Key Takeaways

  • Break complex workflows into steps with file passing
  • Use detailed instructions for each step
  • The model natively handles statistical analysis and basic machine learning
  • Systematically retrieve intermediate files for traceability
  • Combine data analysis and visualization in a single call for complete reports