Communitygithub.com

OpenAI API – Vollständiger Leitfaden

Erstellen Sie Anwendungen mit den zustandslosen APIs von OpenAI – Chat Completions (GPT-5, GPT-4o), Embeddings, Bilder (DALL-E 3), Audio (Whisper + TTS) und Moderation. Inklusive Node.js SDK und fetch-basierten Ansätzen für Cloudflare Workers.

Was ist OpenAI API – Vollständiger Leitfaden?

Diese Fertigkeit ist ein umfassender Leitfaden für die Nutzung der OpenAI-APIs, der sich auf die zustandslosen Chat Completions-, Embeddings-, Bilder-, Audio- und Moderations-APIs konzentriert. Sie richtet sich an Entwickler, die diese APIs direkt nutzen möchten, entweder mit dem offiziellen Node.js SDK oder über einfache fetch-Aufrufe, die sich besonders für serverlose Umgebungen wie Cloudflare Workers eignen. Der Leitfaden behandelt wichtige Modelle wie die GPT-5-Serie (einschließlich des neuen GPT-5.1), GPT-4o (mit Vision-Funktionen) sowie spezialisierte Modelle wie DALL-E 3 für die Bildgenerierung und Whisper für die Audio-Transkription. Es werden ausführlich Streaming-Muster mit Server-Sent Events (SSE), Function Calling/Tools, strukturierte Ausgaben mit JSON-Schemas und Best Practices für die Fehlerbehandlung und Ratenbegrenzung behandelt. Die Fertigkeit enthält auch wichtige Details zu Modellparametern (z. B. reasoning_effort und verbosity für GPT-5), die Bedeutung der Dimensionsreduzierung für Embeddings und die Unterschiede zwischen den GPT-5- und GPT-4o-Modellen. Darüber hinaus wird auf Änderungen in GPT-5.1 hingewiesen, wie die Standardeinstellung für reasoning_effort auf 'none' und die neuen Entwickler-Tools apply_patch und shell. Entwickler lernen, wie sie zustandslose Interaktionen mit vollständigem Chat-Verlauf durchführen, Funktionsaufrufe in einer Schleife handhaben und strukturierte Antworten für eine zuverlässige Datenverarbeitung erzwingen.

Funktioniert mit~Claude Code✓Codex CLI~Cursor✓Antigravity
npx skills add https://github.com/David-Li0406/meta-skill-evloving/tree/HEAD/AgentSkillOS/data/skill_seeds/openai-api

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht OpenAI API – Vollständiger Leitfaden?

Version: Produktionsbereit ✅
Paket: [email protected]
Zuletzt aktualisiert: 2025-11-26


Status

✅ Produktionsbereit:

  • ✅ 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 Generierung + GPT-Image-1 Bearbeitung)
  • ✅ Audio API (Whisper Transkription + TTS mit 11 Stimmen)
  • ✅ Moderation API (11 Sicherheitskategorien)
  • ✅ Streaming-Muster (SSE)
  • ✅ Function Calling / Tools
  • ✅ Strukturierte Ausgaben (JSON-Schemas)
  • ✅ Vision (GPT-4o)
  • ✅ Sowohl Node.js SDK als auch fetch-Ansätze

Inhaltsverzeichnis

  1. Schnellstart
  2. Chat Completions API
  3. GPT-5 Serienmodelle
  4. Streaming-Muster
  5. Function Calling
  6. Strukturierte Ausgaben
  7. Vision (GPT-4o)
  8. Embeddings API
  9. Images API
  10. Audio API
  11. Moderation API
  12. Fehlerbehandlung
  13. Ratenbegrenzung
  14. Best Practices für die Produktion
  15. Beziehung zu openai-responses

Schnellstart

Installation

npm install [email protected]

Umgebungseinrichtung

export OPENAI_API_KEY="sk-..."

Oder erstellen Sie eine .env-Datei:

OPENAI_API_KEY=sk-...

Erste 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: 'Was sind die drei Gesetze der Robotik?' }
  ],
});

