Numbered architecture steps and arrows for building a first app with the OpenAI API
Tutorials
Beginner
20 min read Updated

OpenAI API Tutorial: Python & Node.js Guide (2026)

Build production AI apps with the OpenAI API in Python and Node.js. Learn Responses API, GPT-6.2 models, structured outputs, streaming, and error handling.

OpenAI API Tutorial Responses API Python Node.js TypeScript GPT-6.2 Structured Outputs

Building production AI software with this OpenAI API tutorial centers on the Responses API (/v1/responses), frontier GPT-6.2 models, and strongly typed Python and Node.js SDKs. Automatic prompt caching cuts cached input token costs by up to 90% and lowers time to first token by up to 80%, while constrained decoding guarantees valid JSON outputs.

Production engineering moves far beyond pasting prompts into a web chat window. Teams that master how to use the OpenAI API across both Python and TypeScript unlock deterministic data extraction, real-time token streaming, server-side conversation state, and resilient retry logic.

Key Takeaways

  • OpenAI Responses API (/v1/responses) supersedes Chat Completions for new applications by adding top-level instructions, optional server-side state via previous_response_id, and built-in tool execution.
  • OpenAI GPT-6.2 Astra handles deep frontier reasoning across a 200K context window, GPT-6.2 Sol balances speed and cost for agentic workflows, and GPT-6.1 Terra serves low-latency high-throughput pipelines.
  • Official OpenAI SDKs for Python (with Pydantic) and Node.js TypeScript (with Zod) enforce 100% JSON Schema adherence through Structured Outputs without brittle regex parsing.
  • Automatic OpenAI prompt caching on prefixes exceeding 1,024 tokens cuts cached read rates by up to 90% to 95%, while the Batch API discounts asynchronous workloads by 50%.

What Is the OpenAI Responses API vs Chat Completions?

The OpenAI Responses API (/v1/responses) is OpenAI’s primary unified endpoint for text generation, reasoning, and agentic tool loops, replacing stateless Chat Completions (/v1/chat/completions) for new builds by adding top-level instructions, typed output items, built-in tools, and optional server-side conversation state.

Chat Completions remains operational for legacy codebases and third-party OpenAI-compatible gateways. However, modern OpenAI API guide implementations standardize on the Responses API because it handles reasoning items, multi-step tool calls, and extended prompt cache retention natively.

Architectural Differences Between Responses and Chat Completions

Comparing Chat Completions vs Responses API reveals structural changes that reduce client-side boilerplate. Instead of assembling a messages array on every turn and digging into choices[0].message.content, developers pass instructions and input directly and read response.output_text.

Capability Chat Completions (/v1/chat/completions) Responses API (/v1/responses)
HTTP Endpoint POST /v1/chat/completions POST /v1/responses
Input Payload messages array of role/content dicts input string or array of typed items
System Guidance system or developer message entry Top-level instructions parameter
Conversation State Stateless; client resends full history Optional server-side state via store and previous_response_id
Primary Output Access response.choices[0].message.content response.output_text or typed response.output items
Built-In Tools External orchestration required Native web_search, file_search, code_interpreter

The OpenAI Responses API Migration Guide documents how the unified item schema also improves prompt cache hit rates across multi-turn agent loops. Storing intermediate reasoning items server-side prevents client serialization bugs between turns.

Selecting Frontier Models: GPT-6.2 Astra, GPT-6.2 Sol, and GPT-6.1 Terra

Choosing the right model ID directly governs latency, output quality, and monthly cloud spend. OpenAI organizes its current November 2026 frontier lineup into distinct tiers tailored to reasoning depth and throughput.

