OpenAI API 快速开始 #

准备工作 #

在开始使用 OpenAI API 之前,你需要完成以下准备工作:

1. 注册 OpenAI 账号 #

text
┌─────────────────────────────────────────────────────────────┐
│                    注册流程                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   1. 访问 https://platform.openai.com                       │
│                                                             │
│   2. 点击 "Sign Up" 注册账号                                │
│                                                             │
│   3. 可以使用:                                              │
│      - 邮箱注册                                              │
│      - Google 账号                                          │
│      - Microsoft 账号                                       │
│      - Apple 账号                                           │
│                                                             │
│   4. 完成邮箱验证                                            │
│                                                             │
│   5. 绑定手机号(可选,用于安全验证)                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

2. 获取 API Key #

text
┌─────────────────────────────────────────────────────────────┐
│                    获取 API Key                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   步骤:                                                     │
│                                                             │
│   1. 登录后访问 https://platform.openai.com/api-keys        │
│                                                             │
│   2. 点击 "Create new secret key"                           │
│                                                             │
│   3. 输入 Key 名称(如:my-first-key)                       │
│                                                             │
│   4. 选择权限范围(建议先用默认)                             │
│                                                             │
│   5. 点击 "Create secret key"                               │
│                                                             │
│   6. ⚠️ 立即复制保存 Key,关闭后无法再次查看!               │
│                                                             │
│   Key 格式示例:                                             │
│   sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

3. 充值账户 #

text
┌─────────────────────────────────────────────────────────────┐
│                    账户充值                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   OpenAI API 是付费服务,需要充值后使用:                     │
│                                                             │
│   1. 访问 https://platform.openai.com/settings/organization │
│                                                             │
│   2. 点击 "Billing" -> "Add payment details"                │
│                                                             │
│   3. 添加信用卡信息                                          │
│                                                             │
│   4. 充值金额(建议先充值 $5 测试)                          │
│                                                             │
│   注意:                                                     │
│   - 新用户可能有免费额度(以官方为准)                        │
│   - 按使用量计费,用多少扣多少                               │
│   - 可以设置月度预算上限                                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

安装 SDK #

Python #

bash
pip install openai

Node.js #

bash
npm install openai

其他语言 #

text
┌─────────────────────────────────────────────────────────────┐
│                    其他语言 SDK                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Go:                                                        │
│  go get github.com/sashabaranov/go-openai                   │
│                                                             │
│  Java:                                                      │
│  implementation 'com.theokanning.openai-gpt3-java:service'  │
│                                                             │
│  Ruby:                                                      │
│  gem install ruby-openai                                    │
│                                                             │
│  PHP:                                                       │
│  composer require openai-php/client                         │
│                                                             │
│  .NET:                                                      │
│  dotnet add package OpenAI                                  │
│                                                             │
│  或者直接使用 HTTP API(任何语言都支持)                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

配置 API Key #

方式一:环境变量(推荐) #

bash
# macOS / Linux
export OPENAI_API_KEY='sk-proj-your-api-key-here'

# Windows (PowerShell)
$env:OPENAI_API_KEY='sk-proj-your-api-key-here'

# Windows (CMD)
set OPENAI_API_KEY=sk-proj-your-api-key-here

方式二:.env 文件 #

bash
# 创建 .env 文件
echo "OPENAI_API_KEY=sk-proj-your-api-key-here" > .env

# 添加到 .gitignore(重要!)
echo ".env" >> .gitignore

方式三:代码中直接设置 #

python
# Python
from openai import OpenAI

client = OpenAI(api_key='sk-proj-your-api-key-here')
javascript
// Node.js
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-proj-your-api-key-here'
});

发送第一个请求 #

Python 示例 #

python
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "user", "content": "你好,请介绍一下你自己"}
    ]
)

print(response.choices[0].message.content)

Node.js 示例 #

javascript
import OpenAI from 'openai';

const client = new OpenAI();

async function main() {
  const response = await client.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [
      { role: 'user', content: '你好,请介绍一下你自己' }
    ]
  });

  console.log(response.choices[0].message.content);
}

main();

cURL 示例 #

bash
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [
      {
        "role": "user",
        "content": "你好,请介绍一下你自己"
      }
    ]
  }'

