OpenAI CLI

2026-11-04 11:05 更新

在终端中使用 openai 命令,可以直接调用OpenAI API并将响应接入Shell脚本。下面的Bash示例保留API参数、字段、模型ID和响应结构,中文注释说明操作目的;示意输出不保证与真实返回逐字一致。

安装

可通过 Homebrew 安装,或使用 Go 1.25 及以上版本安装。旧版 Python SDK 也曾附带同名 openai 命令;若已有安装且帮助信息与本页不同,检查当前终端解析到的可执行文件,避免混用旧命令。全新安装不受旧命令影响。

Bash

## 安装
brew install openai/tools/openai

Bash

## 安装
go install 'github.com/openai/openai-cli/cmd/openai@latest'

身份验证

CLI 从 OPENAI_API_KEY 读取普通 API 密钥;尚无密钥时在控制台创建。管理接口使用 OPENAI_ADMIN_KEY,底层客户端根据端点选择对应凭证。需要指定其他 API 主机时设置 OPENAI_BASE_URL。Windows PowerShell 当前会话的环境变量语法为 $env:OPENAI_API_KEY = "your_api_key_here";下面的 export 示例适用于 Bash。

Bash

## 身份验证
export OPENAI_API_KEY="sk-..."

适用场景

CLI 适合在终端生成图像、语音等文件,向 JSONL 提取结构化数据,结合文件、计算机操作或网页上下文使用 Responses,以及调用管理接口创建项目和凭证。既可以临时执行,也可以写成可检查、可重复运行的批处理脚本。

CLI 与 Codex 子智能体的分工

有明确输入与输出、需要检查和重跑的批量提取、文件转换、产物生成或模型选择,可交给 CLI 脚本;探索代码、比较假设、排错和审查等仍需要判断的工作,可由子智能体承担。

全局选项

参数 作用
--format 输出 auto、json、jsonl、pretty、raw、yaml 或 explore 格式
--transform 用 GJSON 路径提取或变换响应内容
--debug 将请求与响应细节写到标准错误;Authorization会脱敏,共享日志前仍须检查其他头部

不同 API 系列的具体参数、响应结构以接口参考为准。OPENAI_BASE_URL 也可用于支持不同模型集合或 API 子集的兼容部署。

Responses 请求

Responses 可用于文本生成、结构化提取、网页搜索、文件理解,以及可重复执行的批处理。

发送首次请求

默认会打印完整 API 响应对象。下面的输出仅保留 id、status、model、output、usage 等代表字段,省略其他内容。输出中可能先出现推理等非消息条目,因此提取助手文本应按 type=="message" 筛选,不要假定文本总在 output[0]。单独展示的 --transform 是命令选项片段,要附在完整命令后使用。

OpenAI CLI / Bash

## 发送首次请求
openai responses create \
  --model gpt-6-astra \
  --input "Say hello in one sentence."

JSON

以下为输出或数据结构示意,标识、文本、模型名和用量以实际响应为准。

{
  "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"
}

Bash

## 发送首次请求
--transform 'output.#(type=="message").content.0.text'

把本地文件内容加入提示词

下面用命令替换读取 note.md,把文本放入提示词。该方式将文件内容作为字符串拼接进请求;需要模型直接处理PDF等文件时,使用后面的文件上传示例。输出文本是示意,不要求逐字一致。

OpenAI CLI / Bash

## 把本地文件内容加入提示词
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 here-document。正文可以包含原本通过参数传入的请求字段。含 :、{} 等符号的字符串可能被参数解析器当作 YAML 结构,复杂提示词应放入 YAML 的 input: | 文本块。带引号的 <<'YAML' 不展开Shell变量;需要在Shell中组装提示词时,可生成YAML后通过管道送入命令。

OpenAI CLI / Bash

## 传递请求体
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.

OpenAI CLI / Bash

