openai

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OpenAI API

OpenAI API

Use the OpenAI API via direct
curl
calls to access GPT models, DALL-E image generation, Whisper transcription, embeddings, and text-to-speech.
Official docs:
https://platform.openai.com/docs/api-reference

通过直接调用
curl
来使用OpenAI API,访问GPT模型、DALL-E图像生成、Whisper转写、文本嵌入以及文本转语音功能。
官方文档:
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

前置条件

  1. Sign up at OpenAI Platform and create an account
  2. Go to API Keys and generate a new secret key
  3. Add billing information and set usage limits
bash
export OPENAI_API_KEY="sk-..."
  1. OpenAI平台注册并创建账号
  2. 前往API密钥页面生成新的密钥
  3. 添加账单信息并设置使用限额
bash
export OPENAI_API_KEY="sk-..."

Pricing (as of 2025)

定价(截至2025年)

ModelInput (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 using
$VAR
in a command that pipes to another command, wrap the command containing
$VAR
in
bash -c '...'
. Due to a Claude Code bug, environment variables are silently cleared when pipes are used directly.
bash
bash -c 'curl -s "https://api.example.com" -H "Authorization: Bearer $API_KEY"' | jq .
速率限制因等级而异(基于使用历史)。可在平台设置页面查看你的限额。

重要提示: 当在包含管道的命令中使用
$VAR
时,请将包含
$VAR
的命令用
bash -c '...'
包裹。由于Claude Code的bug,直接使用管道时环境变量会被自动清除。
bash
bash -c 'curl -s "https://api.example.com" -H "Authorization: Bearer $API_KEY"' | jq .

How to Use

使用方法

All examples below assume you have
OPENAI_API_KEY
set.
Base URL:
https://api.openai.com/v1

以下所有示例均假设你已设置好
OPENAI_API_KEY
基础URL:
https://api.openai.com/v1

1. Basic Chat Completion

1. 基础对话补全

Send a simple chat message:
Write to
/tmp/openai_request.json
:
json
{
  "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:
  • gpt-4o
    : Latest flagship model (128K context)
  • gpt-4o-mini
    : Fast and affordable (128K context)
  • gpt-4-turbo
    : Previous generation (128K context)
  • gpt-3.5-turbo
    : Legacy model (16K context)
  • o1
    : Reasoning model for complex tasks
  • o1-mini
    : Smaller reasoning model

发送简单的对话消息:
写入到
/tmp/openai_request.json
json
{
  "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'
可用模型:
  • gpt-4o
    : 最新旗舰模型(128K上下文)
  • gpt-4o-mini
    : 快速且经济实惠(128K上下文)
  • gpt-4-turbo
    : 上一代模型(128K上下文)
  • gpt-3.5-turbo
    : 旧版模型(16K上下文)
  • o1
    : 用于复杂任务的推理模型
  • o1-mini
    : 轻量化推理模型

2. Chat with System Prompt

2. 带系统提示的对话

Use a system message to set behavior:
Write to
/tmp/openai_request.json
:
json
{
  "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.json
json
{
  "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.json
:
json
{
  "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.json
Streaming returns Server-Sent Events (SSE) with delta chunks.

获取实时的逐token输出:
写入到
/tmp/openai_request.json
json
{
  "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.json
:
json
{
  "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.json
json
{
  "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.json
:
json
{
  "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.json
json
{
  "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.json
:
json
{
  "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.json
json
{
  "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.json
:
json
{
  "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:
  • text-embedding-3-small
    : 1536 dimensions, fastest
  • text-embedding-3-large
    : 3072 dimensions, most capable

为文本创建向量嵌入:
写入到
/tmp/openai_request.json
json
{
  "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个维度。
嵌入模型:
  • text-embedding-3-small
    : 1536维度,速度最快
  • text-embedding-3-large
    : 3072维度,功能最强大

8. Generate Image (DALL-E 3)

8. 生成图像(DALL-E 3)

Create an image from text:
Write to
/tmp/openai_request.json
:
json
{
  "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
    ,
    1792x1024
    , or
    1024x1792
  • quality
    :
    standard
    or
    hd
  • style
    :
    vivid
    or
    natural

根据文本描述创建图像:
写入到
/tmp/openai_request.json
json
{
  "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
    1792x1024
    1024x1792
  • 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.json
:
json
{
  "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.mp3
Voices:
alloy
,
echo
,
fable
,
onyx
,
nova
,
shimmer
Models:
tts-1
(fast),
tts-1-hd
(high quality)

根据文本生成音频:
写入到
/tmp/openai_request.json
json
{
  "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
可用音色:
alloy
echo
fable
onyx
nova
shimmer
可用模型:
tts-1
(快速)、
tts-1-hd
(高质量)

11. 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 -20

12. Check Token Usage

12. 查看Token使用情况

Extract usage from response:
Write to
/tmp/openai_request.json
:
json
{
  "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:
  • prompt_tokens
    : Input token count
  • completion_tokens
    : Output token count
  • total_tokens
    : Sum of both

从响应中提取使用数据:
写入到
/tmp/openai_request.json
json
{
  "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数量。
响应包含:
  • prompt_tokens
    : 输入Token数量
  • completion_tokens
    : 输出Token数量
  • total_tokens
    : 总Token数量

Guidelines

使用指南

  1. Choose the right model: Use
    gpt-4o-mini
    for most tasks,
    gpt-4o
    for complex reasoning,
    o1
    for advanced math/coding
  2. Set max_tokens: Prevent runaway generation and control costs
  3. Use streaming for long responses: Better UX for real-time applications
  4. JSON mode requires system prompt: Include JSON instructions when using
    response_format
  5. Vision requires gpt-4o models: Only
    gpt-4o
    and
    gpt-4o-mini
    support image input
  6. Batch similar requests: Use embeddings API batch input for efficiency
  7. Monitor usage: Check dashboard regularly to avoid unexpected charges
  1. 选择合适的模型:大多数任务使用
    gpt-4o-mini
    ,复杂推理使用
    gpt-4o
    ,高级数学/编码任务使用
    o1
  2. 设置max_tokens:防止生成内容过长并控制成本
  3. 长响应使用流式输出:为实时应用提供更好的用户体验
  4. JSON模式需要系统提示:使用
    response_format
    时需包含JSON格式说明
  5. 视觉功能仅支持GPT-4o系列模型:只有
    gpt-4o
    gpt-4o-mini
    支持图像输入
  6. 批量处理相似请求:使用嵌入API的批量输入提高效率
  7. 监控使用情况:定期查看仪表盘以避免意外收费