Skip to main content
December 2025 Update: Now covers the new Responses API, Predicted Outputs, structured outputs with response_format, and GPT-4.5 capabilities.

Why This Module Matters

The OpenAI API is the most widely-used LLM interface. Every AI startup, enterprise AI feature, and AI-powered tool uses it or something similar. Master this, and you can build anything.
Career Impact: Companies pay $200-350K for engineers who can build reliable, production-grade AI features. This module teaches exactly that.

What’s New in 2025

Your Development Environment

Security: Never hardcode API keys. Never commit .env files. Use environment variables or secret managers in production.

Chat Completions: The Foundation

Chat completions are the bread and butter of every LLM application. The mental model is simple: you send a conversation (a list of messages with roles), and the model continues the conversation. Think of it like passing a script to an actor — the system message is the stage direction, the user messages are the audience’s lines, and the assistant messages are the actor’s previous lines. The model reads the whole script and generates the next line.

The Complete Request Object

Production-Ready Chat Function

Streaming: Real-Time Responses

Why Streaming Matters

Without streaming, users wait 5-30 seconds staring at nothing. With streaming, they see the first token within 200-500ms — even if the full response takes 10 seconds. This is the same principle behind progressive image loading on the web: perceived performance matters as much as actual performance. In user studies, a streaming response that takes 10 seconds total feels faster than a non-streaming response that takes 5 seconds, because the user sees progress immediately.

Production Streaming with FastAPI

Function Calling: LLMs That Take Action

Function calling is the bridge between “chatbot” and “agent.” Without it, an LLM can only generate text. With it, an LLM can check the weather, query a database, send an email, or call any API you expose. The model does not actually execute the function — it generates a structured request (“call get_weather with city=Paris”), you execute it in your code, and you feed the result back. This keeps the LLM in the reasoning seat while your code handles the doing.

The Pattern

  1. You define functions the model can “call” (name, description, parameters)
  2. Model decides which function to call based on user input
  3. You execute the function and return results (the model never runs code)
  4. Model uses results to form final response

Complete Function Calling System

Parallel Function Calls

GPT-4 can call multiple functions in one response:

Function Calling Edge Cases

Edge case — the model calls a function you did not expect: The model might call send_email when you only expected search_products. Always validate the function name before executing. Never blindly dispatch tool calls without checking that the function is safe for the current context. Edge case — malformed arguments: The model occasionally generates invalid JSON in the arguments field, especially for complex nested schemas. Wrap json.loads(tool_call.function.arguments) in a try/except and return a helpful error message to the model so it can retry. Edge case — infinite tool-call loops: The model might call a function, get a result, and decide to call the same function again with slightly different parameters. Set a maximum loop count (3-5 iterations) and force a final response with tool_choice="none" after the limit. Edge case — tool_choice="required" vs. "auto": Use "auto" (default) when the model should decide whether to call a function. Use "required" when you know a function call is needed (e.g., the user said “book the flight”). Use {"type": "function", "function": {"name": "specific_func"}} when you need a specific function called — useful for structured extraction where you want the model to always populate a schema.

Structured Outputs: Guaranteed JSON

Structured outputs solve the single most frustrating problem in LLM engineering: parsing. Before this feature, you would ask the model for JSON and get back… sometimes JSON, sometimes JSON wrapped in markdown, sometimes a conversational response with JSON buried in it, and sometimes invalid JSON that crashes your parser. Structured outputs use constrained decoding to guarantee the output matches your schema. It is not “usually works” — it is mathematically guaranteed.

Structured Output Methods Compared

When to use which: Use json_schema with strict: true for new projects — it is the gold standard. Use Instructor when you need Pydantic validators that go beyond schema validation (e.g., “age must be between 0 and 150”). Use json_object only as a fallback for older models that do not support strict schemas.

The Problem Structured Outputs Solve

With Structured Outputs - Guaranteed

Complex Nested Extraction

Vision: Processing Images

Image Analysis

Multiple Images

Production Error Handling

Cost Optimization Strategies

Cost optimization is not about being cheap — it is about being smart. The difference between a well-optimized and naive LLM application can be 10-50x in monthly spend. The biggest lever is model selection: gpt-4o-mini handles 80% of tasks at 6% of the cost. The second biggest lever is prompt length: every token in your system prompt is charged on every single request.

Model Selection Matrix

Cost Estimation Quick Reference

For back-of-envelope cost estimation, use these rules of thumb: Edge case — hidden cost multipliers: Function calling adds tokens for the function schemas on every request (often 200-500 tokens per function). If you define 10 functions, that is 2,000-5,000 extra input tokens per request. Only include functions relevant to the current context, not your entire function catalog. Edge case — conversation history growth: In multi-turn chat, you resend the entire conversation history on every request. A 20-turn conversation might accumulate 10,000+ tokens of history, costing 5-10x more than the first message. Implement conversation summarization or sliding window truncation for long conversations.

