Claude
Skills
Sign in
Back

openai-api

Included with Lifetime
$97 forever

Complete guide for OpenAI's traditional/stateless APIs: Chat Completions (GPT-5, GPT-4o), Embeddings, Images (DALL-E 3), Audio (Whisper + TTS), and Moderation. Includes both Node.js SDK and fetch-based approaches for maximum compatibility. Use when: integrating OpenAI APIs, implementing chat completions with GPT-5/GPT-4o, generating text with streaming, using function calling/tools, creating structured outputs with JSON schemas, implementing embeddings for RAG, generating images with DALL-E 3, transcribing audio with Whisper, synthesizing speech with TTS, moderating content, deploying to Cloudflare Workers, or encountering errors like rate limits (429), invalid API keys (401), function calling failures, streaming parse errors, embeddings dimension mismatches, or token limit exceeded. Keywords: openai api, chat completions, gpt-5, gpt-5-mini, gpt-5-nano, gpt-4o, gpt-4-turbo, openai sdk, openai streaming, function calling, structured output, json schema, openai embeddings, text-embedding-3, dall-e-3, image generation, whisper api, openai tts, text-to-speech, moderation api, openai fetch, cloudflare workers openai, openai rate limit, openai 429, reasoning_effort, verbosity

Image & Video

What this skill does


# OpenAI API - Complete Guide

**Version**: Production Ready ✅
**Package**: [email protected]
**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

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 [email protected]
```

### 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

OpenAI supports three message roles:

1. **system** (formerly "developer"): Set behavior and context
2. **user**: User input
3. **assistant**: Model responses

```typescript
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:

```typescript
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

```typescript
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

```typescript
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**:
- ❌ `temperature` parameter
- ❌ `top_p` parameter
- ❌ `logprobs` parameter
- ❌ 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-responses` skill 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`:

```typescript
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

```typescript
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)

```typescript
const response = await fetch('https://api.openai.com/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
    'C
Files: 5
Size: 179.0 KB
Complexity: 50/100
Category: Image & Video

Related in Image & Video