Skip to content
E
Educatum
OpenAI API · Applied LLM

OpenAI API Interview Questions & Answers

15 production-grade OpenAI API interview questions with modern Python SDK (openai>=1.x) implementations—covering Responses vs. Chat Completions, 429 rate-limit architecture, SSE streaming, Structured Outputs, tool-calling loops, Prompt Caching, Batch API, embeddings, and regression evals.

15Questions
openai>=1.xPython SDK v1+
3Focus Areas
Updated:
My Study Hub →
OpenAI API production request lifecycle showing App/Client, tiktoken budgeting and 429 backoff, prompt cache and strict JSON schema, OpenAI API Responses/Tools/Batch execution, and SSE streaming plus evals telemetry.
Production OpenAI API lifecycle: pre-flight token budgeting, prompt-cache prefix alignment, surface selection, and streaming observability.

OpenAI API Surfaces at a Glance

Interviewers regularly ask you to pick the right OpenAI API surface for a given latency, cost, and statefulness constraint.

API SurfaceBest Used ForKey Latency / Cost LeverProduction Gotcha
Responses APINew stateful apps, built-in tools (web/file search), and reasoning state persistenceServer-side previous_response_id avoids re-sending full history; cache-friendly prefixMixing previous_response_id with manually mutated message arrays creates state drift
Chat CompletionsStateless pipelines, multi-provider LLM gateways, and portable messages[] wrappersFull client control over message truncation, summarization, and prompt caching prefixForgetting stream_options={"include_usage": True} omits final token counts in SSE
Structured OutputsGuaranteed schema adherence for extraction, classification, and UI JSON payloadsConstrained decoding eliminates retry loops caused by malformed JSON keys or typesRequires additionalProperties: false and all fields in required; check refusal first
Function CallingConnecting models to internal APIs, SQL/search retrievers, and bounded agent loopsParallel tool calls reduce round-trip turns; strict: true enforces typed argumentsUnbounded loops or unvalidated tool arguments can trigger runaway spend or side effects
Prompt CachingLong system prompts, static tool definitions, and few-shot instructions (>=1,024 tok)Automatic >=50% input cost reduction & lower TTFT on repeated 128-token prefix blocksPlacing timestamps, trace IDs, or RAG chunks before static instructions invalidates cache
Batch APIOffline evals, catalog enrichment, classification, and backfills tolerant of 24h SLA50% lower cost and separate higher batch rate-limit pools isolated from live trafficOmitting unique custom_id values or skipping error_file_id inspection hides partial failures
Embeddings (text-embedding-3)Semantic search, RAG indexing, deduplication, and clustering pipelinesMatryoshka dimensions truncation (e.g. 3072 -> 1024) cuts vector DB RAM & latencyQuerying an index with mismatched model or dimensions silently breaks cosine recall
Realtime APISub-second speech-to-speech voice agents with natural barge-in & VADDirect client WebRTC or server WebSocket skips separate STT -> LLM -> TTS hopsMint ephemeral session tokens server-side; never expose standard API keys to browsers
Focus Area 01

Core API & Reliability

API surface selection, rate-limit resilience, deterministic token budgets, SSE streaming, and idempotent timeouts.

Q1MediumAPI Architecture

When should you choose the Responses API over Chat Completions in new production services?

Direct Answer

Choose the Responses API for new single-provider OpenAI applications—especially agentic workflows using built-in tools, multimodal inputs, or reasoning models—where server-side state via previous_response_id and cleaner event-typed streaming simplify orchestration. Keep Chat Completions when you run a multi-provider gateway (OpenAI + Anthropic + open-weights behind one schema) or need 100% client-owned stateless message compaction.

Production Pitfall: Mixing stateful previous_response_id chains with client-side message edits creates silent divergence, and assuming Responses API state replaces your own durable audit log makes compliance debugging painful.
Q2HardReliability & 429

How do you design rate-limit handling (HTTP 429) for high-throughput OpenAI workloads?

Direct Answer

OpenAI enforces both RPM (requests/min) and TPM (tokens/min), reserving prompt tokens plus max_output_tokens / max_completion_tokens up front against TPM. Production services combine: (1) pre-flight tiktoken budgeting with tight output caps, (2) a distributed token-bucket limiter (Redis) ahead of egress, (3) honoring Retry-After and x-ratelimit-reset-tokens headers with bounded exponential backoff + full jitter, and (4) routing bulk async jobs to the Batch API.

