- name
- openai-api
- description
- Build with OpenAI's stateless APIs - Chat Completions (GPT-5, GPT-4o), Embeddings, Images (DALL-E 3), Audio (Whisper + TTS), and Moderation. Includes Node.js SDK and fetch-based approaches for Cloudflare Workers.
Use when: implementing chat completions with GPT-5/GPT-4o, streaming responses with SSE, using function calling/tools, creating structured outputs with JSON schemas, generating embeddings for RAG (text-embedding-3-small/large), generating images with DALL-E 3, editing images with GPT-Image-1, transcribing audio with Whisper, synthesizing speech with TTS (11 voices), moderating content (11 safety categories), or troubleshooting rate limits (429), invalid API keys (401), function calling failures, streaming parse errors, embeddings dimension mismatches, or token limit exceeded.
# OpenAI API - Complete Guide
**Version**: Production Ready ✅
**Package**: openai@6.9.1
**Last Updated**: 2025-11-26
---
## 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. [Production Best Practices](#production-best-practices)
15. [Relationship to openai-responses](#relationship-to-openai-responses)
---
## Quick Start
### Installation
```bash
npm install openai@6.9.1
```
### 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
- **gpt-4**: Original GPT-4 model
### 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.1 (Released November 13, 2025)
**Latest model with major improvements**:
- **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 defaults to `reasoning_effort: 'none'` (vs GPT-5 defaulting to `'medium'`). Update your code when migrating!
### reasoning_effort Parameter
Controls thinking depth (available on GPT-5 and GPT-5.1):
- **"none"**: No reasoning (fastest, lowest latency) - GPT-5.1 default
- **"minimal"**: Quick responses, minimal thinking
- **"low"**: Basic reasoning
- **"medium"**: Balanced reasoning - GPT-5 default
- **"high"**: Deep reasoning for complex problems
```typescript
// GPT-5.1 with no reasoning (fast)
const completion = await openai.chat.completions.create({
model: 'gpt-5.1',
messages: [{ role: 'user', content: 'Simple query' }],
// reasoning_effort: 'none' is implicit default for GPT-5.1
});
// GPT-5.1 with high reasoning (complex tasks)
const completion = await openai.chat.completions.create({
model: 'gpt-5.1',
messages: [{ role: 'user', content: 'Solve this complex math problem...' }],
reasoning_effort: 'high',
});
```
### verbosity Parameter
Controls output detail (GPT-5/GPT-5.1):
- **"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?' }],
tools: tools,
});
```
### Handle Tool Calls
```typescript
const message = completion.choices[0].message;
if (message.tool_calls) {
for (const toolCall of message.tool_calls) {
const args = JSON.parse(toolCall.function.arguments);
const result = await executeFunction(toolCall.function.name, args);
// Send result back to model
await openai.chat.completions.create({
model: 'gpt-5.1',
messages: [
...messages,
message,
{
role: 'tool',
tool_call_id: toolCall.id,
content: JSON.stringify(result)
}
],
tools: tools,
});
}
}
```
**Loop pattern**: Continue calling API until no tool_calls in response.
---
## Structured Outputs
Structured outputs allow you to enforce JSON schema validation on model responses.
### Using JSON Schema
```typescript
const completion = await openai.chat.completions.create({
model: 'gpt-4o', // Note: Structured outputs best supported on GPT-4o
messages: [
{ role: 'user', content: 'Generate a person profile' }
],
response_format: {
type: 'json_schema',
json_schema: {
name: 'person_profile',
strict: true,
schema: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' },
skills: {
type: 'array',
GitHub에서 보기