OpenAI API - Complete Guide
Version: Production Ready ✅ Package: openai@6.7.0 Last Updated: 2025-10-25
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
- [Quick Start](#quick-start)
- [Chat Completions API](#chat-completions-api)
- [GPT-5 Series Models](#gpt-5-series-models)
- [Streaming Patterns](#streaming-patterns)
- [Function Calling](#function-calling)
- [Structured Outputs](#structured-outputs)
- [Vision (GPT-4o)](#vision-gpt-4o)
- [Embeddings API](#embeddings-api)
- [Images API](#images-api)
- [Audio API](#audio-api)
- [Moderation API](#moderation-api)
- [Error Handling](#error-handling)
- [Rate Limits](#rate-limits)
- [Production Best Practices](#production-best-practices)
- [Relationship to openai-responses](#relationship-to-openai-responses)
Quick Start
Installation
npm install openai@6.7.0
Environment Setup
export OPENAI_API_KEY="sk-..."
Or create .env file:
OPENAI_API_KEY=sk-...
First Chat Completion (Node.js SDK)
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)
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
- gpt-4: Original GPT-4 model
Basic Request Structure
{
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
{
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
OpenAI supports three message roles:
- system (formerly "developer"): Set behavior and context
- user: User input
- assistant: Model responses
const messages = [
{
role: 'system',
content: 'You are a helpful assistant that explains complex topics simply.'
},
{
role: 'user',
content: 'Explain quantum computing to a 10-year-old.'
}
];
Multi-turn Conversations
Build conversation history by appending messages:
const messages = [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'What is TypeScript?' },
{ role: 'assistant', content: 'TypeScript is a superset of JavaScript...' },
{ role: 'user', content: 'How do I install it?' }
];
const completion = await openai.chat.completions.create({
model: 'gpt-5',
messages: messages,
});
Important: Chat Completions API is stateless. You must send full conversation history with each request. For stateful conversations, use the openai-responses skill.
GPT-5 Series Models
GPT-5 models (released August 2025) introduce new parameters and capabilities:
Unique GPT-5 Parameters
reasoning_effort
Controls the depth of reasoning:
- "minimal": Quick responses, less reasoning
- "low": Basic reasoning
- "medium": Balanced reasoning (default)
- "high": Deep reasoning for complex problems
const completion = await openai.chat.completions.create({
model: 'gpt-5',
messages: [{ role: 'user', content: 'Solve this complex math problem...' }],
reasoning_effort: 'high', // Deep reasoning
});
verbosity
Controls output length and detail:
- "low": Concise responses
- "medium": Balanced detail (default)
- "high": Verbose, detailed responses
const completion = await openai.chat.completions.create({
model: 'gpt-5',
messages: [{ role: 'user', content: 'Explain quantum mechanics' }],
verbosity: 'high', // Detailed explanation
});
GPT-5 Limitations
NOT Supported with GPT-5:
- ❌
temperatureparameter - ❌
top_pparameter - ❌
logprobsparameter - ❌ Chain of Thought (CoT) persistence between turns
If you need these features:
- Use GPT-4o or GPT-4 Turbo for temperature/top_p/logprobs
- Use
openai-responsesskill for stateful CoT preservation
GPT-5 vs GPT-4o Comparison
| Feature | GPT-5 | GPT-4o | |---------|-------|--------| | Reasoning control | ✅ reasoning_effort | ❌ | | Verbosity control | ✅ verbosity | ❌ | | Temperature | ❌ | ✅ | | Top-p | ❌ | ✅ | | Vision | ❌ | ✅ | | Function calling | ✅ | ✅ | | Streaming | ✅ | ✅ |
When to use GPT-5: Complex reasoning tasks, mathematical problems, logic puzzles, code generation When to use GPT-4o: Vision tasks, when you need temperature control, multimodal inputs
Streaming Patterns
Streaming allows real-time token-by-token delivery, improving perceived latency for long responses.
Enable Streaming
Set stream: true:
const stream = await openai.chat.completions.create({
model: 'gpt-5',
messages: [{ role: 'user', content: 'Tell me a story' }],
stream: true,
});
Streaming with Node.js SDK
import OpenAI from 'openai';
const openai = new OpenAI();
const stream = await openai.chat.completions.create({
model: 'gpt-5',
messages: [{ role: 'user', content: 'Write a poem about coding' }],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
Streaming with Fetch (Cloudflare Workers)
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
'Co