python (openai>=1.x)
import random
import time
from openai import APIConnectionError, APIStatusError, OpenAI, RateLimitError

client = OpenAI(max_retries=0)  # Manage custom jittered backoff & Retry-After

def create_with_backoff(messages: list[dict], max_attempts: int = 5):
    for attempt in range(max_attempts):
        try:
            return client.chat.completions.create(
                model="gpt-4.1-mini",
                messages=messages,
                max_completion_tokens=512,
                timeout=20.0,
            )
        except RateLimitError as err:
            if attempt == max_attempts - 1:
                raise
            retry_after = err.response.headers.get("retry-after") if err.response else None
            base_delay = float(retry_after) if retry_after else min(32.0, 0.5 * (2 ** attempt))
            time.sleep(base_delay + random.uniform(0, 0.4 * base_delay))
        except (APIConnectionError, APIStatusError) as err:
            if isinstance(err, APIStatusError) and err.status_code < 500:
                raise  # Do not retry 400/401/403 client errors
            if attempt == max_attempts - 1:
                raise
            time.sleep(min(16.0, 0.5 * (2 ** attempt)) + random.uniform(0, 0.3))
Production Pitfall: Leaving max_tokens unset or huge (e.g., 16,384) for a 50-token classifier reserves massive TPM quota per request and triggers premature 429s; retrying without jitter causes thundering-herd retry storms.
Q3MediumStreaming SSE

How do you implement low-TTFT streaming with Server-Sent Events (SSE) while still capturing final token usage and errors?

Direct Answer

Stream tokens as soon as generated (stream=True) so users see first tokens in ~250–600ms (TTFT) instead of waiting seconds for full completion. In Chat Completions, pass stream_options={"include_usage": True} so the terminal chunk includes prompt_tokens, completion_tokens, and cached_tokens; in the Responses API, consume typed events such as response.output_text.delta and extract usage from response.completed. Flush chunks immediately and track finish_reason for mid-stream truncation.

python (openai>=1.x)
from openai import OpenAI

client = OpenAI()

def stream_answer(prompt: str) -> tuple[str, dict | None]:
    stream = client.chat.completions.create(
        model="gpt-4.1-mini",
        messages=[{"role": "user", "content": prompt}],
        stream=True,
        stream_options={"include_usage": True},
        timeout=30.0,
    )
    chunks: list[str] = []
    usage_summary: dict | None = None

    for event in stream:
        if event.choices:
            delta = event.choices[0].delta.content
            if delta:
                chunks.append(delta)
                print(delta, end="", flush=True)
        if event.usage is not None:
            usage_summary = {
                "prompt_tokens": event.usage.prompt_tokens,
                "completion_tokens": event.usage.completion_tokens,
                "cached_tokens": getattr(
                    event.usage.prompt_tokens_details, "cached_tokens", 0
                ),
            }
    return "".join(chunks), usage_summary
Production Pitfall: Forgetting stream_options={"include_usage": True} leaves chunk.usage as None on every chunk and breaks cost attribution, while reverse proxies (Nginx/Cloudflare) with response buffering enabled nullify streaming TTFT gains unless X-Accel-Buffering: no is set.
Q4MediumTokenization & Context

Why do token budgets drift between development and production, and how do you enforce context limits deterministically?

Direct Answer

Token counts drift when teams estimate with character heuristics (len(text) / 4), which undercounts dense JSON, code, CJK text, and special tokens, or when they ignore per-message framing tokens and tool/schema definitions. Enforce limits deterministically using tiktoken with the model-matched encoding (o200k_base for GPT-4o/4.1/o-series), count serialized tool schemas plus developer prompts, and reserve explicit headroom for max_output_tokens before dispatching.

Production Pitfall: Trimming only user messages without bounding retrieved RAG chunks or tool-call outputs leads to sudden context-window 400 errors in production on edge-case documents.
Q5MediumTimeouts & Idempotency

How do you handle transient timeouts, partial tool side effects, and idempotency in an LLM gateway?

Direct Answer