Model Name API Model ID Context Window Max Output Primary Engineering Role
GPT-6.2 Astra gpt-6.2-astra 200K tokens 100K tokens Frontier reasoning, architecture synthesis, hard coding
GPT-6.2 Sol gpt-6.2-sol 200K tokens 64K tokens Balanced default for multi-step agentic workflows
GPT-6.1 Terra gpt-6.1-terra 128K tokens 32K tokens High-throughput, low-latency streaming and routing
GPT-6 Luna gpt-6-luna 128K tokens 16K tokens Ultra-low-cost classification, tagging, and extraction

Evaluating GPT-6.2 Astra vs GPT-6.2 Sol comes down to task complexity and latency budgets. Reserve gpt-6.2-astra for multi-file code generation or deep technical planning where accuracy outweighs response time, and route standard interactive features to gpt-6.2-sol or gpt-6.1-terra.

Engineering teams weighing OpenAI API vs Anthropic API or OpenAI API vs Gemini API often evaluate context ceilings and ecosystem integrations. Anthropic Claude Sonnet 5.5 and Google Gemini 4 Hydrogen offer strong alternatives for massive 1M-token repositories, which we break down in our OpenAI vs Anthropic vs Google API comparison.

Migrating Existing Chat Completions Codebases

Teams planning to migrate from Chat Completions to Responses API should follow a staged rollout rather than a blind find-and-replace. Audit every client.chat.completions.create call, map system or developer roles to instructions, and update response extractors to output_text.

[!TIP] Pin explicit model snapshots and run your golden evaluation dataset against /v1/responses before cutting over production traffic. Because the Responses API handles reasoning items and tool schemas differently, verify tool-call parsing and token counts under realistic payloads first.

Prerequisites, Environment Setup, and API Key Security

Setting up an OpenAI API quickstart requires an isolated language runtime, the official SDK package, and a project-scoped API key loaded from environment variables. Installing dependencies inside isolated project environments prevents version drift across microservices.

Python and Node.js Runtime Installation

Python developers need Python 3.9+ and a virtual environment manager. The OpenAI Python SDK Repository on GitHub ships a strongly typed client with built-in Pydantic parsing and synchronous or asynchronous transports.

Create a clean project directory and install the Python dependencies:

mkdir openai-api-python
cd openai-api-python
python3 -m venv .venv
source .venv/bin/activate
pip install openai pydantic python-dotenv

On Windows PowerShell, activate the environment with .\.venv\Scripts\Activate.ps1. Confirm which python or Get-Command python points inside .venv before running scripts.

JavaScript and TypeScript teams need Node.js 22.6+ to run TypeScript files natively without a separate build step. The OpenAI Node.js and TypeScript SDK on GitHub provides full TypeScript declarations and Zod schema helpers out of the box.

Initialize a Node.js project and install the OpenAI SDK alongside Zod:

mkdir openai-api-node
cd openai-api-node
npm init -y
npm install openai zod dotenv

Both SDKs share consistent method names (client.responses.create, client.responses.parse, and client.responses.stream). That symmetry lets polyglot engineering teams share prompt patterns across backend services.

Generating Project-Scoped Keys and Secret Management

Understanding how to get an OpenAI API key securely is the first production guardrail. Open the OpenAI developer platform dashboard, create a dedicated project for each environment (development, staging, and production), and generate a project-scoped secret key (sk-proj-...).

OpenAI displays the secret key value only once inside the creation modal. Copy the key immediately and store it in your shell environment rather than committing it to Git or bundling it into frontend JavaScript.

Export the key inside your terminal session for macOS or Linux:

export OPENAI_API_KEY="sk-proj-your-actual-key-here"

For local development with .env files, add .env to .gitignore immediately and load secrets with python-dotenv or Node’s built-in --env-file=.env flag. Always configure a hard monthly spend limit in the OpenAI billing dashboard so runaway loops or leaked staging credentials cannot trigger uncapped charges.

To see how threat actors exploit PaaS environment variable breaches for unauthorized token spend and how OIDC federation eliminates static key exposure, examine our eMudhra, PHP2Shell, and Railway secret breach post-mortem.

Making Your First OpenAI API Call in Python and Node.js

