使用 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 整合後,你可以在 shell 提示字元處編輯選取的指令。
執行 openai explore --help 即可查看支援的 shell 和鍵盤快速鍵。
驗證身分
CLI 會從 OPENAI_API_KEY 讀取你的 API 金鑰:
指令:
export OPENAI_API_KEY="sk-..."
如果還沒有 API 金鑰,請前往控制台建立金鑰。
若要呼叫 Admin API 端點,請改為設定 OPENAI_ADMIN_KEY。SDK 層會根據呼叫的端點,選用管理員金鑰或預設 API 金鑰。
若要連線到其他 API 主機,請設定 OPENAI_BASE_URL。
使用情境
下列工作適合在終端使用 CLI 完成:
- 在本機生成圖像或語音等檔案。
- 擷取結構化資料並存成 JSONL,供後續 shell 步驟處理。
- 在雲端透過 Responses 處理檔案、操作電腦,以及取得最新網頁內容作為上下文。
- 使用 Admin API 建立專案和 API 金鑰。
你可以直接在終端使用 CLI 傳送單次請求。如果智慧體需要反覆批次處理檔案和生成的產物,也可以從指令碼呼叫 CLI。
在 Codex 中選用 CLI 或子代理程式
如果你想檢查並重新執行可重複的 API 作業,例如批次擷取資料、轉換檔案、生成產物或明確指定模型,請使用 CLI。如果工作仍需要判斷,例如探索程式碼、比較假設、偵錯或審查變更,請使用子代理程式。
全域旗標
下列選項可搭配各項指令使用:
| 旗標 | 用途 |
|---|---|
--format |
以 auto、json、jsonl、pretty、raw、yaml 或 explore 格式輸出回應。 |
--transform |
在輸出前,使用 GJSON 路徑擷取回應資料或調整其結構。 |
--debug |
將請求和回應的詳細資料輸出至 stderr。CLI 會遮蔽 Authorization 標頭的值,分享記錄前請先檢查各個標頭。 |
本指南著重於 CLI 的用法。各類 API 的最新引數和回應結構,請查閱線上 API 參考文件。
如果需要將 CLI 連線到其他相容端點,也可以變更基底 URL。例如,某個部署可能支援不同的模型,或僅支援部分 API 功能。
Responses
你可以使用 Responses 生成文字、擷取結構化資料、搜尋網頁、理解檔案內容,也可以在 Codex 撰寫的批次指令碼中呼叫 Responses,重複執行這些工作。
傳送第一個請求
指令:
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 回應物件。本頁範例僅保留 id、status、model、output 和 usage 等代表性欄位,其餘省略。
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 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-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.
近期產生的 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 不支援透明背景。只要要求的解析度符合 Image API 的尺寸限制,這個模型的 --size 可用值範圍就比先前的 GPT Image 模型更廣。
編輯圖像
圖像編輯請求成功後,請用相同的方式擷取 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 後再試一次。
語音
這些 Speech 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 格式,回應會包含轉錄文字,但不會包含說話者標籤。
Admin API
你可以使用 Admin 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。
如需瞭解其他管理功能,請參閱 Admin API 指南和最新版管理 API 參考文件。授予管理員金鑰存取權時請格外謹慎,尤其是對象尚未經過審核時。