Environment-Specific Configuration for Development and Production

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

Why One Configuration Is Never Enough

A development environment and a production environment have different needs even when they run the exact same code. In development, you want verbose logging, a cheap or fast model for quick iteration, and tolerance for occasional failures. In production, you want conservative logging (no sensitive data), the model your product actually depends on, strict timeouts, and alerting on any failure. Using identical configuration for both is not just wasteful — it is risky: a developer testing locally with the production API key can burn through production rate limits or accidentally cause production-billed usage from a laptop.

Environment-specific configuration means the same codebase behaves differently depending on which environment it is told it is running in, without any code branching on "if I'm in prod, do X." The branching happens once, in configuration, and the rest of the application just reads values.

The APP_ENV Switch

The standard mechanism is a single environment variable — commonly named APP_ENV or ENVIRONMENT — that names the current environment ("development", "staging", "production"), plus a small amount of code that loads the right values based on it.

import os
from dataclasses import dataclass
from enum import Enum


class Environment(str, Enum):
    DEVELOPMENT = "development"
    STAGING = "staging"
    PRODUCTION = "production"


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


_DEFAULTS = {
    Environment.DEVELOPMENT: {
        "model": "gpt-5.6-terra-mini",
        "log_level": "DEBUG",
        "request_timeout": 60.0,
    },
    Environment.STAGING: {
        "model": "gpt-5.6-terra",
        "log_level": "INFO",
        "request_timeout": 30.0,
    },
    Environment.PRODUCTION: {
        "model": "gpt-5.6-terra",
        "log_level": "WARNING",
        "request_timeout": 15.0,
    },
}


def load_config() -> AppConfig:
    env_name = os.environ.get("APP_ENV", "development")
    try:
        environment = Environment(env_name)
    except ValueError as exc:
        valid = ", ".join(e.value for e in Environment)
        raise RuntimeError(f"APP_ENV must be one of: {valid}") from exc

    defaults = _DEFAULTS[environment]
    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        raise RuntimeError("OPENAI_API_KEY is not set")

    return AppConfig(
        environment=environment,
        openai_api_key=api_key,
        model=os.environ.get("OPENAI_MODEL", defaults["model"]),
        log_level=os.environ.get("LOG_LEVEL", defaults["log_level"]),
        request_timeout=float(
            os.environ.get("OPENAI_TIMEOUT_SECONDS", defaults["request_timeout"])
        ),
    )

Two design choices here matter. First, Environment is an Enum, not a plain string. This means a typo like APP_ENV=produciton fails immediately with a clear error listing the valid values, instead of silently falling through to development-style defaults in what is actually a production deployment — a mistake that is dangerous precisely because nothing about it looks wrong until you look closely. Second, every default can still be overridden by an explicit environment variable (os.environ.get("OPENAI_MODEL", defaults["model"])). The per-environment table supplies sensible defaults, but an operator can always override a specific value without touching code — useful when, for example, you want to test a new model in production for a single deployment without changing the default for everyone.

Per-Environment .env Files

During local development, typing environment variables into your shell every time is tedious, and you cannot reasonably export OPENAI_API_KEY=... for every teammate. The common convention is a .env file — a plain text file of KEY=value lines — loaded by a library such as python-dotenv, with a separate file per environment: .env.development, .env.staging, and (rarely, and carefully) .env.production.

# .env.development
APP_ENV=development
OPENAI_API_KEY=sk-dev-xxxxxxxxxxxxxxxx
OPENAI_MODEL=gpt-5.6-terra-mini
LOG_LEVEL=DEBUG
from dotenv import load_dotenv
import os

env_name = os.environ.get("APP_ENV", "development")
load_dotenv(f".env.{env_name}", override=False)

config = load_config()

load_dotenv reads the file named .env.{env_name} and sets each key as an environment variable if it is not already set — override=False is deliberate: real environment variables set by the deployment platform (a container orchestrator, a CI system) should always win over anything in a local .env file. This ordering matters because it means the exact same code path works both for a developer running locally with a .env.development file and for a production container that has no .env file at all and relies entirely on variables injected by the platform.

.env files should never be committed to version control — each one typically holds either a real secret (development API keys still cost money and can be misused) or, in the case of a hypothetical .env.production, the actual production secret. A .gitignore entry for .env* (with a tracked .env.example containing placeholder values and no real secrets) is the standard pattern. Lesson 5 in this unit goes further into how production secrets are actually delivered to a deployed service — in most cloud deployments, it is not a .env file at all, but a secret store the platform injects at runtime.

Feature Flags

