openai-api
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.
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
Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.