Executing a first request with the OpenAI SDK requires instantiating the client class and calling client.responses.create. Both SDKs automatically read OPENAI_API_KEY from the process environment without passing raw credentials in code.

Python Quickstart with the Responses API

This OpenAI Python API tutorial snippet queries gpt-6.2-sol with explicit client timeouts and top-level instructions. Setting explicit timeouts prevents hanging upstream connections from starving web worker threads.

from openai import OpenAI

# Automatically loads OPENAI_API_KEY from the environment
client = OpenAI(timeout=30.0, max_retries=2)

response = client.responses.create(
    model="gpt-6.2-sol",
    instructions="You are a senior systems engineer. Answer directly in three sentences.",
    input="Explain why database connection pooling reduces tail latency.",
    temperature=0.2,
    max_output_tokens=250,
)

print(response.output_text)
print(f"Input tokens: {response.usage.input_tokens} | Output tokens: {response.usage.output_tokens}")

The temperature parameter controls sampling randomness, with 0.2 keeping technical answers focused and repeatable. Inspecting response.usage on every call gives immediate visibility into input, cached, and output token counts for cost accounting.

If your organization still maintains legacy endpoints, client.chat.completions.create remains available in the same SDK. New services should default to client.responses.create to keep tool execution and state handling uniform.

Node.js and TypeScript Quickstart

This OpenAI Node.js API tutorial example mirrors the exact workflow in TypeScript. Saving the file as quickstart.mts enables native ESM imports and direct execution on Node.js 22.6+.

import OpenAI from "openai";

const client = new OpenAI({
  timeout: 30_000,
  maxRetries: 2,
});

async function main(): Promise<void> {
  const response = await client.responses.create({
    model: "gpt-6.2-sol",
    instructions: "You are a senior systems engineer. Answer directly in three sentences.",
    input: "Explain why database connection pooling reduces tail latency.",
    temperature: 0.2,
    max_output_tokens: 250,
  });

  console.log(response.output_text);
  console.log(
    `Input tokens: ${response.usage?.input_tokens} | Output tokens: ${response.usage?.output_tokens}`
  );
}

main().catch((err) => {
  console.error("OpenAI request failed:", err);
  process.exit(1);
});

Run the OpenAI API TypeScript quickstart directly from the terminal without compiling via tsc:

node --experimental-strip-types quickstart.mts

Native type stripping keeps prototyping loops fast while retaining strict compile-time checking in your IDE. For production Docker builds, compile TypeScript to standard JavaScript or bundle with esbuild or tsx.

Managing Multi-Turn State with previous_response_id

Stateless Chat Completions forced applications to serialize and resend the entire conversation transcript on every turn. The Responses API supports optional server-side state by setting store=True and chaining follow-up calls with previous_response_id.

from openai import OpenAI

client = OpenAI(timeout=30.0)

first_turn = client.responses.create(
    model="gpt-6.2-sol",
    store=True,
    instructions="You are a concise Kubernetes SRE assistant.",
    input="Our checkout pod is restarting with exit code 137. What caused it?",
)

print("Turn 1:", first_turn.output_text)

second_turn = client.responses.create(
    model="gpt-6.2-sol",
    previous_response_id=first_turn.id,
    input="Give me the exact kubectl command to inspect its memory limit.",
)

print("Turn 2:", second_turn.output_text)

Passing previous_response_id eliminates manual message-array trimming on the client while preserving reasoning context across turns. Remember that historical tokens still count toward input billing and context limits, though OpenAI’s automatic prefix cache discounts repeated history heavily.

Enforcing Deterministic Schemas with Structured Outputs

Free-form prose breaks automated pipelines whenever a model adds markdown fences, extra commentary, or renamed keys. OpenAI Structured Outputs solve this failure mode by constraining token sampling logits at decode time so every response strictly matches your JSON Schema.