Set explicit connect/read/total timeouts via httpx.Timeout so stalled upstream connections cannot exhaust worker pools, attach a correlation trace_id (x-client-request-id) to every call, and separate read-only tool calls from mutating actions. For mutating workflows (billing, ticket writes, emails), generate a deterministic idempotency key per logical step in your database before executing the side effect so network retries never double-execute.

Production Pitfall: Retrying an entire multi-step agent turn after a read timeout at step 3 can replay non-idempotent POST/PATCH tool calls that already succeeded in step 2.
Focus Area 02

Structured Outputs & Agentic Tooling

Constrained JSON schemas, bounded multi-turn tool loops, reasoning model parameters, state compaction, and layered guardrails.

Q6MediumStructured Outputs

How do Structured Outputs (strict: true) differ from legacy JSON mode, and what schema rules must you obey?

Direct Answer

Legacy json_object mode only guarantees syntactically valid JSON, leaving keys, types, and nesting unverified. Structured Outputs (strict: true via json_schema or Pydantic parsing) compiles the schema into a context-free grammar that masks invalid tokens at decoding time, guaranteeing 100% schema compliance. Schemas must set additionalProperties: false on every object, list every property in required (representing optional fields as nullable unions like ["string", "null"]), and callers must inspect refusal before parsing JSON.

python (openai>=1.x)
import json
from openai import OpenAI

client = OpenAI()

TICKET_SCHEMA = {
    "name": "support_triage",
    "strict": True,
    "schema": {
        "type": "object",
        "properties": {
            "category": {"type": "string", "enum": ["billing", "auth", "bug"]},
            "severity": {"type": "integer"},
            "assignee_hint": {"type": ["string", "null"]},
        },
        "required": ["category", "severity", "assignee_hint"],
        "additionalProperties": False,
    },
}

resp = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[{"role": "user", "content": "SSO login returns 403 for EU tenants."}],
    response_format={"type": "json_schema", "json_schema": TICKET_SCHEMA},
)
msg = resp.choices[0].message
if msg.refusal:
    raise RuntimeError(f"Model refused request: {msg.refusal}")
payload = json.loads(msg.content)
Production Pitfall: Omitting additionalProperties: false or leaving an optional property out of required causes immediate 400 schema-validation failures; blindly calling json.loads() without checking message.refusal crashes when safety refusals occur.
Q7HardFunction Calling

Walk through a production multi-turn tool-calling loop. What safeguards prevent infinite loops and malformed arguments?

Direct Answer

A production tool loop maintains an allowlisted tool registry, caps iterations (e.g., max_steps=6), validates parsed JSON arguments with Pydantic before execution, runs tools with per-call timeouts, and returns recoverable validation or runtime errors back to the model as tool-role messages so it can self-correct. Always append the assistant message containing tool_calls before appending each matching tool_call_id response.

python (openai>=1.x)
import json
from openai import OpenAI

client = OpenAI()

def lookup_order(order_id: str) -> dict:
    return {"order_id": order_id, "status": "shipped", "eta_days": 2}

TOOLS_REGISTRY = {"lookup_order": lookup_order}
TOOL_SPECS = [{
    "type": "function",
    "function": {
        "name": "lookup_order",
        "strict": True,
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "string"}},
            "required": ["order_id"],
            "additionalProperties": False,
        },
    },
}]

def run_tool_loop(messages: list[dict], max_steps: int = 5) -> str:
    for _ in range(max_steps):
        resp = client.chat.completions.create(
            model="gpt-4.1-mini", messages=messages, tools=TOOL_SPECS
        )
        msg = resp.choices[0].message
        messages.append(msg.model_dump(exclude_none=True))
        if not msg.tool_calls:
            return msg.content or ""

        for tc in msg.tool_calls:
            fn = TOOLS_REGISTRY.get(tc.function.name)
            try:
                args = json.loads(tc.function.arguments)
                result = fn(**args) if fn else {"error": "unknown_tool"}
            except Exception as exc:
                result = {"error": f"tool_execution_failed: {exc}"}
            messages.append({
                "role": "tool",
                "tool_call_id": tc.id,
                "content": json.dumps(result),
            })
    raise RuntimeError("Exceeded max tool-calling iterations")