console.log(completion.choices[0].message.content);

Erste 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: 'Was sind die drei Gesetze der Robotik?' }
    ],
  }),
});

const data = await response.json();
console.log(data.choices[0].message.content);

Chat Completions API

Endpunkt: POST /v1/chat/completions

Die Chat Completions API ist die Kernschnittstelle für die Interaktion mit den Sprachmodellen von OpenAI. Sie unterstützt konversationelle KI, Textgenerierung, Function Calling, strukturierte Ausgaben und Vision-Funktionen.

Unterstützte Modelle

GPT-5 Serie (Veröffentlicht August 2025)

  • gpt-5: Voll ausgestattetes Reasoning-Modell mit erweiterten Fähigkeiten
  • gpt-5-mini: Kostengünstige Alternative mit guter Leistung
  • gpt-5-nano: Kleinste/schnellste Variante für einfache Aufgaben

GPT-4o Serie

  • gpt-4o: Multimodales Modell mit Vision-Funktionen
  • gpt-4-turbo: Schnelle GPT-4 Variante

GPT-4 Serie

  • gpt-4: Ursprüngliches GPT-4 Modell

Grundlegende Anfragestruktur

{
  model: string,              // Zu verwendendes Modell (z.B. "gpt-5")
  messages: Message[],        // Gesprächsverlauf
  reasoning_effort?: string,  // Nur GPT-5: "minimal" | "low" | "medium" | "high"
  verbosity?: string,         // Nur GPT-5: "low" | "medium" | "high"
  temperature?: number,       // Wird von GPT-5 NICHT unterstützt
  max_tokens?: number,        // Maximale Anzahl zu generierender Token
  stream?: boolean,           // Streaming aktivieren
  tools?: Tool[],             // Function Calling Tools
}

Antwortstruktur

{
  id: string,                 // Eindeutige Completion-ID
  object: "chat.completion",
  created: number,            // Unix-Zeitstempel
  model: string,              // Verwendetes Modell
  choices: [{
    index: number,
    message: {
      role: "assistant",
      content: string,        // Generierter Text
      tool_calls?: ToolCall[] // Falls Function Calling
    },
    finish_reason: string     // "stop" | "length" | "tool_calls"
  }],
  usage: {
    prompt_tokens: number,
    completion_tokens: number,
    total_tokens: number
  }
}

Nachrichtenrollen & Mehrfach-Konversationen

Drei Rollen: system (Verhalten), user (Eingabe), assistant (Modellantworten).

Wichtig: Die API ist zustandslos – senden Sie den vollständigen Gesprächsverlauf bei jeder Anfrage. Für zustandsbehaftete Konversationen verwenden Sie die openai-responses-Fertigkeit.


GPT-5 Serienmodelle

GPT-5 Modelle (veröffentlicht August 2025) führen Reasoning- und Ausführlichkeitssteuerung ein:

GPT-5.1 (Veröffentlicht 13. November 2025)

Neuestes Modell mit großen Verbesserungen:

  • gpt-5.1: Adaptives Reasoning, das die Denkzeit dynamisch variiert
  • 24-Stunden erweitertes Prompt-Caching: Schnellere Folgefragen zu geringeren Kosten
  • Neue Entwickler-Tools: apply_patch (Code-Bearbeitung), shell (Befehlsausführung)

BREAKING CHANGE: GPT-5.1 standardmäßig auf reasoning_effort: 'none' (vs. GPT-5 standardmäßig 'medium'). Aktualisieren Sie Ihren Code bei der Migration!

reasoning_effort Parameter

Steuert die Denktiefe (verfügbar bei GPT-5 und GPT-5.1):

  • "none": Kein Reasoning (am schnellsten, geringste Latenz) – GPT-5.1 Standard
  • "minimal": Schnelle Antworten, minimales Denken
  • "low": Einfaches Reasoning
  • "medium": Ausgewogenes Reasoning – GPT-5 Standard
  • "high": Tiefes Reasoning für komplexe Probleme
