OpenAI API调用手册
把文字提取成固定 JSON 字段
将用户输入转换为约定的任务字段,让后端可以校验和保存。
← 返回平台功能接入准备
- 模型支持 Structured Outputs;本例使用官方列明支持该功能的 gpt-6.1-sol。
准备环境变量
示例值需要替换为自己的凭证或资源 ID。代码在本机或服务端运行;密钥不应放进公开网页。
OPENAI_API_KEY- 在 API 平台的目标项目中创建的密钥;仅放自己的服务端环境变量。
export OPENAI_API_KEY='replace_with_project_api_key'以上 export 适用于 macOS / Linux 的终端,在同一终端内运行后续代码。Python 示例保存为 request.py 后执行 python3 request.py。
调用步骤
- 01
登录 OpenAI API 平台,创建或选择项目;确认组织、地区资格、模型权限和 API 账单可用。ChatGPT 订阅不代替 API 账单。
- 02
在目标项目的 API keys 页面创建密钥;若使用受限密钥,授予下方目标端点的写入权限。复制后在自己的服务端设置 OPENAI_API_KEY。
- 03
核对请求里的模型名、输入内容和输出上限,再运行代码。本网站不会代收密钥或向 OpenAI 发起请求。
- 04
先设计字段与 JSON Schema;只保留业务确实需要的字段,不把任意文字当成可信指令。
调用 01
按 JSON Schema 输出任务
Responses 使用 text.format;不要把 Chat Completions 的 response_format 原样搬到这里。
POST
https://api.openai.com/v1/responses请求头
AuthorizationBearer ${OPENAI_API_KEY}Content-Typeapplication/json
参数说明
参数表可左右滑动,查看完整说明。
| 字段 / 位置 | 类型 / 必填 | 说明 |
|---|---|---|
model / input请求体 | string必填 | 模型和待提取的原始文字。 |
text.format.type请求体 | string必填 | 本场景固定 json_schema。 |
text.format.name请求体 | string必填 | Schema 名称,本例 task_extract。 |
text.format.strict请求体 | boolean可选 | 本例 true,要求遵守支持的 Schema 子集。 |
text.format.schema请求体 | object必填 | 对象需列 properties、required,并按严格模式设 additionalProperties=false。 |
调用代码
替换示例 ID 与请求体内容后运行。cURL 会报 HTTP 错误,业务状态还需按下方返回示例核对。
cat > request-body.json <<'JSON'
{
"model": "gpt-6.1-sol",
"input": "请把检查登录接口记为普通优先级任务。",
"text": {
"format": {
"type": "json_schema",
"name": "task_extract",
"strict": true,
"schema": {
"type": "object",
"properties": {
"task": {
"type": "string"
},
"priority": {
"type": "string",
"enum": [
"normal",
"urgent"
]
}
},
"required": [
"task",
"priority"
],
"additionalProperties": false
}
}
},
"max_output_tokens": 1024,
"store": false
}
JSON
# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
--request POST \
--url "https://api.openai.com/v1/responses" \
--header "Authorization: Bearer ${OPENAI_API_KEY}" \
--header "Content-Type: application/json" \
--data-binary @request-body.json
import json
import os
import re
import urllib.request
import urllib.error
def expand(value):
return re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}",
lambda match: os.environ[match.group(1)], value)
url = expand("https://api.openai.com/v1/responses")
headers = {
"Authorization": expand("Bearer ${OPENAI_API_KEY}"),
"Content-Type": expand("application/json"),
}
body = {
"model": "gpt-6.1-sol",
"input": "请把检查登录接口记为普通优先级任务。",
"text": {
"format": {
"type": "json_schema",
"name": "task_extract",
"strict": True,
"schema": {
"type": "object",
"properties": {
"task": {
"type": "string",
},
"priority": {
"type": "string",
"enum": [
"normal",
"urgent",
],
},
},
"required": [
"task",
"priority",
],
"additionalProperties": False,
},
},
},
"max_output_tokens": 1024,
"store": False,
}
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
with urllib.request.urlopen(request, timeout=30) as response:
result = json.load(response)
except urllib.error.HTTPError as error:
print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
raise SystemExit(1)
print(json.dumps(result, ensure_ascii=False, indent=2))
// Node.js 22+,保存为 request.mjs 后运行 node request.mjs
function expand(value) {
return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (_, name) => {
if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`);
return process.env[name];
});
}
const url = expand("https://api.openai.com/v1/responses");
const headers = Object.fromEntries(
Object.entries({
"Authorization": "Bearer ${OPENAI_API_KEY}",
"Content-Type": "application/json"
}).map(([key, value]) => [key, expand(value)])
);
const body = {
"model": "gpt-6.1-sol",
"input": "请把检查登录接口记为普通优先级任务。",
"text": {
"format": {
"type": "json_schema",
"name": "task_extract",
"strict": true,
"schema": {
"type": "object",
"properties": {
"task": {
"type": "string"
},
"priority": {
"type": "string",
"enum": [
"normal",
"urgent"
]
}
},
"required": [
"task",
"priority"
],
"additionalProperties": false
}
}
},
"max_output_tokens": 1024,
"store": false
};
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(body),
signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
const result = JSON.parse(text);
console.log(JSON.stringify(result, null, 2));
返回示例
按官方字段整理的响应结构示意,ID、文本和数字均为虚构,非接口实测结果。text 是 JSON 字符串;先检查成功状态与拒绝,再 JSON.parse/json.loads,并继续做业务校验。 以下为结构示意,非本站实测结果。
{
"id": "resp_example_not_real",
"object": "response",
"status": "completed",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "{\"task\":\"检查登录接口\",\"priority\":\"normal\"}",
"annotations": []
}
]
}
],
"usage": {
"input_tokens": 30,
"output_tokens": 16,
"total_tokens": 46
}
}常见错误与排查
HTTP 401密钥认证失败。- 核对环境变量值、项目归属与密钥状态;重新生成已撤销或无效的密钥。
HTTP 403调用身份或所在地区不被允许使用该资源。- 检查模型和项目权限、支持地区及账号验证要求。
HTTP 429请求过快、余额耗尽或组织/项目用量上限触发,原因并不相同。- 读取 error.code;限流按 Retry-After 退避,余额或支出限制需在账单/项目中处理,不能靠快速重试解决。
HTTP 400请求参数或严格 Schema 不受支持。- 核对 text.format 层级、required、additionalProperties 和模型支持情况;缩小为受支持的 Schema 子集。
调用注意
- 全部 properties 在严格模式中应列入 required;可选业务字段可用允许 null 的联合类型表达。
- 结构符合 Schema 不保证事实正确。输入不含字段时要提前定义如何表达缺失,不要让模型凭空补全。
- 安全拒绝可能返回 refusal;输出被截断时 status 可为 incomplete,不能直接把任意文本当成有效 JSON。
注意事项
- 本例使用 gpt-6.1-sol 的标准文本调用,核验日每百万未缓存输入 Token 2 美元、输出 Token 10 美元;缓存、长上下文和其他处理模式另有规则。
- 示例未启用收费工具或外部检索。限流按组织、项目和模型计算,以项目 Limits 为准;返回 usage 才是本次用量依据。
核验来源
本站按官方资料整理本场景的必要调用步骤与代码,覆盖范围以本页列出的接口为准。官方资料用于追溯规范及查看变更。
- 01OpenAI 官方首次调用与密钥配置核验日期 2026-10-15
- 02GPT-6.1 Sol 模型能力和价格核验日期 2026-10-15
- 03OpenAI 组织、项目与模型限流核验日期 2026-10-15
- 04Structured Outputs 的 JSON Schema 与异常处理核验日期 2026-10-15
- 05Create a model response核验日期 2026-10-15
- 06OpenAI HTTP 错误及排查核验日期 2026-10-15