Smart Model Router

Mini-Project: AI Customer Support Bot

Key Takeaways

Streaming Is Essential

Always stream for user-facing apps. Nobody wants to wait 10 seconds for a response to appear.

Functions Enable Actions

Function calling turns LLMs from chatbots into agents that can search, book, send, and execute.

Structured Outputs Save Time

Use Pydantic models + json_schema for guaranteed parseable responses. No more regex parsing.

Cost Awareness Matters

gpt-4o-mini is 17x cheaper. Use it for simple tasks, save gpt-4o for complex reasoning.

Temperature, top_p, and Penalties: A Decision Guide

These parameters interact in subtle ways. Most developers either ignore them entirely or tweak them randomly. Here is a principled framework: Key rule: Change either temperature or top_p, never both at once. They control the same underlying mechanism (token sampling distribution) from different angles. Adjusting both creates unpredictable interactions. Edge case — temperature=0 is not truly deterministic: OpenAI’s documentation says “best-effort.” In practice, you will see occasional variation even at temperature=0 due to floating-point non-determinism in GPU computation. If you need reproducibility, also set seed — but even then, OpenAI only guarantees “mostly deterministic.” For true determinism, use the logprobs response to verify consistency.

Bonus: Responses API (2025)

The Responses API is OpenAI’s next-generation interface, designed to fix the rough edges of chat completions. The key difference: instead of managing a messages array yourself, you pass a single input and optional instructions. It also handles multi-turn conversations, tool calls, and file search natively without you managing the message flow. For new projects, prefer this over chat completions. For existing projects, there is no urgency to migrate — chat completions will continue to work.

Predicted Outputs (Speed Boost)

Predicted outputs exploit a clever optimization: when the model’s output is likely to be very similar to something you already have (like refactoring code), you provide the “prediction” and the model only needs to generate the diff. Under the hood, tokens that match the prediction are processed much faster. The result is 2-5x faster generation for edit-like tasks. When you know most of the output in advance (like code refactoring), use predicted outputs for 2-5x faster generation:
When to use Predicted Outputs: Code editing, document revisions, template filling—any time the output is structurally similar to something you already have.

What’s Next

Vector Databases

Store embeddings at scale with pgvector and Pinecone for semantic search

Interview Deep-Dive

Strong Answer:
  • The architecture has three layers: structured extraction, function calling, and error handling. I would use structured outputs with a strict JSON schema for the extraction step, function calling for the API interaction, and a retry wrapper around the entire flow.
  • For extraction, I would define Pydantic models that represent the business entities — say, an OrderIntent with fields like action (enum: track, return, cancel), order_id (optional string), and reason (optional string). I would use response_format with json_schema and strict: True to guarantee the output matches. This is critical because without strict mode, you get “usually valid” JSON, and “usually” is not good enough when a parse failure crashes your webhook handler at 3am.
  • For function calling, I would define tools for each internal API (lookup_order, initiate_return, etc.) with tight parameter schemas. The key design decision: never let the model construct free-form API calls. Every parameter should be constrained — enums for status values, regex patterns for IDs, explicit required fields. The model decides WHICH function to call and with what arguments; my code validates and executes.
  • The failure modes I would design around: (1) The model hallucinates a function that does not exist — handle with a strict whitelist check before execution. (2) The model extracts a plausible-looking but invalid order_id — validate against the database before processing. (3) Rate limits during high-traffic periods — implement exponential backoff with jitter, and a circuit breaker that falls back to a human agent queue after 3 failed retries. (4) The model returns valid JSON but semantically wrong data (extracts the wrong order_id from a message mentioning multiple orders) — add a confirmation step for high-stakes actions like cancellations.
Follow-up: Your structured output extraction works 99.2% of the time in testing, but in production you are seeing a 3% failure rate on certain user messages. How do you debug this?
  • The gap between test and production is almost always input distribution. Test data is clean and well-formed; production users write in fragments, mix languages, include typos, and paste content from other apps. I would start by pulling the 3% failures and categorizing them.
  • Common culprits: (1) Messages that are too long and get truncated by max_tokens on the response side — the model starts generating the JSON but hits the token limit before closing all brackets. Fix: increase max_tokens for extraction tasks or truncate the input. (2) Messages with special characters or Unicode that confuse the tokenizer. (3) Ambiguous messages where the model cannot confidently fill a required field and produces a schema violation trying to leave it blank.
  • I would add logging that captures the raw input, the model’s raw output, and the Pydantic validation error for every failure. Then I would batch the failure cases into categories, create regression tests for each category, and either adjust the prompt to handle edge cases or add pre-processing to normalize the input before it hits the model.
