Preparing an OpenAI SDK Application for Deployment

Ma Mahalakshmi V Updated 19 Sep 2026
8 min read ·Lesson 190 of 224

From Script to Service

A script that calls the OpenAI SDK from a Jupyter notebook or a python main.py invocation on your laptop is not the same thing as a deployable application. The script assumes a human is present to notice a crash, retype an API key, or install a missing package. A deployed service runs unattended, often on a machine you will never log into, and it has to survive restarts, missing environment variables, and dependency drift without a person watching it.

Preparing an application for deployment means removing every assumption that a human is standing next to it. Concretely, that means:

  • Configuration is read from the environment, not hardcoded or typed in interactively.
  • Dependencies are pinned to exact versions so the deployed environment matches the one you tested against.
  • The application has one clear entry point that can be started by a process manager or container runtime.
  • Output goes to structured logs, not print(), so it can be collected and searched later.
  • The application fails loudly and immediately when something required is missing, instead of failing silently or crashing deep inside a request handler.

This lesson covers the general preparation work. Later lessons in this unit build on it: Lesson 2 covers environment-specific configuration in depth, and Lesson 3 covers packaging the application into a container.

Separating Configuration from Code

Configuration is any value that changes between environments or deployments without the application's logic changing: API keys, model names, timeouts, database URLs, feature flags. If these values are written directly into your Python files, every environment needs its own copy of the source code, and secrets end up committed to version control.

The fix is to read configuration from environment variables at startup and fail immediately if a required one is missing, rather than letting None propagate into a request handler and fail confusingly later.

import os
from dataclasses import dataclass


class ConfigError(RuntimeError):
    """Raised when required configuration is missing or invalid."""


@dataclass(frozen=True)
class AppConfig:
    openai_api_key: str
    model: str
    request_timeout: float

    @classmethod
    def from_env(cls) -> "AppConfig":
        api_key = os.environ.get("OPENAI_API_KEY")
        if not api_key:
            raise ConfigError("OPENAI_API_KEY is not set")

        model = os.environ.get("OPENAI_MODEL", "gpt-5.6-terra")
        timeout_raw = os.environ.get("OPENAI_TIMEOUT_SECONDS", "30")
        try:
            timeout = float(timeout_raw)
        except ValueError as exc:
            raise ConfigError(
                f"OPENAI_TIMEOUT_SECONDS must be numeric, got {timeout_raw!r}"
            ) from exc

        return cls(openai_api_key=api_key, model=model, request_timeout=timeout)

This AppConfig.from_env() method does three things worth calling out. First, it reads every configuration value in one place, so nothing in the rest of the codebase calls os.environ.get directly — that keeps configuration auditable and testable. Second, it validates each value at load time: a missing API key or a non-numeric timeout raises ConfigError immediately, during startup, instead of surfacing as a confusing TypeError three layers deep in a request handler at 2 a.m. Third, the resulting AppConfig is a frozen dataclass, which means once it is constructed nothing in the application can silently mutate it mid-run — configuration for a running process should not change out from under it.

The frozen=True argument matters here specifically because configuration bugs caused by accidental mutation are hard to trace: something modifies config.model in one code path, and a completely unrelated code path starts behaving differently. Making the object immutable turns that class of bug into an AttributeError you see immediately.

Pinning Dependencies

When you pip install openai, you get whatever the latest version is on that day. If your production server installs dependencies fresh (which most deployment pipelines do), a new release of the openai package — or any transitive dependency — can change behavior under you without a single line of your code changing.

Pin exact versions in requirements.txt:

openai==2.6.0
fastapi==0.118.0
uvicorn==0.34.0
python-dotenv==1.0.1

Using == instead of >= means every install, on every machine, resolves to the exact same set of package versions. This is what makes a deployment reproducible: the code that passed your tests is, byte for byte in terms of dependencies, the code running in production. When you do want to upgrade a dependency, do it deliberately — bump the version number, run your test suite, and commit the change — rather than letting it happen implicitly on the next deploy.

Note: For applications with many dependencies, a lock-file-based tool (Poetry, pip-tools, or uv) is generally preferable to a hand-maintained requirements.txt, because it also pins transitive dependencies. The principle — exact, reproducible versions — is the same regardless of which tool enforces it.

