openai-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OpenAI API

OpenAI API

Package: openai@6.9.1 | Last Updated: 2025-11-21
:openai@6.9.1 | 最后更新时间:2025-11-21

Quick Start

快速开始

bash
bun add openai
export OPENAI_API_KEY="sk-..."
typescript
import OpenAI from 'openai';

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Hello!' }]
});
bash
bun add openai
export OPENAI_API_KEY="sk-..."
typescript
import OpenAI from 'openai';

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Hello!' }]
});

Current Models (2025)

当前可用模型(2025年)

  • gpt-5.2: Most capable (128k context)
  • gpt-4o: Fast multimodal (128k context)
  • gpt-4o-mini: Cost-effective (128k context)
  • gpt-4o-transcribe: Audio transcription optimized
  • gpt-4o-mini-transcribe: Cost-effective transcription
  • o1-preview: Advanced reasoning (128k context)
  • o1-mini: Fast reasoning (128k context)
  • gpt-5.2:功能最强大(128k上下文)
  • gpt-4o:快速多模态模型(128k上下文)
  • gpt-4o-mini:高性价比(128k上下文)
  • gpt-4o-transcribe:音频转录优化模型
  • gpt-4o-mini-transcribe:高性价比转录模型
  • o1-preview:高级推理模型(128k上下文)
  • o1-mini:快速推理模型(128k上下文)

Chat Completions

聊天补全

typescript
const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    { role: 'system', content: 'You are a helpful assistant' },
    { role: 'user', content: 'Explain AI' }
  ],
  temperature: 0.7,
  max_tokens: 1000
});
typescript
const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    { role: 'system', content: 'You are a helpful assistant' },
    { role: 'user', content: 'Explain AI' }
  ],
  temperature: 0.7,
  max_tokens: 1000
});

Streaming

流式响应

typescript
const stream = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Tell a story' }],
  stream: true
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || '');
}
typescript
const stream = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Tell a story' }],
  stream: true
});

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

Function Calling

函数调用

typescript
const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'What is the weather?' }],
  tools: [{
    type: 'function',
    function: {
      name: 'getWeather',
      parameters: {
        type: 'object',
        properties: { location: { type: 'string' } },
        required: ['location']
      }
    }
  }]
});
typescript
const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'What is the weather?' }],
  tools: [{
    type: 'function',
    function: {
      name: 'getWeather',
      parameters: {
        type: 'object',
        properties: { location: { type: 'string' } },
        required: ['location']
      }
    }
  }]
});

Embeddings

嵌入

typescript
const response = await client.embeddings.create({
  model: 'text-embedding-3-small',
  input: 'Your text here'
});

const embedding = response.data[0].embedding; // 1536 dimensions
typescript
const response = await client.embeddings.create({
  model: 'text-embedding-3-small',
  input: 'Your text here'
});

const embedding = response.data[0].embedding; // 1536 dimensions

Images (GPT-Image-1.5)

图像生成(GPT-Image-1.5)

typescript
const image = await client.images.generate({
  model: 'gpt-image-1.5',
  prompt: 'A serene landscape',
  size: '1024x1024',
  quality: 'standard'  // or 'hd'
});
typescript
const image = await client.images.generate({
  model: 'gpt-image-1.5',
  prompt: 'A serene landscape',
  size: '1024x1024',
  quality: 'standard'  // or 'hd'
});

Audio

音频处理

Transcription (Whisper):
typescript
const transcription = await client.audio.transcriptions.create({
  file: fs.createReadStream('audio.mp3'),
  model: 'whisper-1'
});
Text-to-Speech:
typescript
const speech = await client.audio.speech.create({
  model: 'tts-1',
  voice: 'alloy',
  input: 'Hello world'
});
转录(Whisper):
typescript
const transcription = await client.audio.transcriptions.create({
  file: fs.createReadStream('audio.mp3'),
  model: 'whisper-1'
});
文本转语音:
typescript
const speech = await client.audio.speech.create({
  model: 'tts-1',
  voice: 'alloy',
  input: 'Hello world'
});

Top Errors

