English
主导航

旧版 API

OpenAI CLI

直接在终端中使用 OpenAI API。

使用命令行工具直接在终端中与 OpenAI API 进行交互。 openai 命令行工具。

安装

使用 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 会从以下位置读取你的 API 密钥: OPENAI_API_KEY:

Command:

export OPENAI_API_KEY="sk-..."

如果你还没有 API 密钥, 请在控制台中创建一个.

对于 Admin API 端点,请设置 OPENAI_ADMIN_KEY 。SDK 层会根据调用的端点自动选择管理密钥或默认的 API 密钥。

要指向其他的 API 主机,请设置 OPENAI_BASE_URL.

用例

当工作理应在终端中进行时,请使用 CLI:

  • 生成图像或语音等本地文件。
  • 将结构化数据提取为 JSONL,以便用于后续的 shell 处理步骤。
  • 在云端结合文件、计算机使用和当前网络上下文使用 Responses。
  • 使用 Admin API 创建项目和 API 密钥。

直接用于一次性的终端请求,或在代理 (agent) 需要对文件和生成内容进行可重复的批处理工作时用于脚本中。

CLI 与 Codex 子代理

当你希望检查和重新运行可重复的 API 工作(如批量提取、文件转换、文件生成或精心挑选模型)时,请使用 CLI。当工作仍需要人为判断时(如探索代码、比较假设、调试或审查更改),请使用子代理。

全局标志

这些选项适用于所有命令:

标志使用
--format将响应打印为 auto, json, jsonl, pretty, raw, yaml, or explore.
--transform在打印之前,使用 GJSON 路径提取或重塑响应数据。
--debug将请求和响应的详细信息打印到标准错误 (stderr)。授权信息会被隐去;在分享日志前请检查请求头。

本指南侧重于 CLI 的使用模式。如需了解任何 API 系列的最新参数和响应结构,请使用实时的 API 参考.

当你需要将 CLI 指向另一个兼容的端点时(例如支持不同模型集或仅支持部分 API 接口的部署),你也可以更改 Base URL。

响应

使用 Responses 进行文本生成、结构化提取、网络搜索、文件理解,以及可重复的 Codex 编写的批处理脚本。

发送你的第一个请求

Command:

1
2
3
openai responses create \
--model gpt-5.5 \
--input "Say hello in one sentence."

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
  "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'

将本地文件添加到提示词中

对于简单的本地文件,请使用命令替换内联构建提示词:

1
2
3
4
5
6
7
8
9
openai responses create \
--model gpt-5.5 \
--input "Summarize this note in one sentence.

<note>
$(cat ./note.md)
</note>" \
--format yaml \
--transform 'output.#(type=="message").content.0.text'

Output:

The note says the launch checklist is ready except for final support ownership.

传递请求体

使用标志进行简短标量输入。对于多行提示词、工具、文件或嵌套请求体,请使用 YAML heredoc。该 heredoc 可以包含与您作为标志传递的相同的请求字段。

小心处理类似于 YAML 的字符串值,尤其是包含以下内容的提示词 : or {}。在标志上,生成的解析器可能会将这些值解释为结构化 YAML,而不是纯文本。如果提示词看起来像配置,请将其放在 input: | 在 YAML 体中代替:

Command:

1
2
3
4
5
6
7
8
9
10
11
12
13
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

Output:

The release note updates the CLI docs with corrected image generation and installation guidance.

当提示词本身需要 shell 拼接时,请构建一个 YAML 体并将其通过管道传递给命令:

1
2
3
4
5
6
7
8
9
10
{
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-5.5 \
--format yaml \
--transform 'output.#(type=="message").content.0.text'

将结构化数据写入 JSON

当下游脚本需要稳定的 JSON 时,请使用结构化输出。将可重用的 schema 保存到磁盘:

另存为 schema.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "type": "json_schema",
  "name": "fact",
  "strict": true,
  "schema": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "person": { "type": "string" },
      "topic": { "type": "string" }
    },
    "required": ["person", "topic"]
  }
}

Command:

1
2
3
4
5
6
7
openai responses create \
--model gpt-5.5 \
--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'

Output:

{ "person": "Ada Lovelace", "topic": "notes about the Analytical Engine" }

