For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
主导航

OpenAI CLI

直接在终端中使用 OpenAI API。

使用 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 不受影响。

身份验证

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 发起一次性的终端请求;当智能体需要对文件和生成的产物执行可重复的批处理工作时,也可以通过脚本调用它。

在 Codex 中选择 CLI 还是子智能体

对于您希望检查并重复运行的 API 工作,例如批量提取、文件转换、产物生成或有针对性的模型选择,请使用 CLI。对于仍需判断的工作,例如探索代码、比较假设、调试或审查更改,请使用子智能体。

全局标志

以下选项适用于各个命令:

标志用途
--formatautojsonjsonlprettyrawyamlexplore 格式输出响应。
--transform在输出前,使用 GJSON 路径提取响应数据或调整其结构。
--debug将请求和响应的详细信息输出到 stderr。Authorization 的内容会被遮蔽;分享日志前请检查标头。

本指南重点介绍 CLI 的使用方式。如需了解任意 API 类别的最新参数和响应结构,请查阅在线 API 参考

如果需要将 CLI 指向其他兼容端点,您也可以更改基础 URL,例如指向支持不同模型集或仅支持部分 API 功能的部署。

Responses

使用 Responses 进行文本生成、结构化提取、网页搜索和文件理解,也可在 Codex 编写的可重复运行的批处理脚本中使用它。

发送您的第一个请求

命令:

openai responses create \
  --model gpt-6-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 响应对象。本页示例保留了 idstatusmodeloutputusage 等代表性字段,并省略其余字段。

Responses 的输出中,助手消息之前可能包含推理项等非消息项。需要获取助手文本时,请按类型选择消息项,不要假定它始终位于 output[0]

--transform 'output.#(type=="message").content.0.text'

将本地文件添加到提示中

对于简单的本地文件,可以通过命令替换直接在命令中构建提示:

openai responses create \
  --model gpt-6-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 heredoc。heredoc 可以包含与通过标志传递时相同的请求字段。

请留意看起来像 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-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-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 步骤处理。

Responses 可以通过同一个 YAML 请求体调用托管工具:

命令:

openai responses create \
  --model gpt-6-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,再将该 ID 作为 input_file.file_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.

最近生成的构建版本会将通过本地文件标志指定的文件作为 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 transparentpng(默认格式)或 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 在本地创建 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-4o-transcribe \
  --file ./speech.mp3 \
  --transform text \
  --raw-output

输出:

The OpenAI CLI can call the API from ordinary shell scripts.

根据您需要的产物选择相应的响应格式:

需求命令格式
纯文本转录内容--model gpt-4o-transcribe --transform text --raw-output
字幕文件--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 支持 jsontextsrtverbose_jsonvttdiarized_json 格式包含 segments[].speaker;使用同一说话人分离模型和普通 json 格式时,响应包含转录文本,但不包含说话人标签。

管理 API

使用管理 API 处理组织管理、凭据配置、合规和用量监控工作流。设置 OPENAI_ADMIN_KEY,然后调用生成的 admin:organization:* 命令。

如需配置新的机器凭据,请先创建项目,再在该项目中创建服务账户,然后使用返回的 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,并将返回的凭据以 OPENAI_API_KEY=... 的形式写入 .env。请将这两个 JSON 文件视为机密文件,并在代码仓库中使用此方式之前,将 project.jsonservice-account.json.env 添加到 .gitignore

有关其余功能,请参阅管理 API 指南和最新的管理 API 参考。向未经审查的主体授予管理密钥的访问权限时,请务必谨慎。