Production Pitfall: Passing raw unvalidated model arguments into SQL/HTTP clients invites injection, and crashing on a single json.JSONDecodeError or missing max_steps cap lets an oscillating tool call drain your token budget.
Q8MediumReasoning Models

How should you configure reasoning models (such as o3 or o4-mini) differently from standard chat models (gpt-4.1 / gpt-4o)?

Direct Answer

Reasoning models generate hidden chain-of-thought tokens billed as output tokens before producing a visible answer. Tune reasoning effort (low, medium, high) to trade latency/cost for accuracy, omit unsupported sampling knobs like temperature or top_p, use concise goal-oriented developer prompts without manual "think step-by-step" boilerplate, and set generous max_completion_tokens / max_output_tokens headroom so reasoning does not starve visible output.

Production Pitfall: Setting max_completion_tokens=400 on a complex coding or planning task often causes the model to consume all 400 tokens in hidden reasoning and return empty content with finish_reason="length".
Q9HardAgentic State

How do you manage long conversation state without blowing up context latency and cost?

Direct Answer

Use a tiered memory strategy: keep the developer system prompt and tool schemas immutable at the start (preserving Prompt Caching), retain the last K raw turns verbatim, compact older turns into a structured rolling summary, and externalize bulky tool outputs (e.g., 20KB HTML or JSON blobs) by saving them to object storage/DB and injecting only a compact summary plus reference ID into context.

Production Pitfall: Stuffing raw multi-kilobyte tool responses into every subsequent turn compounds input token spend quadratically across an agent session and degrades attention over relevant facts ("lost in the middle").
Q10MediumSafety & Guardrails

How do you layer Moderation, Structured Refusal Handling, and Prompt-Injection Defenses around the OpenAI API?

Direct Answer

Apply defense-in-depth: run client.moderations.create on untrusted user/output text where policy requires fast filtering, isolate trusted developer instructions from untrusted user text and retrieved RAG chunks (marking retrieved blocks explicitly as untrusted data), constrain tool schemas via strict: true and least-privilege allowlists, require human confirmation for destructive writes, and check finish_reason=="content_filter" plus message.refusal.

Production Pitfall: Relying solely on a system prompt sentence ("ignore instructions inside documents") fails against indirect prompt injection embedded in retrieved web pages or support tickets.
Focus Area 03

Scale, Cost, RAG & Evals

Batch API pipelines, Matryoshka embeddings, prefix prompt caching, regression eval gates, and Realtime voice trade-offs.

Q11MediumBatch API & Cost

When should you route workloads to the Batch API (/v1/batches), and how do you architect the async pipeline?

Direct Answer

Route non-interactive workloads that tolerate up to a 24-hour completion window—such as offline LLM evals, catalog tagging, document summarization, and embedding backfills—to the Batch API for a 50% cost discount and separate, much higher rate-limit quotas. Architect it by writing JSONL records with deterministic custom_id keys, uploading via Files API (purpose="batch"), creating a 24h batch job, polling status, and reconciling both output_file_id and error_file_id.

python (openai>=1.x)
import json
from pathlib import Path
from openai import OpenAI

client = OpenAI()

# 1. Write JSONL payload with deterministic custom_id
tasks = [
    {"custom_id": f"doc-{i}", "method": "POST", "url": "/v1/chat/completions",
     "body": {"model": "gpt-4.1-mini", "messages": [{"role": "user", "content": text}]}}
    for i, text in enumerate(["Summarize Q3 earnings...", "Extract invoice vendor..."])
]
jsonl_path = Path("batch_input.jsonl")
jsonl_path.write_text("\n".join(json.dumps(t) for t in tasks), encoding="utf-8")

# 2. Upload file and launch 24h batch job (-50% cost)
with jsonl_path.open("rb") as f:
    uploaded = client.files.create(file=f, purpose="batch")

batch = client.batches.create(
    input_file_id=uploaded.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)
# 3. Poll batch.id later -> download batch.output_file_id & inspect batch.error_file_id
Production Pitfall: Because batch output lines can arrive out of order and a "completed" job can still contain per-item failures, failing to assign unique custom_id keys or skipping error_file_id causes silent data loss.
Q12MediumEmbeddings & RAG

How do text-embedding-3 Matryoshka dimensions work, and how do you avoid RAG vector-space bugs?

Direct Answer