The OpenAI Structured Outputs Guide confirms that constrained decoding achieves 100% schema adherence on supported models. Downstream microservices can ingest validated objects directly into databases, queues, or UI components.

Python Structured Outputs with Pydantic

In Python, client.responses.parse accepts any BaseModel subclass from the Pydantic Documentation through the text_format parameter. The SDK converts the class to a strict JSON Schema and hydrates response.output_parsed automatically.

from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field

class IncidentTriage(BaseModel):
    service_name: str
    severity: Literal["low", "medium", "high", "critical"]
    observed_latency_ms: float = Field(description="Measured p95 latency in milliseconds")
    root_cause_hypothesis: str
    immediate_action: str

client = OpenAI(timeout=30.0)

response = client.responses.parse(
    model="gpt-6.2-sol",
    instructions="Extract structured incident telemetry from raw alert logs.",
    input="Alert: auth-gateway p95 latency spiked to 842ms after Redis primary failover. Flush stale pool connections.",
    text_format=IncidentTriage,
)

triage: IncidentTriage = response.output_parsed
print(f"Service: {triage.service_name} | Severity: {triage.severity}")
print(f"Action: {triage.immediate_action}")

Using Literal types and Field descriptions guides the model’s semantic choices while guaranteeing type safety. If the model refuses a request for safety reasons, check response.output[0].content[0].refusal before accessing output_parsed.

TypeScript Structured Outputs with Zod

Node.js services achieve the same compile-time and runtime guarantees using Zod alongside zodResponseFormat from openai/helpers/zod. Define the schema once in TypeScript and derive static types with z.infer.

import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const IncidentTriageSchema = z.object({
  service_name: z.string(),
  severity: z.enum(["low", "medium", "high", "critical"]),
  observed_latency_ms: z.number(),
  root_cause_hypothesis: z.string(),
  immediate_action: z.string(),
});

type IncidentTriage = z.infer<typeof IncidentTriageSchema>;

const client = new OpenAI({ timeout: 30_000 });

async function triageAlert(): Promise<void> {
  const response = await client.responses.create({
    model: "gpt-6.2-sol",
    instructions: "Extract structured incident telemetry from raw alert logs.",
    input: "Alert: auth-gateway p95 latency spiked to 842ms after Redis primary failover.",
    text: {
      format: zodResponseFormat(IncidentTriageSchema, "incident_triage"),
    },
  });

  const parsed: IncidentTriage = IncidentTriageSchema.parse(
    JSON.parse(response.output_text)
  );
  console.log(parsed.service_name, parsed.severity, parsed.immediate_action);
}

triageAlert();

Validating the parsed JSON back through IncidentTriageSchema.parse provides a defense-in-depth runtime check at the application boundary. Keep schemas flat and avoid deep recursive nesting, which can trigger HTTP 400 Bad Request validation errors.

Built-In Tools and Custom Function Calling Schemas

Beyond structured JSON extraction, the Responses API supports both built-in hosted tools (web_search, file_search, code_interpreter) and custom function calling definitions. Built-in tools execute server-side inside OpenAI’s runtime without requiring you to host search scrapers or sandboxes.

Custom function calling schemas let the model request live database lookups, billing actions, or internal API calls from your backend. Always enforce a strict maximum iteration count (such as 5 turns) on tool loops and pass tool exceptions back as function_call_output so the model can recover cleanly.

For deeper coverage of constrained decoding grammars, JSON mode caveats, and schema nesting limits, read our guide to structured outputs and JSON mode architecture.

Streaming Responses in Real Time with Server-Sent Events

Waiting four to eight seconds for a full completion creates sluggish chat interfaces and high user abandonment. Enabling streaming switches the OpenAI API transport to Server-Sent Events (SSE), delivering incremental token deltas as soon as inference begins.

Token Streaming in Python

The Python SDK exposes client.responses.stream as a context manager that handles connection cleanup automatically. Routing interactive streaming to gpt-6.1-terra typically delivers a 400ms time to first token for responsive user experiences.

