使用 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 金鑰。
你可以直接用它在終端中發出一次性請求;當智慧體需要對檔案和產生的成品執行可重複的批次工作時,也可以透過指令碼使用。
Codex 中 CLI 與子代理程式的比較
對於需要檢查及重新執行的可重複 API 工作,例如批次擷取、檔案轉換、成品產生,或需要明確選擇模型的工作,請使用 CLI。若工作仍需要判斷,例如探索程式碼、比較假設、除錯或審查變更,則使用子代理程式。
全域旗標
下列選項適用於各項指令:
| 旗標 | 用途 |
|---|---|
--format | 以 auto、json、jsonl、pretty、raw、yaml 或 explore 格式輸出回應。 |
--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 回應物件。本頁範例僅保留 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 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 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 在本機建立 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 支援 json、text、srt、verbose_json 和 vtt。diarized_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.json、service-account.json 和 .env 加入 .gitignore。
如需瞭解其餘功能,請參閱管理 API 指南及最新的管理 API 參考文件。授予未經審核的人員或系統管理金鑰存取權時,請務必謹慎。