openai
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOpenAI API
OpenAI API
Use the OpenAI API via direct calls to access GPT models, DALL-E image generation, Whisper transcription, embeddings, and text-to-speech.
curlOfficial docs:https://platform.openai.com/docs/api-reference
通过直接调用来使用OpenAI API,访问GPT模型、DALL-E图像生成、Whisper转写、文本嵌入以及文本转语音功能。
curl官方文档:https://platform.openai.com/docs/api-reference
When to Use
使用场景
Use this skill when you need to:
- Chat completions with GPT-4o, GPT-4, or GPT-3.5 models
- Image generation with DALL-E 3
- Audio transcription with Whisper
- Text-to-speech audio generation
- Text embeddings for semantic search and RAG
- Vision tasks (analyze images with GPT-4o)
在以下场景中可使用该技能:
- 使用GPT-4o、GPT-4或GPT-3.5模型进行对话补全
- 使用DALL-E 3进行图像生成
- 使用Whisper进行音频转写
- 生成文本转语音音频
- 用于语义搜索和RAG的文本嵌入
- 视觉任务(使用GPT-4o分析图像)
Prerequisites
前置条件
- Sign up at OpenAI Platform and create an account
- Go to API Keys and generate a new secret key
- Add billing information and set usage limits
bash
export OPENAI_API_KEY="sk-..."Pricing (as of 2025)
定价(截至2025年)
| Model | Input (per 1M tokens) | Output (per 1M tokens) |
|---|---|---|
| GPT-4o | $2.50 | $10.00 |
| GPT-4o-mini | $0.15 | $0.60 |
| GPT-4 Turbo | $10.00 | $30.00 |
| text-embedding-3-small | $0.02 | - |
| text-embedding-3-large | $0.13 | - |
| 模型 | 输入(每100万tokens) | 输出(每100万tokens) |
|---|---|---|
| GPT-4o | $2.50 | $10.00 |
| GPT-4o-mini | $0.15 | $0.60 |
| GPT-4 Turbo | $10.00 | $30.00 |
| text-embedding-3-small | $0.02 | - |
| text-embedding-3-large | $0.13 | - |
Rate Limits
速率限制
Rate limits vary by tier (based on usage history). Check your limits at Platform Settings.
Important: When usingin a command that pipes to another command, wrap the command containing$VARin$VAR. Due to a Claude Code bug, environment variables are silently cleared when pipes are used directly.bash -c '...'bashbash -c 'curl -s "https://api.example.com" -H "Authorization: Bearer $API_KEY"' | jq .
速率限制因等级而异(基于使用历史)。可在平台设置页面查看你的限额。
重要提示: 当在包含管道的命令中使用时,请将包含$VAR的命令用$VAR包裹。由于Claude Code的bug,直接使用管道时环境变量会被自动清除。bash -c '...'bashbash -c 'curl -s "https://api.example.com" -H "Authorization: Bearer $API_KEY"' | jq .
How to Use
使用方法
All examples below assume you have set.
OPENAI_API_KEYBase URL:
https://api.openai.com/v1以下所有示例均假设你已设置好。
OPENAI_API_KEY基础URL:
https://api.openai.com/v11. Basic Chat Completion
1. 基础对话补全
Send a simple chat message:
Write to :
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Hello, who are you?"}]
}Then run:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.content'Available models:
- : Latest flagship model (128K context)
gpt-4o - : Fast and affordable (128K context)
gpt-4o-mini - : Previous generation (128K context)
gpt-4-turbo - : Legacy model (16K context)
gpt-3.5-turbo - : Reasoning model for complex tasks
o1 - : Smaller reasoning model
o1-mini
发送简单的对话消息:
写入到:
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Hello, who are you?"}]
}然后运行:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.content'可用模型:
- : 最新旗舰模型(128K上下文)
gpt-4o - : 快速且经济实惠(128K上下文)
gpt-4o-mini - : 上一代模型(128K上下文)
gpt-4-turbo - : 旧版模型(16K上下文)
gpt-3.5-turbo - : 用于复杂任务的推理模型
o1 - : 轻量化推理模型
o1-mini
2. Chat with System Prompt
2. 带系统提示的对话
Use a system message to set behavior:
Write to :
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a helpful assistant that responds in JSON format."},
{"role": "user", "content": "List 3 programming languages with their main use cases."}
]
}Then run:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.content'使用系统消息设置助手行为:
写入到:
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a helpful assistant that responds in JSON format."},
{"role": "user", "content": "List 3 programming languages with their main use cases."}
]
}然后运行:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.content'3. Streaming Response
3. 流式响应
Get real-time token-by-token output:
Write to :
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Write a haiku about programming."}],
"stream": true
}Then run:
bash
curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.jsonStreaming returns Server-Sent Events (SSE) with delta chunks.
获取实时的逐token输出:
写入到:
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Write a haiku about programming."}],
"stream": true
}然后运行:
bash
curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json流式响应返回带delta块的Server-Sent Events(SSE)。
4. JSON Mode
4. JSON模式
Force the model to return valid JSON:
Write to :
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "Return JSON only."},
{"role": "user", "content": "Give me info about Paris: name, country, population."}
],
"response_format": {"type": "json_object"}
}Then run:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.content'强制模型返回有效的JSON:
写入到:
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "Return JSON only."},
{"role": "user", "content": "Give me info about Paris: name, country, population."}
],
"response_format": {"type": "json_object"}
}然后运行:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.content'5. Vision (Image Analysis)
5. 视觉功能(图像分析)
Analyze an image with GPT-4o:
Write to :
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image?"},
{"type": "image_url", "image_url": {"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg"}}
]
}
],
"max_tokens": 300
}Then run:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.content'使用GPT-4o分析图像:
写入到:
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image?"},
{"type": "image_url", "image_url": {"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg"}}
]
}
],
"max_tokens": 300
}然后运行:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.content'6. Function Calling (Tools)
6. 函数调用(工具)
Define functions the model can call:
Write to :
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "What is the weather in Tokyo?"}],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}
}
]
}Then run:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.tool_calls'定义模型可调用的函数:
写入到:
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "What is the weather in Tokyo?"}],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}
}
]
}然后运行:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.choices[0].message.tool_calls'7. Generate Embeddings
7. 生成文本嵌入
Create vector embeddings for text:
Write to :
/tmp/openai_request.jsonjson
{
"model": "text-embedding-3-small",
"input": "The quick brown fox jumps over the lazy dog."
}Then run:
bash
bash -c 'curl -s "https://api.openai.com/v1/embeddings" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.data[0].embedding[:5]'This extracts the first 5 dimensions of the embedding vector.
Embedding models:
- : 1536 dimensions, fastest
text-embedding-3-small - : 3072 dimensions, most capable
text-embedding-3-large
为文本创建向量嵌入:
写入到:
/tmp/openai_request.jsonjson
{
"model": "text-embedding-3-small",
"input": "The quick brown fox jumps over the lazy dog."
}然后运行:
bash
bash -c 'curl -s "https://api.openai.com/v1/embeddings" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.data[0].embedding[:5]'此命令提取嵌入向量的前5个维度。
嵌入模型:
- : 1536维度,速度最快
text-embedding-3-small - : 3072维度,功能最强大
text-embedding-3-large
8. Generate Image (DALL-E 3)
8. 生成图像(DALL-E 3)
Create an image from text:
Write to :
/tmp/openai_request.jsonjson
{
"model": "dall-e-3",
"prompt": "A white cat sitting on a windowsill, digital art",
"n": 1,
"size": "1024x1024"
}Then run:
bash
bash -c 'curl -s "https://api.openai.com/v1/images/generations" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.data[0].url'Parameters:
- :
size,1024x1024, or1792x10241024x1792 - :
qualityorstandardhd - :
styleorvividnatural
根据文本描述创建图像:
写入到:
/tmp/openai_request.jsonjson
{
"model": "dall-e-3",
"prompt": "A white cat sitting on a windowsill, digital art",
"n": 1,
"size": "1024x1024"
}然后运行:
bash
bash -c 'curl -s "https://api.openai.com/v1/images/generations" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.data[0].url'参数说明:
- :
size、1024x1024或1792x10241024x1792 - :
quality(标准)或standard(高清)hd - :
style(生动)或vivid(自然)natural
9. Audio Transcription (Whisper)
9. 音频转写(Whisper)
Transcribe audio to text:
bash
bash -c 'curl -s "https://api.openai.com/v1/audio/transcriptions" -H "Authorization: Bearer ${OPENAI_API_KEY}" -F "file=@audio.mp3" -F "model=whisper-1"' | jq '.text'Supports: mp3, mp4, mpeg, mpga, m4a, wav, webm (max 25MB).
将音频转换为文本:
bash
bash -c 'curl -s "https://api.openai.com/v1/audio/transcriptions" -H "Authorization: Bearer ${OPENAI_API_KEY}" -F "file=@audio.mp3" -F "model=whisper-1"' | jq '.text'支持的格式:mp3、mp4、mpeg、mpga、m4a、wav、webm(最大25MB)。
10. Text-to-Speech
10. 文本转语音
Generate audio from text:
Write to :
/tmp/openai_request.jsonjson
{
"model": "tts-1",
"input": "Hello! This is a test of OpenAI text to speech.",
"voice": "alloy"
}Then run:
bash
curl -s "https://api.openai.com/v1/audio/speech" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json --output speech.mp3Voices: , , , , ,
alloyechofableonyxnovashimmerModels: (fast), (high quality)
tts-1tts-1-hd根据文本生成音频:
写入到:
/tmp/openai_request.jsonjson
{
"model": "tts-1",
"input": "Hello! This is a test of OpenAI text to speech.",
"voice": "alloy"
}然后运行:
bash
curl -s "https://api.openai.com/v1/audio/speech" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json --output speech.mp3可用音色: 、、、、、
alloyechofableonyxnovashimmer可用模型: (快速)、(高质量)
tts-1tts-1-hd11. List Available Models
11. 列出可用模型
Get all available models:
bash
bash -c 'curl -s "https://api.openai.com/v1/models" -H "Authorization: Bearer ${OPENAI_API_KEY}"' | jq -r '.data[].id' | sort | head -20获取所有可用的模型:
bash
bash -c 'curl -s "https://api.openai.com/v1/models" -H "Authorization: Bearer ${OPENAI_API_KEY}"' | jq -r '.data[].id' | sort | head -2012. Check Token Usage
12. 查看Token使用情况
Extract usage from response:
Write to :
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Hi!"}]
}Then run:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.usage'This returns token counts for both input and output.
Response includes:
- : Input token count
prompt_tokens - : Output token count
completion_tokens - : Sum of both
total_tokens
从响应中提取使用数据:
写入到:
/tmp/openai_request.jsonjson
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Hi!"}]
}然后运行:
bash
bash -c 'curl -s "https://api.openai.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer ${OPENAI_API_KEY}" -d @/tmp/openai_request.json' | jq '.usage'此命令返回输入和输出的Token数量。
响应包含:
- : 输入Token数量
prompt_tokens - : 输出Token数量
completion_tokens - : 总Token数量
total_tokens
Guidelines
使用指南
- Choose the right model: Use for most tasks,
gpt-4o-minifor complex reasoning,gpt-4ofor advanced math/codingo1 - Set max_tokens: Prevent runaway generation and control costs
- Use streaming for long responses: Better UX for real-time applications
- JSON mode requires system prompt: Include JSON instructions when using
response_format - Vision requires gpt-4o models: Only and
gpt-4osupport image inputgpt-4o-mini - Batch similar requests: Use embeddings API batch input for efficiency
- Monitor usage: Check dashboard regularly to avoid unexpected charges
- 选择合适的模型:大多数任务使用,复杂推理使用
gpt-4o-mini,高级数学/编码任务使用gpt-4oo1 - 设置max_tokens:防止生成内容过长并控制成本
- 长响应使用流式输出:为实时应用提供更好的用户体验
- JSON模式需要系统提示:使用时需包含JSON格式说明
response_format - 视觉功能仅支持GPT-4o系列模型:只有和
gpt-4o支持图像输入gpt-4o-mini - 批量处理相似请求:使用嵌入API的批量输入提高效率
- 监控使用情况:定期查看仪表盘以避免意外收费