openai-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOpenAI 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 dimensionstypescript
const response = await client.embeddings.create({
model: 'text-embedding-3-small',
input: 'Your text here'
});
const embedding = response.data[0].embedding; // 1536 dimensionsImages (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
常见错误
- Invalid API Key (401): Verify OPENAI_API_KEY
- Rate Limit (429): Implement exponential backoff
- Model Not Found (404): Use correct model names
- Context Length (400): Reduce input size
- Invalid JSON: Fix function calling schemas
See:
references/error-catalog.md- 无效API密钥(401):验证OPENAI_API_KEY是否正确
- 请求频率限制(429):实现指数退避策略
- 模型未找到(404):使用正确的模型名称
- 上下文长度超限(400):缩小输入内容的规模
- JSON格式无效:修复函数调用的Schema
参考文档:
references/error-catalog.mdResources
资源
Reference Guides
参考指南
- - Complete model comparison and selection
references/models-guide.md - - Function calling best practices
references/function-calling-patterns.md - - Structured outputs with JSON Schema
references/structured-output-guide.md - - Text embeddings and vector search
references/embeddings-guide.md - - GPT-Image-1.5 image generation
references/images-guide.md - - Whisper transcription + TTS
references/audio-guide.md - - Token optimization and pricing
references/cost-optimization.md - - Top 20 errors with solutions
references/top-errors.md - - Complete error reference
references/error-catalog.md
- - 完整的模型对比与选择指南
references/models-guide.md - - 函数调用最佳实践
references/function-calling-patterns.md - - 基于JSON Schema的结构化输出
references/structured-output-guide.md - - 文本嵌入与向量搜索
references/embeddings-guide.md - - GPT-Image-1.5图像生成指南
references/images-guide.md - - Whisper转录 + TTS指南
references/audio-guide.md - - Token优化与定价指南
references/cost-optimization.md - - 20种常见错误及解决方案
references/top-errors.md - - 完整错误参考手册
references/error-catalog.md
Templates
模板
- - Quick start example
templates/basic-usage.ts - - Basic chat completion
templates/chat-completion-basic.ts - - Node.js implementation
templates/chat-completion-nodejs.ts - - Streaming responses
templates/streaming-chat.ts - - Streaming with fetch API
templates/streaming-fetch.ts - - Tools and function calling
templates/function-calling.ts - - JSON Schema outputs
templates/structured-output.ts - - Vision with GPT-4o
templates/vision-gpt4o.ts - - Text embeddings
templates/embeddings.ts - - GPT-Image-1.5 generation
templates/image-generation.ts - - Image editing
templates/image-editing.ts - - Whisper transcription
templates/audio-transcription.ts - - TTS with voices
templates/text-to-speech.ts - - Content moderation
templates/moderation.ts - - Exponential backoff
templates/rate-limit-handling.ts - - Cloudflare Workers integration
templates/cloudflare-worker.ts
- - 快速入门示例
templates/basic-usage.ts - - 基础聊天补全示例
templates/chat-completion-basic.ts - - Node.js实现示例
templates/chat-completion-nodejs.ts - - 流式响应示例
templates/streaming-chat.ts - - 使用fetch API实现流式响应
templates/streaming-fetch.ts - - 工具与函数调用示例
templates/function-calling.ts - - JSON Schema输出示例
templates/structured-output.ts - - GPT-4o视觉功能示例
templates/vision-gpt4o.ts - - 文本嵌入示例
templates/embeddings.ts - - GPT-Image-1.5图像生成示例
templates/image-generation.ts - - 图像编辑示例
templates/image-editing.ts - - Whisper转录示例
templates/audio-transcription.ts - - 带语音选择的TTS示例
templates/text-to-speech.ts - - 内容审核示例
templates/moderation.ts - - 指数退避实现示例
templates/rate-limit-handling.ts - - Cloudflare Workers集成示例
templates/cloudflare-worker.ts