// GPT-5.1 ohne Reasoning (schnell)
const completion = await openai.chat.completions.create({
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: 'Einfache Abfrage' }],
  // reasoning_effort: 'none' ist impliziter Standard für GPT-5.1
});

// GPT-5.1 mit hohem Reasoning (komplexe Aufgaben)
const completion = await openai.chat.completions.create({
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: 'Löse dieses komplexe Mathematikproblem...' }],
  reasoning_effort: 'high',
});

verbosity Parameter

Steuert die Ausführlichkeit der Ausgabe (GPT-5/GPT-5.1):

  • "low": Knapp
  • "medium": Ausgewogen (Standard)
  • "high": Ausführlich

GPT-5 Einschränkungen

NICHT unterstützt:

  • ❌ Parameter temperature, top_p, logprobs
  • ❌ Zustandsbehaftete Denkkette zwischen den Antworten

Alternativen: Verwenden Sie GPT-4o für temperature/top_p oder die openai-responses-Fertigkeit für zustandsbehaftetes Reasoning


Streaming-Muster

Aktivieren Sie stream: true für die tokenweise Auslieferung.

Node.js SDK

const stream = await openai.chat.completions.create({
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: 'Schreibe ein Gedicht' }],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content || '';
  process.stdout.write(content);
}

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.1',
    messages: [{ role: 'user', content: 'Schreibe ein Gedicht' }],
    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) {
        // Ungültiges JSON überspringen
      }
    }
  }
}

Server-Sent Events (SSE) Format:

data: {"id":"chatcmpl-xyz","choices":[{"delta":{"content":"Hallo"}}]}
data: [DONE]

Wichtige Punkte: Behandeln Sie unvollständige Blöcke, [DONE]-Signal und ungültiges JSON ordnungsgemäß.


Function Calling

Definieren Sie Tools mit JSON-Schema, das Modell ruft sie basierend auf dem Kontext auf.

Tool-Definition & Anfrage

const tools = [{
  type: 'function',
  function: {
    name: 'get_weather',
    description: 'Aktuelles Wetter für einen Ort abrufen',
    parameters: {
      type: 'object',
      properties: {
        location: { type: 'string', description: 'Stadtname' },
        unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
      },
      required: ['location']
    }
  }
}];

const completion = await openai.chat.completions.create({
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: 'Wie ist das Wetter in SF?' }],
  tools: tools,
});

Tool-Aufrufe behandeln

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);

    // Ergebnis zurück an das Modell senden
    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,
    });
  }
}

Schleifenmuster: Rufen Sie die API weiter auf, bis keine tool_calls mehr in der Antwort vorhanden sind.


Strukturierte Ausgaben

Strukturierte Ausgaben ermöglichen die Erzwingung einer JSON-Schema-Validierung für Modellantworten.

Verwendung von JSON-Schema

const completion = await openai.chat.completions.create({
  model: 'gpt-4o', // Hinweis: Strukturierte Ausgaben werden am besten auf GPT-4o unterstützt
  messages: [
    { role: 'user', content: 'Erstelle ein Personenprofil' }
  ],
  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',
            items: { type: 'string' }
          }
        },
        required: ['name', 'age', 'skills'],
        additionalProperties: false
      }
    }
  }
});

const person = JSON.parse(completion.choices[0].message.content);
// { name: "Alice", age: 28, skills: ["TypeScript", "React"] }

JSON-Modus (Einfach)

Für einfachere Anwendungsfälle ohne strenge Schema-Validierung:

const completion = await openai.chat.completions.create({
  model: 'gpt-5',
  messages: [
    { role: 'user', content: 'Liste 3 Programmiersprachen als JSON auf' }
  ],
  response_format: { type: 'json_object' }
});

const data = JSON.parse(completion.choices[0].message.content);

Wichtig: Fügen Sie bei Verwendung von response_format "JSON" in Ihren Prompt ein, um das Modell zu leiten.


Vision (GPT-4o)

GPT-4o unterstützt Bildverständnis neben Text.