Strong Answer:
  • Temperature and top_p both control randomness, but through different mechanisms. Temperature scales the logits before softmax: at 0 the model always picks the highest-probability token (deterministic), at 1 it samples from the natural distribution, and at 2 it flattens the distribution dramatically so even low-probability tokens have a decent chance. Top_p (nucleus sampling) is a different approach: it dynamically truncates the distribution to include only the smallest set of tokens whose cumulative probability exceeds p. At top_p=0.1, only the most likely tokens are considered; at top_p=1.0, all tokens are candidates.
  • The critical mistake: changing both simultaneously. They interact in non-obvious ways. If you set temperature=0.3 and top_p=0.5, you are double-constraining the distribution — the temperature already concentrated probability on top tokens, and then top_p further truncates. The result is more deterministic than either setting alone, which is usually not what you want. OpenAI’s own documentation says to change one or the other, not both.
  • Frequency penalty and presence penalty both reduce repetition, but differently. Frequency penalty scales with how many times a token has appeared — it penalizes “the” more each time “the” appears. Presence penalty is binary: it penalizes a token the same amount whether it has appeared once or ten times. Use frequency penalty (0.3-0.8) when the model gets stuck repeating phrases. Use presence penalty (0.3-0.6) when you want topic diversity — it encourages the model to explore new concepts rather than rehashing the same point.
  • My production defaults: temperature=0 for extraction and classification (determinism matters), temperature=0.7 with top_p=1.0 for conversational responses, frequency_penalty=0.3 for any task where repetition is noticeable. I almost never touch presence_penalty because it can cause the model to go off-topic.
Follow-up: You set temperature=0 for determinism, but you notice that the same prompt sometimes gives different outputs. Why, and how do you get true reproducibility?
  • Temperature=0 is “approximately deterministic” but not guaranteed. There are several sources of non-determinism: GPU floating-point operations are not associative (the order of additions changes the result at the bit level), different hardware produces slightly different rounding, and OpenAI may route your request to different GPU clusters. The seed parameter helps — when you set it, OpenAI returns a system_fingerprint in the response, and outputs are deterministic as long as the fingerprint matches. But the fingerprint can change when OpenAI updates their infrastructure.
  • For true reproducibility in production, I cache the response keyed on the hash of the full request (messages + model + seed + all parameters). If the same request comes in again, return the cached response. This also saves money and reduces latency. For evaluation, I run each test case 3 times and check that all 3 outputs match; if they diverge, I flag it as a non-determinism issue and increase the test tolerance.
Strong Answer:
  • At 500K calls/month, cost optimization is not about saving pennies — it is likely a $5K-50K/month line item depending on model mix. The first step is instrumentation: log every API call with model, input tokens, output tokens, task type, and calculated cost. Without this data, you are optimizing blind.
  • The biggest lever is model routing. I would categorize every API call by task: classification, extraction, summarization, generation, reasoning. Then I would benchmark GPT-4o-mini against GPT-4o for each category using our actual prompts and a labeled evaluation set. In my experience, GPT-4o-mini handles classification and extraction at 95%+ of GPT-4o accuracy at 6% of the cost. That alone, if 60% of our calls are simple tasks, cuts our bill by 50%.
  • The second lever is prompt length. Output tokens cost 2-4x more than input tokens. A verbose system prompt is cheap (amortized across many requests), but a verbose response is expensive on every single call. I would audit our prompts: add max_tokens limits to every call (prevents runaway responses), add explicit length constraints in the system prompt (“respond in 2-3 sentences”), and remove any unnecessary context from the messages array.
  • The third lever is caching. If the same question gets asked repeatedly (common in customer support), cache the response keyed on a hash of the messages. Even a 10% cache hit rate on 500K calls saves 50K API calls per month. Use Redis with a TTL of 1-24 hours depending on how dynamic your data is.
  • The fourth lever is batching. For non-real-time workloads (nightly summarization, weekly report generation), use the Batch API which offers a 50% discount in exchange for up to 24-hour turnaround.
Follow-up: After implementing model routing and caching, your costs dropped 45% but you are getting complaints that some responses feel “dumber” since the switch. How do you investigate?
  • The routing logic is probably miscategorizing some complex queries as simple and sending them to GPT-4o-mini when they need GPT-4o. I would pull the complaints, match them to the logged API calls, and check which model served each one. If the pattern is “all complaints were served by mini,” the routing heuristic is too aggressive.
  • The fix is a quality feedback loop. Add a thumbs-up/thumbs-down to the UI, log the feedback with the request metadata, and periodically review which task types have the lowest satisfaction scores on GPT-4o-mini. Move those task types back to GPT-4o. You can also implement a “try cheap first, escalate if bad” pattern: route to GPT-4o-mini, use a lightweight quality check on the response (length, confidence score, keyword presence), and if it fails, automatically retry with GPT-4o. This adds latency for the escalated cases but keeps costs low for the majority.