- name
- openai-api
- description
- Use when implementing GPT chat, streaming, function calling, embeddings for RAG, images, audio or batch jobs, or troubleshooting 429 rate limits and API or TypeScript errors. Stateless OpenAI patterns that prevent 16 documented errors.
- user-invocable
- true
- domain
- engineering
# OpenAI API - Complete Guide
**Version**: Production Ready ✅
**Package**: openai@6.16.0
**Last Updated**: 2026-01-20
---
## Status
**✅ Production Ready**:
- ✅ Chat Completions API (GPT-5, GPT-4o, GPT-4 Turbo)
- ✅ Embeddings API (text-embedding-3-small, text-embedding-3-large)
- ✅ Images API (DALL-E 3 generation + GPT-Image-1 editing)
- ✅ Audio API (Whisper transcription + TTS with 11 voices)
- ✅ Moderation API (11 safety categories)
- ✅ Streaming patterns (SSE)
- ✅ Function calling / Tools
- ✅ Structured outputs (JSON schemas)
- ✅ Vision (GPT-4o)
- ✅ Both Node.js SDK and fetch approaches
---
## Table of Contents
1. [Quick Start](#quick-start)
2. [Chat Completions API](#chat-completions-api)
3. [GPT-5 Series Models](#gpt-5-series-models)
4. [Streaming Patterns](#streaming-patterns)
5. [Function Calling](#function-calling)
6. [Structured Outputs](#structured-outputs)
7. [Vision (GPT-4o)](#vision-gpt-4o)
8. [Embeddings API](#embeddings-api)
9. [Images API](#images-api)
10. [Audio API](#audio-api)
11. [Moderation API](#moderation-api)
12. [Error Handling](#error-handling)
13. [Rate Limits](#rate-limits)
14. [Common Mistakes & Gotchas](#common-mistakes--gotchas)
15. [TypeScript Gotchas](#typescript-gotchas)
16. [Production Best Practices](#production-best-practices)
17. [Relationship to openai-responses](#relationship-to-openai-responses)
---
## Quick Start
### Installation
```bash
npm install openai@6.16.0
```
### Environment Setup
```bash
export OPENAI_API_KEY="sk-..."
```
Or create `.env` file:
```
OPENAI_API_KEY=sk-...
```
### First Chat Completion (Node.js SDK)
```typescript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const completion = await openai.chat.completions.create({
model: 'gpt-5',
messages: [
{ role: 'user', content: 'What are the three laws of robotics?' }
],
});
console.log(completion.choices[0].message.content);
```
### First Chat Completion (Fetch - Cloudflare Workers)
```typescript
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-5',
messages: [
{ role: 'user', content: 'What are the three laws of robotics?' }
],
}),
});
const data = await response.json();
console.log(data.choices[0].message.content);
```
---
## Chat Completions API
**Endpoint**: `POST /v1/chat/completions`
The Chat Completions API is the core interface for interacting with OpenAI's language models. It supports conversational AI, text generation, function calling, structured outputs, and vision capabilities.
### Supported Models
#### GPT-5 Series (Released August 2025)
- **gpt-5**: Full-featured reasoning model with advanced capabilities
- **gpt-5-mini**: Cost-effective alternative with good performance
- **gpt-5-nano**: Smallest/fastest variant for simple tasks
#### GPT-4o Series
- **gpt-4o**: Multimodal model with vision capabilities
- **gpt-4-turbo**: Fast GPT-4 variant
#### GPT-4 Series (Legacy)
- **gpt-4**: Original GPT-4 model *(deprecated - use gpt-5 or gpt-4o)*
### Basic Request Structure
```typescript
{
model: string, // Model to use (e.g., "gpt-5")
messages: Message[], // Conversation history
reasoning_effort?: string, // GPT-5 only: "minimal" | "low" | "medium" | "high"
verbosity?: string, // GPT-5 only: "low" | "medium" | "high"
temperature?: number, // NOT supported by GPT-5
max_tokens?: number, // Max tokens to generate
stream?: boolean, // Enable streaming
tools?: Tool[], // Function calling tools
}
```
### Response Structure
```typescript
{
id: string, // Unique completion ID
object: "chat.completion",
created: number, // Unix timestamp
model: string, // Model used
choices: [{
index: number,
message: {
role: "assistant",
content: string, // Generated text
tool_calls?: ToolCall[] // If function calling
},
finish_reason: string // "stop" | "length" | "tool_calls"
}],
usage: {
prompt_tokens: number,
completion_tokens: number,
total_tokens: number
}
}
```
### Message Roles & Multi-turn Conversations
Three roles: **system** (behavior), **user** (input), **assistant** (model responses).
**Important**: API is **stateless** - send full conversation history each request. For stateful conversations, use `openai-responses` skill.
---
## GPT-5 Series Models
GPT-5 models (released August 2025) introduce reasoning and verbosity controls.
### GPT-5.2 (Released December 11, 2025)
**Latest flagship model**:
- **gpt-5.2**: 400k context window, 128k output tokens
- **xhigh reasoning_effort**: New level beyond "high" for complex problems
- **Compaction**: Extends context for long workflows (via API endpoint)
- **Pricing**: $1.75/$14 per million tokens (1.4x of GPT-5.1)
```typescript
// GPT-5.2 with maximum reasoning
const completion = await openai.chat.completions.create({
model: 'gpt-5.2',
messages: [{ role: 'user', content: 'Solve this extremely complex problem...' }],
reasoning_effort: 'xhigh', // NEW: Beyond "high"
});
```
### GPT-5.1 (Released November 13, 2025)
**Warmer, more intelligent model**:
- **gpt-5.1**: Adaptive reasoning that varies thinking time dynamically
- **24-hour extended prompt caching**: Faster follow-up queries at lower cost
- **New developer tools**: apply_patch (code editing), shell (command execution)
**BREAKING CHANGE**: GPT-5.1/5.2 default to `reasoning_effort: 'none'` (vs GPT-5 defaulting to `'medium'`).
### O-Series Reasoning Models
Dedicated reasoning models (separate from GPT-5):
| Model | Released | Purpose |
|-------|----------|---------|
| **o3** | Apr 16, 2025 | Successor to o1, advanced reasoning |
| **o3-pro** | Jun 10, 2025 | Extended compute version of o3 |
| **o3-mini** | Jan 31, 2025 | Smaller, faster o3 variant |
| **o4-mini** | Apr 16, 2025 | Fast, cost-efficient reasoning |
```typescript
// O-series models
const completion = await openai.chat.completions.create({
model: 'o3', // or 'o3-mini', 'o4-mini'
messages: [{ role: 'user', content: 'Complex reasoning task...' }],
});
```
**Note**: O-series may be deprecated in favor of GPT-5 with `reasoning_effort` parameter.
### reasoning_effort Parameter
Controls thinking depth (GPT-5/5.1/5.2):
- **"none"**: No reasoning (fastest) - GPT-5.1/5.2 default
- **"minimal"**: Quick responses *(Note: May not be available - [Issue #1690](https://github.com/openai/openai-node/issues/1690))*
- **"low"**: Basic reasoning
- **"medium"**: Balanced - GPT-5 default
- **"high"**: Deep reasoning
- **"xhigh"**: Maximum reasoning (GPT-5.2 only)
### verbosity Parameter
Controls output detail (GPT-5 series):
- **"low"**: Concise
- **"medium"**: Balanced (default)
- **"high"**: Verbose
### GPT-5 Limitations
**NOT Supported**:
- ❌ `temperature`, `top_p`, `logprobs` parameters
- ❌ Stateful Chain of Thought between turns
**Alternatives**: Use GPT-4o for temperature/top_p, or `openai-responses` skill for stateful reasoning
---
## Streaming Patterns
Enable with `stream: true` for token-by-token delivery.
### Node.js SDK
```typescript
const stream = await openai.chat.completions.create({
model: 'gpt-5.1',
messages: [{ role: 'user', content: 'Write a poem' }],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
```
### Fetch (Cloudflare Workers)
```typescript
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-5.1',
messages: [{ role: 'user', content: 'Write a poem' }],
stream: true,
}),
});
const reader = response.body?.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader!.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n').filter(line => line.trim() !== '');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') break;
try {
const json = JSON.parse(data);
const content = json.choices[0]?.delta?.content || '';
console.log(content);
} catch (e) {
// Skip invalid JSON
}
}
}
}
```
**Server-Sent Events (SSE) format**:
```
data: {"id":"chatcmpl-xyz","choices":[{"delta":{"content":"Hello"}}]}
data: [DONE]
```
**Key Points**: Handle incomplete chunks, `[DONE]` signal, and invalid JSON gracefully.
---
## Function Calling
Define tools with JSON schema, model invokes them based on context.
### Tool Definition & Request
```typescript
const tools = [{
type: 'function',
function: {
name: 'get_weather',
description: 'Get current weather for a location',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' },
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
},
required: ['location']
}
}
}];
const completion = await openai.chat.completions.create({
model: 'gpt-5.1',
messages: [{ role: 'user', content: 'What is the weather in SF?' }],
在 GitHub 查看