Bild per URL

const completion = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: 'Was ist in diesem Bild?' },
        {
          type: 'image_url',
          image_url: {
            url: 'https://example.com/image.jpg'
          }
        }
      ]
    }
  ]
});

Bild per Base64

import fs from 'fs';

const imageBuffer = fs.readFileSync('./image.jpg');
const base64Image = imageBuffer.toString('base64');

const completion = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: 'Beschreibe dieses Bild im Detail' },
        {
          type: 'image_url',
          image_url: {
            url: `data:image/jpeg;base64,${base64Image}`
          }
        }
      ]
    }
  ]
});

Mehrere Bilder

const completion = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: 'Vergleiche diese beiden Bilder' },
        { type: 'image_url', image_url: { url: 'https://example.com/image1.jpg' } },
        { type: 'image_url', image_url: { url: 'https://example.com/image2.jpg' } }
      ]
    }
  ]
});

Embeddings API

Endpunkt: POST /v1/embeddings

Konvertiert Text in Vektoren für semantische Suche und RAG.

Modelle

  • text-embedding-3-large: 3072 Dimensionen (benutzerdefiniert: 256-3072), höchste Qualität
  • text-embedding-3-small: 1536 Dimensionen (benutzerdefiniert: 256-1536), kostengünstig, empfohlen

Grundlegende Anfrage

const embedding = await openai.embeddings.create({
  model: 'text-embedding-3-small',
  input: 'Das Essen war köstlich.',
});
// Gibt zurück: { data: [{ embedding: [0.002, -0.009, ...] }] }

Benutzerdefinierte Dimensionen (OpenAI-spezifisch)

const embedding = await openai.embeddings.create({
  model: 'text-embedding-3-small',
  input: 'Beispieltext',
  dimensions: 256, // Reduziert von 1536 Standard
});

Vorteile: 4x-12x Speicherreduzierung, schnellere Suche, minimaler Qualitätsverlust.

Batch-Verarbeitung

const embeddings = await openai.embeddings.create({
  model: 'text-embedding-3-small',
  input: ['Erstes Dokument', 'Zweites Dokument', 'Drittes Dokument'],
});

Grenzen: 8192 Token/Eingabe, 300k Token insgesamt über Batch, maximal 2048 Array-Größe.

Wichtige Punkte: Verwenden Sie benutzerdefinierte Dimensionen für Effizienz, bündeln Sie bis zu 2048 Dokumente, cachen Sie Embeddings (deterministisch).


Images API

Bildgenerierung (DALL-E 3)

Endpunkt: POST /v1/images/generations

const image = await openai.images.generate({
  model: 'dall-e-3',
  prompt: 'Eine weiße Siamkatze mit auffälligen blauen Augen',
  size: '1024x1024', // Auch: 1024x1536, 1536x1024, 1024x1792, 1792x1024
  quality: 'standard', // oder 'hd'
  style: 'vivid', // oder 'natural'
});

console.log(image.data[0].url);
console.log(image.data[0].revised_prompt); // DALL-E 3 kann Prompts aus Sicherheitsgründen überarbeiten

DALL-E 3 Besonderheiten:

  • Unterstützt nur n: 1 (ein Bild pro Anfrage)
  • Kann Prompts aus Sicherheits-/Qualitätsgründen überarbeiten (prüfen Sie revised_prompt)
  • URLs verfallen nach 1 Stunde (verwenden Sie response_format: 'b64_json')

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

David-Li0406/meta-skill-evloving

Browser automation with persistent page state. Use when users ask to navigate websites, fill forms, take screenshots, extract web data, test web apps, or automate browser workflows. Trigger phrases include "go to [url]", "click on", "fill out the form", "take a screenshot", "scrape", "automate", "test the website", "log into", or any browser interaction request.

David-Li0406/meta-skill-evloving

