OpenAI / Codex
OpenAI 的 GPT 系列模型,包括通用对话和代码生成场景常用的 Codex / GPT 模型。
基本信息
- 官方 API:
/v1/chat/completions - 统一网关格式:
/api/openai/v1/chat/completions - 鉴权头:
Authorization: Bearer ...
聊天补全
- 方法:
POST - 官方路径:
/v1/chat/completions - 统一路径:
/api/openai/v1/chat/completions
请求头
| 名称 | 必填 | 说明 |
|---|---|---|
Authorization | 是 | Bearer token 用于身份验证 |
Content-Type | 是 | 请求内容类型,固定为 application/json |
请求体
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | 例如 gpt-4、gpt-4-turbo-preview |
messages | array | 是 | 到目前为止对话的消息列表 |
temperature | number | 否 | 采样温度 |
max_tokens | integer | 否 | 最大输出 token 数 |
stream | boolean | 否 | 是否流式返回 |
top_p | number | 否 | nucleus 采样 |
n | integer | 否 | 返回多少个候选 |
presence_penalty | number | 否 | 主题重复惩罚 |
frequency_penalty | number | 否 | 频率重复惩罚 |
请求示例
官方格式
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-4",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
}'
统一格式
curl https://your-domain.com/api/openai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $YOUR_API_KEY" \
-d '{
"model": "gpt-4",
"messages": [
{"role": "user", "content": "Hello!"}
]
}'
TypeScript
import OpenAI from 'openai'
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Hello!' },
],
})
console.log(completion.choices[0].message.content)
Python
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
completion = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
)
print(completion.choices[0].message.content)
成功响应
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"model": "gpt-4",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I assist you today?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 9,
"total_tokens": 18
}
}
速率限制
- 每分钟请求数:
500 - 每分钟 token 数:
10000 - 响应头:
x-ratelimit-limit-requestsx-ratelimit-remaining-requestsx-ratelimit-reset-requests
流式响应
- 协议:
SSE - 关键事件:
data:包含部分响应[DONE]:表示流结束
const stream = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Say hello!' }],
stream: true,
})
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '')
}
函数调用
GPT 模型支持函数调用以生成结构化输出。
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{
role: 'user',
content: "What's the weather like in Boston?"
}],
functions: [{
name: 'get_current_weather',
description: 'Get the current weather in a given location',
parameters: {
type: 'object',
properties: {
location: { type: 'string' }
},
required: ['location']
}
}]
})
Prompt Caching
- 命中缓存后,
usage.cached_tokens会显示缓存命中量 - 缓存命中的输入 tokens 会按 Cached Input 价格计费
- 是否支持缓存与保留策略,以供应商官方说明为准
模型
| 模型 | 上下文窗口 | 最大输出 | 价格(输入 / 输出,USD / 1M) | 能力 |
|---|---|---|---|---|
| GPT-4 | 8192 | 4096 | 30 / 60 | 流式、函数调用 |
| GPT-4 Turbo | 128000 | 4096 | 10 / 30 | 流式、函数调用、视觉 |
| GPT-3.5 Turbo | 16385 | 4096 | 0.5 / 1.5 | 流式、函数调用 |
SDK
| 语言 | 包名 | 安装命令 | 仓库 |
|---|---|---|---|
| TypeScript | openai | npm install openai | https://github.com/openai/openai-node |
| Python | openai | pip install openai | https://github.com/openai/openai-python |
常见错误码
| 代码 | HTTP 状态 | 含义 | 处理建议 |
|---|---|---|---|
invalid_request_error | 400 | 请求无效 | 检查参数和格式 |
invalid_api_key | 401 | API 密钥无效 | 检查密钥是否正确 |
rate_limit_exceeded | 429 | 超出速率限制 | 放慢请求速率或退避重试 |
insufficient_quota | 429 | 配额不足 | 检查套餐和计费 |
server_error | 500 | 服务器错误 | 稍后重试 |
最佳实践
- 使用系统消息设置助手行为
- 为速率限制实现指数退避
- 监控 token 使用以控制成本
- 长前缀场景关注 Prompt Caching 命中率
- 使用流式传输改善用户体验