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 コマンドもインストールされていました。そのパッケージをすでにインストールしていて、手元のコマンドがこのガイドの説明と一致しない場合は、シェルが旧版の実行ファイルを参照している可能性があります。CLI を新規にインストールする場合、この問題はありません。
コマンドの検索
API キーを設定する前でも、ターミナルで openai explore を実行すると、利用できるコマンドを調べられます。
たとえば、count tokens offline と入力すると、オフラインでトークン数を数える openai tokenizer count が候補に表示されます。
矢印キーで目的の候補に移動し、Enter で選択するか、Escape でキャンセルします。
Explore は、選択したコマンドを実行せずに表示します。シェル連携を使うと、選択したコマンドをシェルのプロンプトで編集できます。
対応するシェルとキーボードショートカットを確認するには、openai explore --help を実行してください。
認証
CLI は OPENAI_API_KEY から API キーを読み取ります。
コマンド:
export OPENAI_API_KEY="sk-..."
API キーをまだお持ちでない場合は、ダッシュボードで作成してください。
Admin API のエンドポイントを利用する場合は、代わりに OPENAI_ADMIN_KEY を設定します。SDK 層は、呼び出すエンドポイントに応じて管理者キーとデフォルトの API キーを使い分けます。
別の API ホストに接続するには、OPENAI_BASE_URL を設定します。
用途
CLI は、ターミナルで行う次のような作業に適しています。
- 画像や音声などのファイルをローカルに生成
- 後続のシェル処理に使う構造化データを JSONL 形式で抽出
- クラウド上の Responses で、ファイル、コンピューターの使用、ウェブ上の最新情報を活用
- Admin API でプロジェクトや API キーを作成
単発のリクエストはターミナルから直接実行できます。エージェントがファイルや生成物を繰り返しバッチ処理する場合は、スクリプトから CLI を呼び出します。
Codex での CLI とサブエージェントの使い分け
データの一括抽出、ファイル変換、成果物の生成、用途に応じたモデルの明示的な選択など、処理内容を確認して再実行したい定型的な API 操作には CLI を使います。コードの調査、仮説の比較、デバッグ、変更内容のレビューなど、判断を伴う作業にはサブエージェントを使います。
グローバルフラグ
次のオプションは各コマンドで共通して使えます。
| フラグ | 用途 |
|---|---|
--format |
レスポンスの出力形式を auto、json、jsonl、pretty、raw、yaml、explore から選びます。 |
--transform |
出力前に GJSON パスを使ってレスポンスのデータを抽出または整形します。 |
--debug |
リクエストとレスポンスの詳細を標準エラー出力に書き出します。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 のヒアドキュメントを使います。フラグで渡すリクエストフィールドは、ヒアドキュメントにも記述できます。
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.
プロンプト自体をシェルで組み立てる場合は、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 への書き出し
1 つの入力から複数のレコードが得られる場合は、モデルに配列を返すよう指示し、その要素を JSONL として書き出します。これで、後続のシェル処理では 1 行につき 1 レコードを処理できます。
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 オブジェクトを 1 行に 1 つずつ出力できます。
ウェブ検索
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 を取得して 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 では、フラグで指定したローカルファイルを、ファイル名とコンテンツタイプのメタデータを付けてマルチパートのファイルパートとして送信します。ローカルファイルのアップロードコマンドが 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 のサイズ制約を満たしていれば、従来の GPT Image モデルよりも幅広い値を --size に指定できます。
画像の編集
画像を編集する場合も、編集リクエストが成功した後、同じ手順で 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 だけを変更する方法には対応していません。詳しくは提供終了のお知らせをご覧ください。
Speech 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文字起こし
シェルのパイプラインで使うために、文字起こし結果をプレーンテキストで出力します。
コマンド:
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.
上の例では、音声ファイルの文字起こしに推奨されるモデルを使用しています。既存の連携では、次の用途別の例も引き続き利用できます。
whisper-1 と gpt-4o-transcribe-diarize は非推奨で、2027 年 2 月 26 日に提供を終了します。推奨の文字起こしモデルに切り替えると、一部の出力形式やメタデータフィールドが使えなくなります。詳しくは提供終了のお知らせと文字起こしのワークフローをご覧ください。
| 用途 | コマンドの指定例 |
|---|---|
| 字幕ファイル | --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 キーの値が省略されずに返されます。
コマンド:
# 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 リファレンスをご覧ください。管理者キーへのアクセスを許可する際は、相手の信頼性を十分に確認してください。