Create technical diagrams using Mermaid syntax for architecture, sequences, ERDs, flowcharts, and state machines. Use for visualizing system design, data flows, and processes. Triggers: diagram, mermaid, architecture diagram, sequence diagram, flowchart, ERD, entity relationship, state diagram, C4 model, component diagram, visualize, draw.

David-Li0406/meta-skill-evloving

Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks

David-Li0406/meta-skill-evloving

Complete color manipulation and green screen effects system. PROACTIVELY activate for: (1) Green screen/chromakey removal, (2) Color grading with LUTs, (3) Color correction (levels, curves, white balance), (4) Colorkey/color removal effects, (5) Hue/saturation manipulation, (6) Color space conversions (BT.709, BT.2020, HDR), (7) Color isolation effects, (8) Teal and orange look, (9) Vintage/film looks, (10) Color keying for transparency. Provides: chromakey and colorkey filters, LUT application (lut3d), curves and levels adjustment, color balance, selective color manipulation, color space handling, HDR tone mapping, professional color grading chains.

David-Li0406/meta-skill-evloving

Convert files and office documents to Markdown. Supports PDF, DOCX, PPTX, XLSX, images (with OCR), audio (with transcription), HTML, CSV, JSON, XML, ZIP, YouTube URLs, EPubs and more.

David-Li0406/meta-skill-evloving

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

David-Li0406/meta-skill-evloving

Comprehensive PDF manipulation toolkit for extracting text and tables, creating new PDFs, merging/splitting documents, and handling forms. When Claude needs to fill in a PDF form or programmatically process, generate, or analyze PDF documents at scale.

David-Li0406/meta-skill-evloving

Presentation creation, editing, and analysis. When Claude needs to work with presentations (.pptx files) for: (1) Creating new presentations, (2) Modifying or editing content, (3) Working with layouts, (4) Adding comments or speaker notes, or any other presentation tasks

David-Li0406/meta-skill-evloving

Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas

David-Li0406/meta-skill-evloving

Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.

David-Li0406/meta-skill-evloving

Best practices for Remotion - Video creation in React

David-Li0406/meta-skill-evloving

Provides bidirectional translation (Chinese/English), grammar checking, and sentence polishing. Supports specific tense constraints, context-aware tone adjustment, and natural expression optimization. Outputs direct text without formatting.

David-Li0406/meta-skill-evloving

指导如何通过自定义注解(如@Unicom)标识Dubbo接口,利用BeanDefinitionRegistryPostProcessor在启动时扫描并动态注册ReferenceBean,实现RPC调用的封装。

David-Li0406/meta-skill-evloving

生成Python脚本,利用FFmpeg将图片序列按3x3布局合并,或将合并图拆分。要求使用subprocess模块执行命令,并支持用户交互式输入路径。

David-Li0406/meta-skill-evloving

SOP for extracting and analyzing promotional activity details, handling time formatting, location mapping, payment logic, and step-by-step process validation.

David-Li0406/meta-skill-evloving

Specializes in creating TikTok short video scripts using an anthropomorphic 'Chef' perspective to explain wildlife food chains and survival environments, utilizing real field footage.

David-Li0406/meta-skill-evloving

针对TikTok平台,以拟人化视角(如动物作为厨师)创作系列短视频脚本。重点介绍野生动物、食物链及生态环境,要求使用野外实拍素材,风格幽默且具有教育意义。

David-Li0406/meta-skill-evloving

Generates KWL (Know, Want to know, Learned) charts for educational videos, specifically BrainPOP, using simple 7th-grade language and short, concise bullet points.

David-Li0406/meta-skill-evloving

Develops DAX measures to calculate promo and regular volumes and generates a calculated table of dates excluding continuous promo date ranges, handling multiple periods and nulls.

David-Li0406/meta-skill-evloving

Tracks complex, multi-session work using the Beads issue tracker and dependency graphs, and provides persistent memory that survives conversation compaction. Use when work spans multiple sessions, has complex dependencies, or needs persistent context across compaction cycles. Trigger with phrases like "create task for", "what's ready to work on", "show task", "track this work", "what's blocking", or "update status".

Verwandte Skills