使用 openai 命令行工具,您可以直接在终端中调用 OpenAI API。
安装
使用 Homebrew 安装 CLI:
brew install openai/tools/openai
也可以使用 Go 1.25 或更高版本安装:
go install 'github.com/openai/openai-cli/cmd/openai@latest'
旧版 Python SDK 也会安装旧版 openai 命令。如果您之前安装过该软件包,而当前看到的命令与本指南不一致,可能是因为 shell 仍将该命令解析为旧版可执行文件。全新安装 CLI 不受此问题影响。
浏览命令
在设置 API 密钥之前,您就可以在终端中运行 openai explore 来浏览命令。
输入任务描述即可查找相应的命令。例如,输入 count tokens offline 可以找到 openai tokenizer count。
使用方向键高亮显示匹配项,按 Enter 选中该项,或按 Escape 取消。
Explore 只显示选中的命令,不会执行。启用 shell 集成后,您可以在命令行提示符处编辑选中的命令。
运行 openai explore --help 可查看支持的 shell 和键盘快捷键。
身份验证
CLI 从 OPENAI_API_KEY 读取您的 API 密钥:
命令:
export OPENAI_API_KEY="sk-..."
如果您还没有 API 密钥,请在控制台中创建密钥。
对于管理 API 端点,请改为设置 OPENAI_ADMIN_KEY。SDK 层会根据所调用的端点选择管理密钥或默认 API 密钥。
要连接其他 API 主机,请设置 OPENAI_BASE_URL。
使用场景
以下任务适合在终端中使用 CLI 完成:
- 生成图像或语音等本地文件。
- 提取结构化数据并保存为 JSONL,供后续 shell 步骤使用。
- 在云端通过 Responses 处理文件、调用计算机使用功能或获取最新网页信息作为上下文。
- 使用管理 API 创建项目和 API 密钥。
您可以直接在终端中使用 CLI 发送一次性请求。如果智能体需要反复批量处理文件和生成的产物,也可以从脚本中调用 CLI。
在 Codex 中选择 CLI 或子智能体
对于需要检查并重复运行的 API 任务,例如批量提取数据、转换文件、生成产物或明确指定模型,请使用 CLI。对于仍需做出判断的任务,例如探索代码、比较假设、调试或审查更改,请使用子智能体。
全局选项
以下选项适用于各个命令:
| 选项 | 用途 |
|---|---|
--format |
指定响应的输出格式,可选值为 auto、json、jsonl、pretty、raw、yaml 或 explore。 |
--transform |
在输出前使用 GJSON 路径提取响应数据或调整其结构。 |
--debug |
将请求和响应的详细信息输出到标准错误流。Authorization 标头的值会被隐去。共享日志前,请检查标头。 |
本指南介绍 CLI 的常见用法。如需了解各类 API 的最新参数和响应结构,请查阅在线 API 参考文档。
如果需要将 CLI 指向其他兼容端点,也可以更改基础 URL。例如,目标部署可能支持不同的一组模型,或仅提供部分 API 功能。
Responses
使用 Responses 可以生成文本、提取结构化数据、执行网页搜索、理解文件内容,也可以在 Codex 编写的批处理脚本中反复执行这些任务。
发送第一个请求
命令:
openai responses create \
--model gpt-6.2-astra \
--input "Say hello in one sentence."输出:
{
"id": "resp_...",
"object": "response",
"status": "completed",
"model": "gpt-5.5-...",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Hello!"
}
]
}
],
"usage": {
"input_tokens": 12,
"output_tokens": 6,
"total_tokens": 18
},
"...": "additional response fields omitted"
}
CLI 默认输出完整的 API 响应对象。本页示例保留了 id、status、model、output 和 usage 等代表性字段,其余字段均已省略。
在 Responses 的输出中,助手消息之前可能还有推理项等非消息项。要获取助手回复的文本,请按类型选择消息项,因为它不一定是 output[0]:
--transform 'output.#(type=="message").content.0.text'
将本地文件添加到提示词
要使用本地文件,请通过命令替换直接在命令中构建提示词:
openai responses create \
--model gpt-6.2-astra \
--input "Summarize this note in one sentence.
<note>
$(cat ./note.md)
</note>" \
--format yaml \
--transform 'output.#(type=="message").content.0.text'输出:
The note says the launch checklist is ready except for final support ownership.
传递请求体
对于较短的标量输入,请使用命令行选项。对于多行提示词、工具、文件或嵌套的请求体,请使用 YAML here-document。原本通过命令行选项传递的请求字段也可以写入 here-document。
请留意看起来像 YAML 的字符串值,尤其是包含 : 或 {} 的提示词。通过命令行选项传入这些值时,自动生成的解析器可能会将其解析为结构化 YAML,而非纯文本。如果提示词的写法类似配置内容,请将其放在 YAML 请求体的 input: | 下:
命令:
openai responses create \
--format yaml \
--transform 'output.#(type=="message").content.0.text' <<'YAML'
model: gpt-5.5
instructions: Return exactly one sentence.
max_output_tokens: 120
input: |
Summarize this release note in one sentence.
<release_note>
Fixed the image generation example and added CLI installation guidance.
</release_note>
YAML输出:
The release note updates the CLI docs with corrected image generation and installation guidance.
如果提示词本身需要在 shell 中拼接,请构建 YAML 请求体,再通过管道将其传给命令:
{
printf 'input: |\n'
printf ' Summarize this note in one sentence.\n\n'
printf ' <note>\n'
sed 's/^/ /' ./note.md
printf ' </note>\n'
} | openai responses create \
--model gpt-6.2-astra \
--format yaml \
--transform 'output.#(type=="message").content.0.text'将结构化数据写入 JSON
如果下游脚本需要格式稳定的 JSON,请使用结构化输出。将可复用的模式保存到磁盘:
保存为 schema.json:
{
"type": "json_schema",
"name": "fact",
"strict": true,
"schema": {
"type": "object",
"additionalProperties": false,
"properties": {
"person": { "type": "string" },
"topic": { "type": "string" }
},
"required": ["person", "topic"]
}
}
命令:
openai responses create \
--model gpt-6.2-astra \
--instructions "Extract the person and topic from the input." \
--input "Ada Lovelace wrote notes about the Analytical Engine." \
--text.format "$(cat ./schema.json)" \
--format yaml \
--transform 'output.#(type=="message").content.0.text'输出:
{ "person": "Ada Lovelace", "topic": "notes about the Analytical Engine" }
将结构化记录写入 JSONL
如果一条输入可能产生多条记录,请让模型返回数组,再将数组展开为 JSONL,以便后续 shell 步骤按行处理,每行一条记录:
保存为 records-schema.json:
{
"type": "json_schema",
"name": "items",
"strict": true,
"schema": {
"type": "object",
"additionalProperties": false,
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"title": { "type": "string" },
"summary": { "type": "string" },
"evidence": { "type": "string" }
},
"required": ["title", "summary", "evidence"]
}
}
},
"required": ["items"]
}
}
命令:
: > records.jsonl
for file in notes/*.md; do
extracted="$(
openai responses create \
--model gpt-5.5 \
--text.format "$(cat ./records-schema.json)" \
--raw-output \
--transform 'output.#(type=="message").content.0.text' <<YAML
input: |
<note path="$file">
$(sed 's/^/ /' "$file")
</note>
YAML
)"
jq -r --arg source "$file" \
'.items[]? + {source: $source} | @json' \
<<<"$extracted" >> records.jsonl
done这样既能让模型返回结构化响应,又能每行输出一个 JSON 对象,供后续 shell 步骤使用。
网页搜索
在同一个 YAML 请求体中指定托管工具后,Responses 即可调用这些工具:
命令:
openai responses create \
--model gpt-6.2-astra \
--format yaml \
--transform 'output.#(type=="message").content.0.text' <<'YAML'
tools:
- type: web_search
input: |
Research the latest material news for AAPL.
Return three concise bullets and cite sources in the text.
YAML输出:
- Apple announced ...
- Analysts highlighted ...
- The company said ...
文件输入
对于 PDF 等需要上传的文件,请先上传并创建文件对象,取得其 ID,再通过 input_file.file_id 传入该 ID:
命令:
FILE_ID=$(
openai files create \
--file ./brief.pdf \
--purpose user_data \
--format yaml \
--transform id
)
openai responses create \
--model gpt-5.5 \
--format yaml \
--transform 'output.#(type=="message").content.0.text' <<YAML
input:
- role: user
content:
- type: input_text
text: Summarize this brief and list three risks.
- type: input_file
file_id: ${FILE_ID}
YAML输出:
- The brief proposes ...
- Risks: migration timing, unclear rollback criteria, and unresolved support ownership.
近期生成的 CLI 版本会将通过选项指定的本地文件作为 multipart 请求中的文件部分发送,并附上文件名和内容类型元数据。如果本地文件上传命令因 UploadFile 类型错误而失败,请更新 CLI 后重试。
图像
生成图像
生成图像后,提取 base64 编码的数据,再解码并保存为常规图像文件:
命令:
openai images generate \
--model gpt-image-2 \
--prompt "A simple product-style render of a translucent green cube on a neutral background." \
--format yaml \
--transform 'data.0.b64_json' | base64 --decode > hero.png
printf 'wrote hero.png\n'输出:
wrote hero.png
目前,图像命令尚未原生支持 --output,因此生成图像后仍需自行提取 b64_json 并解码。
使用 gpt-image-2 时,请省略 --input-fidelity。该模型始终以高保真度处理输入图像。透明背景功能已开放预览,请搭配使用 --background transparent 与 png(默认格式)或 webp。jpeg 不支持透明背景。与早期 GPT Image 模型相比,该模型还支持更多 --size 取值,前提是请求的分辨率符合 Image API 的尺寸限制。
编辑图像
图像编辑请求成功后,使用相同的方法提取 base64 编码的数据:
命令:
openai images edit \
--model gpt-image-2 \
--image ./hero.png \
--prompt "Turn the cube bright green." \
--format yaml \
--transform 'data.0.b64_json' | base64 --decode > hero-edited.png
printf 'wrote hero-edited.png\n'输出:
wrote hero-edited.png
编辑图像时,如果本地图像因 UploadFile 类型错误而上传失败,请更新 CLI 后重试。
语音
以下语音 API 示例使用已弃用的 gpt-4o-mini-tts 模型,该模型将于 2027 年 1 月 6 日停止服务。请迁移到 gpt-realtime-2.1-mini,并通过 Realtime API 调用该模型。仅更改 openai audio:speech create 中的模型 ID 无法完成迁移。请参阅弃用公告。
使用语音 API 在本地创建 MP3 文件:
命令:
openai audio:speech create \
--model gpt-4o-mini-tts \
--voice marin \
--input "The OpenAI CLI can call the API from ordinary shell scripts." \
--output speech.mp3输出:
Wrote output to: speech.mp3
您可以使用计算机上可用的音频工具播放该文件。在 macOS 上可运行:
afplay speech.mp3
使用 --instructions 指定朗读方式,使用 --input 提供要朗读的文本。您可以在指令中说明语速、表达是否富有活力、语气的亲切程度、正式程度、需要强调的内容或目标听众:
openai audio:speech create \
--model gpt-4o-mini-tts \
--voice marin \
--instructions "Whisper very quickly, like a hurried stage cue, while staying clear and intelligible." \
--input "The launch checklist is ready. Please send final feedback by Friday at noon." \
--output reminder.mp3转录
以纯文本形式输出转录结果,供 shell 管道使用:
命令:
openai audio:transcriptions create \
--model gpt-transcribe \
--file ./speech.mp3 \
--transform text \
--raw-output输出:
The OpenAI CLI can call the API from ordinary shell scripts.
上例使用推荐的文件转录模型。现有集成仍可使用下列示例来满足特定的转录需求:
| 需求 | 命令选项 |
|---|---|
| 字幕文件 | --model whisper-1 --response-format srt 或 --response-format vtt |
| 分段或逐词时间戳 | --model whisper-1 --response-format verbose_json |
| 区分并标注说话人 | --model gpt-4o-transcribe-diarize --response-format diarized_json |
要获取逐词时间戳,请请求详细的转录格式:
命令:
openai audio:transcriptions create \
--model whisper-1 \
--file ./speech.mp3 \
--response-format verbose_json \
--timestamp-granularity word \
--format json输出:
{
"task": "transcribe",
"language": "english",
"duration": 6,
"text": "The OpenAI CLI can call the API from ordinary shell scripts.",
"words": [
{ "word": "The", "start": 0, "end": 0.42 },
{ "word": "OpenAI", "start": 0.42, "end": 1.22 }
],
"...": "additional response fields omitted"
}
要在输出中标注说话人,请使用说话人分离模型,并请求 diarized_json 格式:
命令:
openai audio:transcriptions create \
--model gpt-4o-transcribe-diarize \
--file ./speech.mp3 \
--response-format diarized_json \
--format json输出:
{
"text": "The OpenAI CLI can call the API from ordinary shell scripts.",
"segments": [
{
"type": "transcript.text.segment",
"id": "seg_0",
"start": 0.05,
"end": 5.25,
"text": " The OpenAI CLI can call the API from ordinary shell scripts.",
"speaker": "A"
}
],
"...": "additional response fields omitted"
}
whisper-1 支持 json、text、srt、verbose_json 和 vtt。diarized_json 格式包含 segments[].speaker 字段。如果使用同一个说话人分离模型,但请求普通 json 格式,响应中会包含转录文本,但不会包含说话人标签。
管理 API
使用管理 API 可以管理组织、配置凭据、处理合规事务和监控用量。请先设置 OPENAI_ADMIN_KEY,然后调用自动生成的 admin:organization:* 命令。
要配置新的机器凭据,请先创建项目,再在该项目中创建服务账号,并使用返回的 API 密钥。
创建项目、服务账号和 API 密钥
在该项目中创建服务账号时,API 会返回该服务账号的完整 API 密钥。
命令:
# Create the project that will own this app or agent and save the response.
openai admin:organization:projects create \
--name "automation project" \
--format json > project.json
PROJECT_ID="$(jq -r '.id' project.json)"
# Create a service account inside the project and save the full response.
openai admin:organization:projects:service-accounts create \
--project-id "$PROJECT_ID" \
--name "automation bot" \
--format json > service-account.json
# Extract the returned API key into an env file for the workload to use.
jq -r '.api_key.value | "OPENAI_API_KEY=\(.)"' \
service-account.json > .env输出:
{
"object": "organization.project.service_account",
"id": "svc_acct_...",
"name": "automation bot",
"role": "member",
"api_key": {
"id": "key_...",
"value": "sk-..."
}
}
上述命令将创建项目的响应写入 project.json,从中提取项目 ID 并传给下一条命令,然后将创建服务账号的响应写入 service-account.json,并将返回的凭据写入 .env,格式为 OPENAI_API_KEY=...。请将这两个 JSON 文件都作为机密文件处理。在代码仓库中使用这一做法之前,请先将 project.json、service-account.json 和 .env 添加到 .gitignore。
如需了解其他管理功能,请参阅管理 API 指南和最新的管理 API 参考文档。向未经审查的人员或系统授予管理密钥访问权限时,请务必谨慎。