欢迎回来

登录 EAKE AI,继续您的智能之旅

忘记密码?
还没有账号?立即注册

OpenAI API 使用手册

2026-05-07 · 使用手册

一、概述

OpenAI API 提供 GPT 系列模型的程序化访问,支持文本生成、对话、函数调用、图像生成、语音合成与识别、嵌入向量等功能。所有接口兼容 OpenAI 格式,可通过 REST API 或官方 SDK 调用。

二、认证

所有请求需在 HTTP Header 中携带 API Key:

Authorization: Bearer sk-xxxxxxxxxxxxxxxx

API Key 在 platform.openai.com/api-keys 创建,建议通过环境变量管理:

export OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxx

三、Base URL

https://api.openai.com/v1

四、模型列表

模型ID类型上下文窗口训练数据
gpt-5.2旗舰对话256K2026年4月
gpt-4o通用对话128K2025年10月
gpt-4o-mini轻量对话128K2025年10月
o3推理专用200K2026年4月
o4-mini轻量推理128K2026年3月
dall-e-3图像生成--
whisper-1语音识别--
tts-1语音合成--
text-embedding-3-large文本嵌入8191-

五、Chat Completions

请求

POST /v1/chat/completions

{
  "model": "gpt-4o",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ],
  "temperature": 0.7,
  "top_p": 1,
  "max_tokens": 4096,
  "stream": false,
  "stop": null,
  "presence_penalty": 0,
  "frequency_penalty": 0
}

参数说明

参数类型必填说明
modelstring模型ID
messagesarray消息数组,每条含 role + content
temperaturefloat0-2,默认1。越低越确定性
top_pfloat核采样,0-1,默认1
max_tokensint最大生成token数
streambool是否流式输出,默认false
stopstring/array停止序列
presence_penaltyfloat-2到2,正值鼓励新话题
frequency_penaltyfloat-2到2,正值降低重复
toolsarray函数定义列表
tool_choicestring/object"auto"/"none"/"required"/指定函数
response_formatobject{"type":"json_object"} 强制JSON输出
seedint随机种子,可复现结果

响应

{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "created": 1717100000,
  "model": "gpt-4o",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Hello! How can I help you today?"
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 20,
    "completion_tokens": 8,
    "total_tokens": 28
  }
}

六、Function Calling(函数调用)

定义函数

"tools": [{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "获取指定城市的当前天气",
    "parameters": {
      "type": "object",
      "properties": {
        "city": {"type": "string", "description": "城市名称"},
        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
      },
      "required": ["city"]
    }
  }
}]

处理函数调用

// 模型返回 tool_calls
if (response.choices[0].finish_reason === "tool_calls") {
  const toolCall = response.choices[0].message.tool_calls[0];
  // 执行实际函数
  const result = await getWeather(toolCall.function.arguments);
  // 将结果返回给模型
  const followUp = await client.chat.completions.create({
    model: "gpt-4o",
    messages: [
      ...previousMessages,
      response.choices[0].message,
      {
        role: "tool",
        tool_call_id: toolCall.id,
        content: JSON.stringify(result)
      }
    ]
  });
}

七、图像生成(DALL·E)

POST /v1/images/generations

{
  "model": "dall-e-3",
  "prompt": "A white siamese cat in a cyberpunk city",
  "n": 1,
  "size": "1024x1024",
  "quality": "hd",
  "style": "vivid"
}

可选尺寸:1024x1024, 1792x1024, 1024x1792

八、语音识别(Whisper)

POST /v1/audio/transcriptions
Content-Type: multipart/form-data

file: audio.mp3
model: whisper-1
language: zh

九、语音合成(TTS)

POST /v1/audio/speech

{
  "model": "tts-1",
  "input": "你好,世界!",
  "voice": "alloy"
}

可用声音:alloy, echo, fable, onyx, nova, shimmer

十、文本嵌入

POST /v1/embeddings

{
  "model": "text-embedding-3-large",
  "input": "The food was delicious"
}

十一、速率限制

层级RPMTPM
Free340,000
Tier 1 ($5+)500200,000
Tier 2 ($50+)5,0002,000,000

遇到 429 错误时使用指数退避重试。

十二、错误码

状态码含义处理建议
400请求格式错误检查参数
401API Key 无效检查密钥
429速率限制退避重试
500服务器错误稍后重试
503服务过载稍后重试

评论区

发表评论