Receber por email
← Voltar para o catálogo

openai-api

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 struc

15estrelas
Atualizado há 11 meses

Ver no GitHub ↗ Licença: MIT

Como adicionar

/plugin marketplace add jackspace/ClaudeSkillz

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/openai-api/svg)](https://www.skillteca.com.br/skills/openai-api)

Skills relacionadas

Ver todas de Automação →

Alerta por categoria

Receba novas skills de Automação toda segunda

1 email curto, só com as skills novas de Automação. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

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

  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

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:

  1. system (formerly "developer"): Set behavior and context
  2. user: User input
  3. 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:

  • ❌ 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:

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
Compartilhar X LinkedIn