响应结构解析 #

完整响应示例 #

json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1677858242,
  "model": "gpt-4o-mini",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "你好!我是 OpenAI 开发的人工智能助手..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 15,
    "completion_tokens": 50,
    "total_tokens": 65
  }
}

字段说明 #

text
┌─────────────────────────────────────────────────────────────┐
│                    响应字段说明                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  id                 请求唯一标识                             │
│  ─────────────────────────────────────────────────────────  │
│  格式:chatcmpl-xxxxx                                       │
│  用于追踪和调试                                              │
│                                                             │
│  object             对象类型                                │
│  ─────────────────────────────────────────────────────────  │
│  值:chat.completion                                        │
│                                                             │
│  created            创建时间戳                              │
│  ─────────────────────────────────────────────────────────  │
│  Unix 时间戳                                                 │
│                                                             │
│  model              使用的模型                              │
│  ─────────────────────────────────────────────────────────  │
│  实际使用的模型名称                                          │
│                                                             │
│  choices            回复选项                                │
│  ─────────────────────────────────────────────────────────  │
│  index: 选项索引                                            │
│  message: 回复消息                                          │
│    - role: 角色(assistant)                                │
│    - content: 回复内容                                      │
│  finish_reason: 结束原因                                    │
│    - stop: 正常结束                                         │
│    - length: 达到长度限制                                   │
│    - content_filter: 内容过滤                               │
│                                                             │
│  usage              Token 使用量                            │
│  ─────────────────────────────────────────────────────────  │
│  prompt_tokens: 输入 Token 数                               │
│  completion_tokens: 输出 Token 数                           │
│  total_tokens: 总 Token 数                                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

常用代码模板 #

基础对话 #

python
from openai import OpenAI

client = OpenAI()

def chat(message: str) -> str:
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "user", "content": message}
        ]
    )
    return response.choices[0].message.content

result = chat("什么是机器学习?")
print(result)

带系统提示的对话 #

python
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {
            "role": "system",
            "content": "你是一个专业的 Python 编程助手,回答要简洁专业。"
        },
        {
            "role": "user",
            "content": "如何读取 JSON 文件?"
        }
    ]
)

print(response.choices[0].message.content)

多轮对话 #

python
from openai import OpenAI

client = OpenAI()

messages = [
    {"role": "system", "content": "你是一个友好的助手。"}
]

def chat(user_input: str) -> str:
    messages.append({"role": "user", "content": user_input})
    
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages
    )
    
    assistant_message = response.choices[0].message.content
    messages.append({"role": "assistant", "content": assistant_message})
    
    return assistant_message

print(chat("你好!"))
print(chat("我刚才说了什么?"))

错误处理 #

python
from openai import OpenAI, APIError, RateLimitError, APIConnectionError

client = OpenAI()

try:
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "user", "content": "你好"}
        ]
    )
    print(response.choices[0].message.content)

except RateLimitError as e:
    print(f"请求频率超限: {e}")
    print("请等待后重试")

except APIConnectionError as e:
    print(f"网络连接错误: {e}")
    print("请检查网络连接")

except APIError as e:
    print(f"API 错误: {e}")
    print("请检查请求参数")

except Exception as e:
    print(f"未知错误: {e}")

模型选择指南 #

可用模型 #

text
┌─────────────────────────────────────────────────────────────┐
│                    OpenAI 模型选择                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  GPT-4o(推荐)                                              │
│  ─────────────────────────────────────────────────────────  │
│  - 最新旗舰模型                                              │
│  - 多模态支持(文本、图像、音频)                            │
│  - 速度快、成本低                                            │
│  - 适用:大多数场景                                          │
│                                                             │
│  GPT-4o-mini                                                │
│  ─────────────────────────────────────────────────────────  │
│  - 轻量级模型                                                │
│  - 极低成本                                                  │
│  - 适用:简单任务、大量调用                                  │
│                                                             │
│  GPT-4 Turbo                                                │
│  ─────────────────────────────────────────────────────────  │
│  - 强大推理能力                                              │
│  - 128K 上下文                                              │
│  - 适用:复杂推理任务                                        │
│                                                             │
│  o1 / o1-mini                                               │
│  ─────────────────────────────────────────────────────────  │
│  - 深度推理模型                                              │
│  - 适用:数学、编程、科学问题                                │
│                                                             │
│  GPT-3.5 Turbo                                              │
│  ─────────────────────────────────────────────────────────  │
│  - 经济实惠                                                  │
│  - 适用:简单任务、预算有限                                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