Structuring an Application Entry Point

A script-style program does its work at import time — top-level code runs the moment the file is loaded. A deployable service needs a clear separation between defining the application and running it, so that a process manager, a test suite, or a container's CMD can each start it the same way.

from openai import OpenAI


def build_client(config: AppConfig) -> OpenAI:
    return OpenAI(api_key=config.openai_api_key, timeout=config.request_timeout)


def create_app():
    """Application factory: builds and returns a configured app instance."""
    config = AppConfig.from_env()
    client = build_client(config)

    from fastapi import FastAPI

    app = FastAPI()
    app.state.config = config
    app.state.openai_client = client

    @app.get("/")
    def root():
        return {"status": "ok", "model": app.state.config.model}

    return app


app = create_app()

create_app() is an application factory: a function that builds the application object instead of that object existing as a bare module-level global. This pattern matters for two practical reasons. First, tests can call create_app() with environment variables patched to test values, getting a fresh, isolated application instance instead of fighting with global state. Second, if the application ever needs multiple configurations (for example, running a smoke-test instance against a mock client), the factory makes that trivial — you just call it with different inputs — where a bare global object does not.

Notice that build_client takes the config object as a parameter rather than reading environment variables itself. This is the same dependency-injection idea used throughout this course's testing pattern: any function that depends on external configuration should receive it as an argument, not fetch it globally, so that it can be tested with fake configuration and no real API key.

Logging Instead of Print

print() statements go to standard output with no severity level, no timestamp, and no structure. In a deployed service, standard output is usually captured by the container runtime or process manager and forwarded somewhere for storage, but by the time it gets there it is an undifferentiated stream of text. Using Python's logging module instead gives you severity levels, timestamps, and the ability to route different messages to different destinations — all without changing the call sites.

import logging

logger = logging.getLogger("myapp")


def configure_logging(level: str = "INFO") -> None:
    logging.basicConfig(
        level=level,
        format="%(asctime)s %(levelname)s %(name)s %(message)s",
    )


def handle_request(prompt: str) -> None:
    logger.info("received request prompt_length=%d", len(prompt))
    try:
        pass  # call the OpenAI client here
    except Exception:
        logger.exception("request failed")
        raise

logger.exception deserves attention: called from inside an except block, it automatically attaches the full traceback to the log record, which logger.error does not do on its own. This is the difference between a log line that tells you something failed and one that tells you exactly where and why it failed — the second is what you need when debugging a production incident without a debugger attached. Lesson 9 in this unit goes further into structuring logs and monitoring failures; the point here is simply that print() should never appear in code destined for deployment.

Common Mistakes

Hardcoding secrets or model names directly in source files. This forces every environment to run identical code with different values baked in, which usually means someone edits the file by hand before each deploy — an error-prone process that also means the API key ends up in git history. Read every environment-dependent value from configuration instead.

Letting pip install resolve to "latest" in production. An unpinned dependency can introduce a breaking change between the version you tested and the version that gets installed on the server. Pin exact versions and upgrade deliberately.

Validating configuration lazily, inside request handlers. If a missing environment variable is only discovered when the first user request touches that code path, the failure surfaces as a confusing 500 error to a real user instead of a clear startup failure. Validate all configuration once, at startup.

Leaving print() debugging statements in place. They provide no severity, no timestamp, and are difficult to filter or search once the application is running unattended. Replace them with logging calls before deployment.

Best Practices

Load and validate configuration in one place, at startup. A single AppConfig.from_env() (or equivalent) function makes it obvious what the application requires to run, and it turns missing configuration into a startup crash rather than a runtime surprise.

Use dependency injection for anything external. Functions that need an OpenAI client, a database connection, or configuration values should receive them as parameters. This is what makes the application's core logic testable with fakes, per this course's established testing pattern, without real network calls.

Pin dependencies exactly and commit the pinned file. Reproducibility between your test environment and production is not optional for anything you intend to operate reliably.

Treat a missing or invalid environment variable as a startup failure, never a warning. A service that starts successfully with broken configuration is far more dangerous than one that refuses to start at all — the former fails silently under real traffic.

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 Preparing an OpenAI SDK Application for Deployment and get answers drawn from it.

Signed-in readers only.