from openai import OpenAI

client = OpenAI(timeout=30.0)

with client.responses.stream(
    model="gpt-6.1-terra",
    instructions="You are a concise DevOps engineer.",
    input="List five pre-deployment checks for a zero-downtime Postgres migration.",
) as stream:
    for event in stream:
        if event.type == "response.output_text.delta":
            print(event.delta, end="", flush=True)

    final_response = stream.get_final_response()

print(f"\n\nCompleted. Output tokens: {final_response.usage.output_tokens}")

Filtering on event.type == "response.output_text.delta" ensures your UI prints only user-visible text while ignoring lifecycle metadata events. Calling stream.get_final_response() after the loop gives you the full consolidated response and token usage metrics for logging.

Async Event Streaming in Node.js TypeScript

Node.js backends stream responses cleanly using for await...of over the async iterable returned when stream: true is set. This pattern maps directly to HTTP chunked transfer encoding or Express and Next.js route handlers.

import OpenAI from "openai";

const client = new OpenAI({ timeout: 30_000 });

async function streamChecklist(): Promise<void> {
  const stream = await client.responses.create({
    model: "gpt-6.1-terra",
    instructions: "You are a concise DevOps engineer.",
    input: "List five pre-deployment checks for a zero-downtime Postgres migration.",
    stream: true,
  });

  for await (const event of stream) {
    if (event.type === "response.output_text.delta") {
      process.stdout.write(event.delta);
    }
  }
  process.stdout.write("\n");
}

streamChecklist();

Forwarding event.delta directly to a ReadableStream keeps browser memory footprints flat even during multi-kilobyte code generations. Always attach an AbortController signal to cancel upstream OpenAI generation immediately if a client closes the browser tab.

Measuring Time to First Token and Handling Disconnects

Track two distinct latency metrics in production: Time to First Token (TTFT) and inter-token latency. High TTFT usually signals oversized uncached prompt prefixes or heavy reasoning effort, whereas jittery inter-token latency points to network congestion or server-side backpressure.

Explore production SSE proxies, WebSocket fallbacks, and backpressure buffering in our streaming LLM responses architecture guide.

Managing Token Costs, Prompt Caching, and the Batch API

Unchecked LLM usage scales cloud bills quickly when engineering teams send bloated prompts to flagship reasoning models. Effective OpenAI API pricing optimization combines model tier routing, automatic prompt caching, and asynchronous Batch API execution.

OpenAI Token Pricing and Long-Context Thresholds

OpenAI bills per 1 million tokens across standard input, cached input reads, and generated output tokens. Prompts exceeding 272,000 input tokens on extended-context workloads incur long-context pricing multipliers (typically 2x input and 1.5x to 2x output), making context hygiene essential.

Model Tier Standard Input (1M) Cached Read (1M) Standard Output (1M) Batch API (Input / Output) Best Workload Fit
GPT-6.2 Astra $8.00 $0.40 $40.00 $4.00 / $20.00 Complex reasoning, architecture review
GPT-6.2 Sol $2.00 $0.10 $10.00 $1.00 / $5.00 Multi-step agents, production code
GPT-6.1 Terra $0.40 $0.04 $1.60 $0.20 / $0.80 Real-time streaming, customer support
GPT-6 Luna $0.10 $0.01 $0.50 $0.05 / $0.25 Bulk classification, entity extraction

Notice the 80x input cost spread between gpt-6.2-astra ($8.00) and gpt-6-luna ($0.10). Routing simple classification and extraction steps to gpt-6-luna or gpt-6.1-terra while reserving gpt-6.2-astra for final synthesis routinely cuts total inference spend by over 60%.

Automatic Prompt Caching and Retention Windows

According to the OpenAI Prompt Caching Guide, automatic prompt caching activates on static prompt prefixes exceeding 1,024 tokens, delivering up to a 90% to 95% discount on cached input reads and up to an 80% latency reduction in time to first token.