A feature flag is a configuration value that turns a piece of functionality on or off without a code deployment. In an OpenAI SDK application, a common use is gating a new prompt design, a new model, or an expensive feature (like automatically running a second verification call) behind a flag that can differ between environments — or even be enabled for a percentage of production traffic — without redeploying code.

from dataclasses import dataclass


@dataclass(frozen=True)
class FeatureFlags:
    use_verification_pass: bool
    enable_streaming: bool


def load_feature_flags() -> FeatureFlags:
    return FeatureFlags(
        use_verification_pass=os.environ.get("FF_VERIFICATION_PASS", "false") == "true",
        enable_streaming=os.environ.get("FF_STREAMING", "true") == "true",
    )


def answer_question(client, question: str, flags: FeatureFlags, model: str) -> str:
    response = client.responses.create(model=model, input=question)
    answer = response.output_text

    if flags.use_verification_pass:
        check = client.responses.create(
            model=model,
            input=f"Verify this answer is factually consistent: {answer}",
        )
        answer = f"{answer}\n\n[Verified: {check.output_text}]"

    return answer

use_verification_pass is a good example of what feature flags are for in an AI application specifically: the verification pass roughly doubles the API cost and latency of every request, so you might enable it in staging to validate the approach, keep it off in production until you are confident in it, and then flip it on for production once validated — all without touching answer_question itself. The function reads the flag value it was given; it does not know or care where that value came from, which is what keeps it testable with a fake FeatureFlags instance in unit tests.

class FakeResponse:
    def __init__(self, text: str) -> None:
        self.output_text = text


class FakeClient:
    def __init__(self, replies: list[str]) -> None:
        self._replies = list(replies)
        self.calls = 0

    class _Responses:
        def __init__(self, outer: "FakeClient") -> None:
            self._outer = outer

        def create(self, model: str, input: str) -> FakeResponse:
            self._outer.calls += 1
            return FakeResponse(self._outer._replies[self._outer.calls - 1])

    @property
    def responses(self) -> "FakeClient._Responses":
        return FakeClient._Responses(self)


def test_verification_pass_adds_a_second_call() -> None:
    client = FakeClient(["The sky is blue.", "Consistent."])
    flags = FeatureFlags(use_verification_pass=True, enable_streaming=False)

    result = answer_question(client, "What color is the sky?", flags, "gpt-5.6-terra")

    assert client.calls == 2
    assert "Verified: Consistent." in result
    print("PASS: verification pass triggers a second call and appends its result")


test_verification_pass_adds_a_second_call()

This test never touches the network — FakeClient returns pre-set replies and counts how many times it was called — but it verifies real behavior: that turning the flag on results in exactly two calls instead of one, and that the verification text is appended to the output. This is the value of designing answer_question to receive flags as a parameter rather than reading a global: the feature-flag logic is exercised by a fast, deterministic test with no API key and no cost.

Comparison: .env Files vs. Platform-Injected Environment Variables

Aspect.env filePlatform-injected environment variable
Where it livesA file on disk, loaded by your codeSet by the hosting platform before your process starts
Typical useLocal developmentStaging and production deployments
Secret safetyMust never be committed; still a plaintext file on someone's diskUsually backed by a managed secret store (see Lesson 5)
Who controls itEach developer, locallyDeployment configuration / platform operators
RotationManual edit and restartOften supported via the platform's secret rotation tooling

The important takeaway from this table is not that one mechanism is universally better, but that your application code should not need to know which one supplied a given value — it should just read os.environ. That indifference is exactly what load_config() earlier in this lesson achieves.

Common Mistakes

Reusing the same API key across development and production. A bug in a local script, or an accidental infinite loop while testing, then consumes production quota and shows up on the production bill. Provision separate keys per environment, even if they belong to the same OpenAI organization.

Committing a .env file to version control. Even a .env.development file often contains a real, working API key. Once committed, it exists in git history permanently, even if the file is later deleted or gitignored — the key must be revoked and rotated, not just removed.

Letting feature flags accumulate indefinitely. A flag added to test a change and never removed becomes a second, undocumented configuration surface that future developers have to reason about. Once a flagged feature is fully rolled out and stable, remove the flag and the old code path.

Best Practices

Make the environment name itself a validated value, using an Enum or an explicit allow-list, so a typo in APP_ENV fails loudly rather than silently defaulting to the wrong environment's behavior.

Keep per-environment defaults in code, but allow every value to be overridden by an explicit environment variable. This gives you sensible out-of-the-box behavior per environment while still allowing operational overrides without a code change.

Design flag-gated functions to receive the flag values as parameters, not to read global state, so the branching logic can be exercised in fast, dependency-injected tests exactly like any other configuration-dependent code path in this course.

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 Environment-Specific Configuration for Development and Production and get answers drawn from it.

Signed-in readers only.