## 传递请求体
{
  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,并将其保存为 schema.json。示例要求提取 person 与 topic,禁止额外字段。--text.format 读取该Schema,请求完成后再从助手消息提取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 CLI / Bash

## 提取结构化 JSON
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'

JSON

以下为输出或数据结构示意,标识、文本、模型名和用量以实际响应为准。

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

将结构化记录写成 JSONL

先将Schema保存为 records-schema.json,要求根对象含 items 数组,每项包含标题、摘要和证据。脚本逐个处理 notes/*.md,再用 jq 将数组拆成一行一个JSON对象,并附上来源文件。模型仍返回结构化对象,JSONL展开由Shell流水线负责。示例的 : > records.jsonl 会清空目标文件,运行时应先确认输出路径。

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"]
  }
}

OpenAI CLI / Bash

## 将结构化记录写成 JSONL
: > 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

网页搜索

可在同一个YAML请求体中声明托管工具 web_search,并要求结果附带来源。示例研究对象仅演示命令写法,输出中的省略号不是实际新闻或分析结果。

OpenAI CLI / Bash

## 网页搜索
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,再在 input_file.file_id 中引用。当前生成式CLI会把本地文件参数作为带文件名和内容类型的multipart文件部分发送;如果上传遇到 UploadFile 类型错误,先更新CLI,再检查并重试该命令。下面脚本保留原页的变量展开形式。

OpenAI CLI / Bash

## 文件输入
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.

图像

图像生成与编辑返回的数据可以提取为base64,再解码成普通图片文件。

生成图像

示例提取 data.0.b64_json 并解码到 hero.png。图像命令目前没有原生 --output 选项,仍需自己提取并解码。gpt-image-2 的图像输入总以高保真处理,不传 --input-fidelity;透明背景处于预览,用 --background transparent 配合PNG或WebP,不能使用JPEG。可用尺寸仍须符合Image API限制。下面的base64命令按Bash环境示范,平台工具参数有差异时使用对应的解码方式。

Bash

## 生成图像
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

编辑图像

编辑请求成功后,采用相同的base64提取与解码流程保存 hero-edited.png。如果本地图片上传发生 UploadFile 类型错误,先更新CLI并核对文件。

Bash

## 编辑图像
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

语音合成

本节保留原文的Speech API示例:gpt-4o-mini-tts 已弃用,计划于 2027年1月6日 停用。迁移到 gpt-realtime-2.1-mini 必须按Realtime API改造,不能仅替换 openai audio:speech create 的模型ID;状态见弃用公告。

第一个命令保存MP3;afplay 是macOS播放示例。--input 指要朗读的文字,--instructions 用于语速、力度、情绪、正式程度、重音或受众等表达要求。下面按原顺序列出生成、输出提示、播放与带表达指令的示例。

Bash

## 语音合成
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

Bash

## 语音合成
afplay speech.mp3

Bash

## 语音合成
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

语音转写

一般文件转写示例使用 gpt-transcribe,提取 text 并用 --raw-output 打印纯文本,便于继续接入Shell流水线。

后续保留既有集成的专用例子:whisper-1 与 gpt-4o-transcribe-diarize 已弃用,计划于 2027年2月26日 停用。更换推荐模型不保证保留所有输出格式或元数据字段,迁移时核对弃用公告及转写工作流。

需要的输出 原页对应选项
字幕文件 whisper-1 与 srt 或 vtt
片段或词级时间戳 whisper-1 与 verbose_json;词级还需 --timestamp-granularity word
带说话人标识 gpt-4o-transcribe-diarize 与 diarized_json

whisper-1 支持 json、text、srt、verbose_json、vtt。说话人标识在 diarized_json 的 segments[].speaker 中;同一说话人分离模型改用普通 json 时只返回转写文本,不返回说话人标签。下面依次为普通转写、输出示意、词时间戳和说话人分离示例。

Bash

## 语音转写
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.

Bash

## 语音转写
openai audio:transcriptions create \
  --model whisper-1 \
  --file ./speech.mp3 \
  --response-format verbose_json \
  --timestamp-granularity word \
  --format json

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"
}

Bash

## 语音转写
openai audio:transcriptions create \
  --model gpt-4o-transcribe-diarize \
  --file ./speech.mp3 \
  --response-format diarized_json \
  --format json

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"
}

管理接口

管理接口用于组织管理、凭证配置、合规和用量监控。设置 OPENAI_ADMIN_KEY 后调用生成式 admin:organization:* 命令。为应用创建机器凭证时,流程是先创建项目,再在项目内创建服务账号,使用返回的API密钥。

创建项目、服务账号与 API 密钥

脚本将项目响应保存为 project.json,用 jq 提取项目ID,再创建服务账号并保存 service-account.json,最后将返回的API密钥写入 .env。这是会创建真实资源与凭证的操作示例,不是只读查询。

使用该模式前,将 project.json、service-account.json 和 .env 加入 .gitignore;这些文件可能含敏感信息。服务账号创建响应中的完整密钥要妥善保存。其他操作见管理接口指南与管理接口参考,不要将管理密钥开放给不可信的执行方。

Bash

## 创建项目、服务账号与 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

JSON

以下为输出或数据结构示意,标识、文本、模型名和用量以实际响应为准。

{
  "object": "organization.project.service_account",
  "id": "svc_acct_...",
  "name": "automation bot",
  "role": "member",
  "api_key": {
    "id": "key_...",
    "value": "sk-..."
  }
}
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号