No extra SDK flags are required for the default 30-minute cache window. On the Responses API, teams running long-lived agents can also opt into a 12-hour cache write retention window; the upfront cache write costs roughly 2.5x standard input, so use 12-hour retention only when shared system prompts or codebases are queried repeatedly across the workday.

[!NOTE] Prompt caching matches strictly from byte zero of the request prefix. Always place static instructions, tool JSON schemas, and reference documents at the very start of the prompt, and append dynamic timestamps, user IDs, or query strings strictly at the end.

Dive deeper into cache hit-rate telemetry, prefix ordering traps, and multi-provider caching rules in our LLM prompt caching optimization guide.

Cutting Asynchronous Workload Costs with the Batch API

Offline pipelines such as nightly document indexing, dataset labeling, and evaluation suites do not need sub-second responses. Submitting those requests as JSONL files through the OpenAI Batch API unlocks a flat 50% discount on both input and output tokens with a 24-hour completion SLA.

Batch API jobs also run against separate rate-limit pools, preventing massive offline backfills from starving live user-facing RPM and TPM quotas.

Production Error Handling, Rate Limits, and Troubleshooting

Production traffic inevitably encounters transient upstream spikes, malformed tool schemas, and quota ceilings. Reliable OpenAI API error handling inspects both the HTTP status code and the specific JSON error.code before deciding whether to retry or fail fast.

Diagnosing 401, 400, and Dual-Nature 429 Error Codes

OpenAI enforces Requests Per Minute (RPM) and Tokens Per Minute (TPM) limits globally across your entire organization rather than per individual API key. As detailed in the OpenAI Rate Limits Documentation, heavy JSON schemas for Structured Outputs and function calling count directly toward TPM ceilings and can trigger sudden throttling under concurrency.

HTTP Status error.code Value Root Cause Correct Production Action
401 Unauthorized invalid_api_key Missing, revoked, or wrong project key Fail fast; verify OPENAI_API_KEY and project scope
400 Bad Request invalid_request_error Unsupported schema nesting or invalid parameter Fail fast; fix payload or simplify JSON schema
429 Too Many Requests rate_limit_exceeded / slow_down Organization RPM or TPM limit exceeded Retry with exponential backoff, jitter, and Retry-After
429 Too Many Requests insufficient_quota Prepaid credit balance or monthly cap exhausted Do NOT retry; page billing owner immediately
500 / 503 Server Error server_error Transient OpenAI upstream inference fault Retry up to 3 times with backoff, then trip circuit breaker

The most common production bug in OpenAI integrations is blindly retrying every HTTP 429 error. If error.code is insufficient_quota, retries will never succeed and only add cascading latency to your API gateway.

Implementing Exponential Backoff with Jitter in Python

Set max_retries=0 on the SDK client when implementing custom retry policies so your wrapper has full control over error.code inspection, jittered delays, and observability metrics.

import random
import time
from openai import APIConnectionError, APIStatusError, OpenAI, RateLimitError

client = OpenAI(max_retries=0, timeout=15.0)

def generate_with_backoff(prompt: str, max_attempts: int = 4) -> str:
    for attempt in range(max_attempts):
        try:
            response = client.responses.create(
                model="gpt-6.1-terra",
                instructions="You are a concise backend engineering assistant.",
                input=prompt,
            )
            return response.output_text
        except RateLimitError as exc:
            error_code = getattr(exc, "code", None)
            if error_code in {"insufficient_quota", "credit_balance_exhausted"}:
                raise RuntimeError("OpenAI billing quota exhausted; aborting retries.") from exc

            delay = (2 ** attempt) + random.uniform(0.1, 0.75)
            print(f"Rate limited ({error_code}). Retrying in {delay:.2f}s...")
            time.sleep(delay)
        except APIConnectionError:
            delay = (2 ** attempt) + random.uniform(0.1, 0.5)
            time.sleep(delay)
        except APIStatusError as exc:
            if exc.status_code >= 500:
                time.sleep((2 ** attempt) + random.uniform(0.1, 0.5))
            else:
                raise

    raise RuntimeError("Exceeded maximum OpenAI API retry attempts.")