将结构化记录写入 JSONL

当一个输入可能产生多条记录时,请向模型请求一个数组,并将其展平为 JSONL,以便后续的 shell 步骤可以逐行处理每条记录:

另存为 records-schema.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
  "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"]
  }
}

Command:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
: > 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

这保持了模型响应的结构化,同时为后续的 shell 步骤逐行生成一个 JSON 对象。

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

Command:

1
2
3
4
5
6
7
8
9
10
openai responses create \
--model gpt-5.5 \
--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

Output:

- Apple announced ...
- Analysts highlighted ...
- The company said ...

文件输入

对于上传的文件(例如 PDF),请首先创建文件,捕获其 ID,并将其作为 input_file.file_id:

Command:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

Output:

- The brief proposes ...
- Risks: migration timing, unclear rollback criteria, and unresolved support ownership.

最近的生成构建会将本地文件标志作为包含文件名和内容类型元数据的多部分文件部分发送。如果本地上传命令失败并出现 UploadFile 类型错误,请更新 CLI 并重试。

图像

多轮图像生成

生成图像,提取 base64 有效载荷,并将其解码为常规的资源文件:

Command:

1
2
3
4
5
6
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'

Output:

wrote hero.png

目前的限制:图像命令尚无原生 --output 支持,因此图像生成仍需要提取 b64_json and decoding it yourself.

For gpt-image-2, omit --input-fidelity;图像输入始终以高保真度进行处理。请勿使用 --background transparent with gpt-image-2。该模型还支持比早期 GPT Image 模型更广泛的 --size 值,只要请求的分辨率符合 Image API 尺寸约束即可。

编辑图片

图像编辑在编辑请求成功后,使用相同的 base64 提取模式:

Command:

1
2
3
4
5
6
7
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'

Output:

wrote hero-edited.png

如果本地图像编辑上传失败,并出现 UploadFile 类型错误,请更新 CLI 并重试。

语音

使用语音 API 在本地创建一个 MP3 文件:

Command:

1
2
3
4
5
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

Output:

Wrote output to: speech.mp3

使用本地可用的任何音频工具进行播放。在 macOS 上:

afplay speech.mp3

使用 --instructions to shape delivery and --input 代表应说出的文字。指令非常适用于控制节奏、能量、热情、正式程度、强调重点或面向受众等提示:

1
2
3
4
5
6
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 管道输出纯文本记录:

Command:

1
2
3
4
5
openai audio:transcriptions create \
  --model gpt-4o-transcribe \
  --file ./speech.mp3 \
  --transform text \
  --raw-output

Output:

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

使用与所需生成内容相匹配的响应格式:

需求Command 格式
纯文本记录--model gpt-4o-transcribe --transform text --raw-output
字幕文件--model whisper-1 --response-format srt or --response-format vtt
段落或词级别时间戳--model whisper-1 --response-format verbose_json
带说话人标签的说话人分离--model gpt-4o-transcribe-diarize --response-format diarized_json

如需词级别时间信息,请请求 verbose transcription 格式:

Command:

1
2
3
4
5
6
openai audio:transcriptions create \
  --model whisper-1 \
  --file ./speech.mp3 \
  --response-format verbose_json \
  --timestamp-granularity word \
  --format json

Output:

1
2
3
4
5
6
7
8
9
10
11
{
  "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:

Command:

1
2
3
4
5
openai audio:transcriptions create \
  --model gpt-4o-transcribe-diarize \
  --file ./speech.mp3 \
  --response-format diarized_json \
  --format json

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "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:* commands.

要配置新的机器凭证,请 创建一个项目, 在该项目中创建一个服务账户 并使用返回的 API 密钥。

创建项目、服务账户和 API 密钥

在该项目中创建服务账户会返回该服务账户的未脱敏 API 密钥。

Command:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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

Output:

1
2
3
4
5
6
7
8
9
10
{
  "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 as OPENAI_API_KEY=...。将这两个 JSON 文件视为机密,并添加 project.json, service-account.json,且 .env to .gitignore 在将此模式用于代码仓库之前。

关于其余接口,请参见 Admin APIs 指南 and the current 管理 API 参考。请谨慎向未经审查的参与者授予管理员密钥的访问权限。