常见错误

  1. Invalid API Key (401): Verify OPENAI_API_KEY
  2. Rate Limit (429): Implement exponential backoff
  3. Model Not Found (404): Use correct model names
  4. Context Length (400): Reduce input size
  5. Invalid JSON: Fix function calling schemas
See:
references/error-catalog.md
  1. 无效API密钥(401):验证OPENAI_API_KEY是否正确
  2. 请求频率限制(429):实现指数退避策略
  3. 模型未找到(404):使用正确的模型名称
  4. 上下文长度超限(400):缩小输入内容的规模
  5. JSON格式无效:修复函数调用的Schema
参考文档
references/error-catalog.md

Resources

资源

Reference Guides

参考指南

  • references/models-guide.md
    - Complete model comparison and selection
  • references/function-calling-patterns.md
    - Function calling best practices
  • references/structured-output-guide.md
    - Structured outputs with JSON Schema
  • references/embeddings-guide.md
    - Text embeddings and vector search
  • references/images-guide.md
    - GPT-Image-1.5 image generation
  • references/audio-guide.md
    - Whisper transcription + TTS
  • references/cost-optimization.md
    - Token optimization and pricing
  • references/top-errors.md
    - Top 20 errors with solutions
  • references/error-catalog.md
    - Complete error reference
  • references/models-guide.md
    - 完整的模型对比与选择指南
  • references/function-calling-patterns.md
    - 函数调用最佳实践
  • references/structured-output-guide.md
    - 基于JSON Schema的结构化输出
  • references/embeddings-guide.md
    - 文本嵌入与向量搜索
  • references/images-guide.md
    - GPT-Image-1.5图像生成指南
  • references/audio-guide.md
    - Whisper转录 + TTS指南
  • references/cost-optimization.md
    - Token优化与定价指南
  • references/top-errors.md
    - 20种常见错误及解决方案
  • references/error-catalog.md
    - 完整错误参考手册

Templates

模板

  • templates/basic-usage.ts
    - Quick start example
  • templates/chat-completion-basic.ts
    - Basic chat completion
  • templates/chat-completion-nodejs.ts
    - Node.js implementation
  • templates/streaming-chat.ts
    - Streaming responses
  • templates/streaming-fetch.ts
    - Streaming with fetch API
  • templates/function-calling.ts
    - Tools and function calling
  • templates/structured-output.ts
    - JSON Schema outputs
  • templates/vision-gpt4o.ts
    - Vision with GPT-4o
  • templates/embeddings.ts
    - Text embeddings
  • templates/image-generation.ts
    - GPT-Image-1.5 generation
  • templates/image-editing.ts
    - Image editing
  • templates/audio-transcription.ts
    - Whisper transcription
  • templates/text-to-speech.ts
    - TTS with voices
  • templates/moderation.ts
    - Content moderation
  • templates/rate-limit-handling.ts
    - Exponential backoff
  • templates/cloudflare-worker.ts
    - Cloudflare Workers integration
  • templates/basic-usage.ts
    - 快速入门示例
  • templates/chat-completion-basic.ts
    - 基础聊天补全示例
  • templates/chat-completion-nodejs.ts
    - Node.js实现示例
  • templates/streaming-chat.ts
    - 流式响应示例
  • templates/streaming-fetch.ts
    - 使用fetch API实现流式响应
  • templates/function-calling.ts
    - 工具与函数调用示例
  • templates/structured-output.ts
    - JSON Schema输出示例
  • templates/vision-gpt4o.ts
    - GPT-4o视觉功能示例
  • templates/embeddings.ts
    - 文本嵌入示例
  • templates/image-generation.ts
    - GPT-Image-1.5图像生成示例
  • templates/image-editing.ts
    - 图像编辑示例
  • templates/audio-transcription.ts
    - Whisper转录示例
  • templates/text-to-speech.ts
    - 带语音选择的TTS示例
  • templates/moderation.ts
    - 内容审核示例
  • templates/rate-limit-handling.ts
    - 指数退避实现示例
  • templates/cloudflare-worker.ts
    - Cloudflare Workers集成示例