Adding randomized jitter (random.uniform) prevents thundering-herd retries where hundreds of workers slam the API at the exact same millisecond after a brief throttle window. For circuit breakers, multi-provider fallbacks, and dead-letter queues, review our production AI error handling patterns.

Production Readiness Guardrails and Turn Limits

Before deploying any OpenAI-powered feature to live traffic, lock down four operational guardrails: explicit per-request timeouts, hard organization spend limits, maximum agent loop turn caps, and automated eval suites.

Run a golden evaluation dataset of 50 to 200 real production inputs whenever you modify instructions, migrate from Chat Completions to the Responses API, or upgrade between gpt-6.1-terra, gpt-6.2-sol, and gpt-6.2-astra. Measuring schema pass rate, latency p95, and token cost per request catches regressions long before users see them.

Frequently Asked Questions

Should new projects use the OpenAI Responses API or Chat Completions?

New applications should target the OpenAI Responses API (/v1/responses) because it adds native built-in tools, top-level instructions, and optional server-side state via previous_response_id. The Chat Completions API remains supported for existing integrations and third-party OpenAI-compatible gateways.

How do I migrate from Chat Completions to the Responses API?

Replace client.chat.completions.create with client.responses.create, move system or developer prompts into the top-level instructions parameter, and pass user turns through input. Update response parsing from choices[0].message.content to response.output_text and re-run your evaluation suite before production cutover.

How do I get an OpenAI API key for Python and Node.js?

Create an account on the OpenAI developer platform, add a billing method, and generate a project-scoped secret key from the API keys dashboard. Export the key as the OPENAI_API_KEY environment variable immediately because the dashboard hides the string after the creation modal closes.

Which OpenAI model should I choose between GPT-6.2 Astra, GPT-6.2 Sol, and GPT-6.1 Terra?

Choose GPT-6.2 Astra for deep reasoning, complex architecture analysis, and high-stakes synthesis, and use GPT-6.2 Sol as the balanced default for multi-step agentic workflows. Route high-throughput extraction, classification, and low-latency UI streaming to GPT-6.1 Terra or GPT-6 Luna to minimize spend.

How much does the OpenAI API cost per million tokens?

OpenAI bills per million input and output tokens based on model tier, ranging from roughly $0.10 input and $0.50 output for GPT-6 Luna to $8.00 input and $40.00 output for GPT-6.2 Astra. Automatic prompt caching cuts cached input reads by up to 90% to 95%, and the Batch API discounts asynchronous jobs by 50%.

Why am I getting a 429 error even with low request volume?

OpenAI uses HTTP 429 for both rate throttling (rate_limit_exceeded or slow_down) and exhausted prepaid credits (insufficient_quota). Inspect error.code in the JSON payload to decide whether to apply exponential backoff or top up your organization billing balance.

Does OpenAI prompt caching require extra code changes?

Standard automatic prompt caching activates without extra flags whenever a prompt prefix exceeds 1,024 tokens and matches a recent request. Keep static instructions, tool schemas, and reference documents at the front of every request while appending dynamic user inputs at the end.

OpenAI API Tutorial Responses API Python Node.js TypeScript GPT-6.2 Structured Outputs

Found this helpful? Share it with others.

Raj, Founder, AI Agents Kit at AI Agents Kit

Raj

Founder, AI Agents Kit

Raj is the founder of AI Agents Kit, where he writes hands-on guides on AI agents, agent frameworks, Model Context Protocol (MCP), prompt engineering and developer tooling. He builds and tests the tools he covers and focuses on practical, working examples for developers and teams adopting agentic AI.

AI Agents LLMs Prompt Engineering Python TypeScript