OpenAI text-embedding-3-small (default 1536d) and text-embedding-3-large (default 3072d) are trained with Matryoshka Representation Learning, meaning front-loaded dimensions retain most semantic signal. Passing dimensions=512 or dimensions=1024 returns smaller, normalized vectors that shrink pgvector/HNSW memory and speed up ANN search with minimal recall drop. Always batch chunks within the 8,191-token limit per input and keep model + dimensions identical between ingestion and query.

python (openai>=1.x)
from openai import OpenAI

client = OpenAI()

def embed_batch(chunks: list[str], dimensions: int = 1024) -> list[list[float]]:
    resp = client.embeddings.create(
        model="text-embedding-3-large",
        input=chunks,  # Batch multiple pre-chunked (<8191 tok) texts per HTTP call
        dimensions=dimensions,
    )
    # Sort by index to guarantee alignment with input order
    return [item.embedding for item in sorted(resp.data, key=lambda d: d.index)]
Production Pitfall: Changing dimensions or upgrading from ada-002 to text-embedding-3 at query time without re-indexing stored vectors produces nonsensical cosine similarity scores.
Q13MediumPrompt Caching

How does OpenAI Prompt Caching work automatically, and how do you structure prompts to maximize cache hit rates?

Direct Answer

Prompt Caching activates automatically for prompts of 1,024+ tokens and matches exact prefixes in 128-token increments, discounting cached input tokens by 50%+ and lowering TTFT. To maximize hit rate—monitored via usage.prompt_tokens_details.cached_tokens—place immutable content strictly at the front (system/developer instructions -> tool schemas -> static few-shot examples) and push all dynamic per-request variables (timestamps, user IDs, retrieved RAG snippets, user query) to the very end.

Production Pitfall: Injecting current_date, request_id, or user profile metadata at line 1 of the system prompt invalidates the entire prefix cache on every request.
Q14HardEvals & Quality

How do you build a regression Evals harness for OpenAI API prompt and model upgrades?

Direct Answer

Pin production model snapshots (never unpinned aliases without gating), curate a versioned golden dataset covering happy paths, edge cases, and adversarial injections, and run a two-tier eval suite in CI/CD: (1) deterministic assertions (JSON schema validity, regex/unit checks, latency p95, token cost), plus (2) calibrated LLM-as-a-judge rubrics using pairwise comparison with position-swapping against human-labeled anchor examples before promoting any prompt or model change.

Production Pitfall: Shipping a prompt edit or model version bump based on 5 manual "vibe checks" often introduces silent regressions on long-tail formatting or refusal rates.
Q15HardRealtime & Multimodal

What are the key architectural trade-offs between the Realtime API (WebRTC / WebSockets) and a chained STT -> LLM -> TTS pipeline?

Direct Answer

The Realtime API streams audio natively in/out over WebRTC (ideal for browser/mobile clients via ephemeral session tokens) or WebSockets (server-to-server), delivering sub-second conversational turn-taking, server VAD barge-in, and prosody preservation. A chained STT (Whisper/gpt-4o-transcribe) -> Responses API -> TTS pipeline adds ~500–1200ms latency but gives full intermediate transcript control, deterministic RAG/moderation gating before audio synthesis, and typically lower unit cost.

Production Pitfall: Proxying browser microphone audio through your own backend WebSocket instead of direct WebRTC adds extra network hops and audio jitter; minting standard API keys into client apps exposes credentials.

Frequently Asked Questions

Does OpenAI still test pre-v1.0 legacy Python SDK syntax in interviews?

No. Interviewers expect modern openai>=1.x Python SDK patterns (`from openai import OpenAI`), including Responses API vs. Chat Completions trade-offs, Structured Outputs (`strict: true`), and explicit `stream_options={"include_usage": True}`.

What is the single most common production OpenAI API bug interviewers look for?

Missing or naive 429 rate-limit and timeout handling—such as retrying without jitter, omitting `max_output_tokens` caps (which over-reserves TPM quota), or mutating the prompt prefix and silently breaking Prompt Caching.

How does this page relate to the OpenAI Company Interview Hub?

This guide focuses on applied OpenAI API engineering (SDKs, reliability, RAG, evals), while our OpenAI Company Hub covers reported OpenAI coding, concurrency, distributed systems, and ML loop prompts.

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.