选择建议 #

python
def get_model_for_task(task_type: str) -> str:
    models = {
        "simple": "gpt-4o-mini",      # 简单对话、分类
        "standard": "gpt-4o",          # 日常任务
        "complex": "gpt-4-turbo",      # 复杂推理
        "reasoning": "o1-mini",        # 深度推理
        "budget": "gpt-3.5-turbo"      # 预算有限
    }
    return models.get(task_type, "gpt-4o-mini")

Token 计算 #

什么是 Token? #

text
┌─────────────────────────────────────────────────────────────┐
│                    Token 概念                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Token 是文本的基本单位,用于计费和限制。                     │
│                                                             │
│  英文规则:                                                  │
│  - 约 4 个字符 = 1 token                                    │
│  - 约 0.75 个单词 = 1 token                                 │
│                                                             │
│  中文规则:                                                  │
│  - 约 1-2 个汉字 = 1 token                                  │
│                                                             │
│  示例:                                                      │
│  "Hello, world!" → 4 tokens                                 │
│  "你好,世界!" → 约 6-8 tokens                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Token 计算工具 #

python
import tiktoken

def count_tokens(text: str, model: str = "gpt-4o-mini") -> int:
    encoding = tiktoken.encoding_for_model(model)
    return len(encoding.encode(text))

text = "你好,这是一个测试文本。"
print(f"Token 数量: {count_tokens(text)}")

费用估算 #

python
def estimate_cost(
    input_tokens: int,
    output_tokens: int,
    model: str = "gpt-4o-mini"
) -> float:
    prices = {
        "gpt-4o-mini": {"input": 0.15, "output": 0.60},
        "gpt-4o": {"input": 2.50, "output": 10.00},
        "gpt-4-turbo": {"input": 10.00, "output": 30.00},
        "gpt-3.5-turbo": {"input": 0.50, "output": 1.50}
    }
    
    price = prices.get(model, prices["gpt-4o-mini"])
    
    input_cost = (input_tokens / 1_000_000) * price["input"]
    output_cost = (output_tokens / 1_000_000) * price["output"]
    
    return input_cost + output_cost

cost = estimate_cost(1000, 500, "gpt-4o-mini")
print(f"预估费用: ${cost:.6f}")

常见问题排查 #

1. API Key 无效 #

text
错误信息:
"Invalid API Key"

解决方案:
1. 检查 API Key 是否正确复制
2. 确认 API Key 未过期
3. 检查是否有空格或换行符
4. 确认环境变量设置正确

2. 余额不足 #

text
错误信息:
"Insufficient quota"

解决方案:
1. 访问 Billing 页面充值
2. 检查使用限额设置
3. 等待额度重置(如有免费额度)

3. 请求超时 #

text
错误信息:
"Request timeout"

解决方案:
1. 检查网络连接
2. 增加超时时间
3. 使用重试机制
4. 考虑使用异步请求
python
from openai import OpenAI

client = OpenAI(timeout=60.0)

4. 速率限制 #

text
错误信息:
"Rate limit exceeded"

解决方案:
1. 添加请求间隔
2. 实现指数退避重试
3. 升级账户等级
4. 分散请求时间
python
import time
from openai import OpenAI, RateLimitError

client = OpenAI()

def chat_with_retry(message: str, max_retries: int = 3) -> str:
    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[{"role": "user", "content": message}]
            )
            return response.choices[0].message.content
        except RateLimitError:
            wait_time = 2 ** attempt
            print(f"速率限制,等待 {wait_time} 秒后重试...")
            time.sleep(wait_time)
    raise Exception("超过最大重试次数")

下一步 #

现在你已经完成了 OpenAI API 的快速入门,接下来学习 对话补全详解,深入了解 Chat Completions API 的各种功能!

最后更新:2026-03-29