For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
メインナビゲーション

OpenAI CLI

ターミナルから OpenAI API を直接利用できます。

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 を新規にインストールする場合は影響ありません。

認証

CLI は OPENAI_API_KEY から API キーを読み取ります。

コマンド:

export OPENAI_API_KEY="sk-..."

API キーをまだお持ちでない場合は、ダッシュボードで作成してください

管理 API のエンドポイントには、代わりに OPENAI_ADMIN_KEY を設定します。SDK レイヤーが、呼び出すエンドポイントに応じて管理キーまたはデフォルトの API キーを選択します。

別の API ホストに接続するには、OPENAI_BASE_URL を設定します。

ユースケース

次のような、ターミナルで行うのに適した作業には CLI を使います。

  • 画像や音声などの成果物をローカルに生成
  • 後続のシェル処理に向けて、構造化データを JSONL に抽出
  • クラウド上でファイル、コンピューターの使用、ウェブの最新情報を活用して Responses を利用
  • 管理 API によるプロジェクトと API キーの作成

ターミナルからの単発のリクエストには直接使えます。また、エージェントがファイルや生成した成果物に対して繰り返し実行できるバッチ処理を必要とする場合は、スクリプトから使えます。

Codex での CLI とサブエージェントの使い分け

一括抽出、ファイル変換、成果物の生成、意図に応じたモデルの選択など、内容を確認して再実行したい定型的な API 処理には CLI を使います。コードの調査、仮説の比較、デバッグ、変更のレビューなど、その都度判断が必要な作業にはサブエージェントを使います。

グローバルフラグ

以下のオプションは各コマンドで共通して使えます。

フラグ用途
--formatレスポンスを autojsonjsonlprettyrawyaml、または explore 形式で出力します。
--transform出力前に GJSON パスを使ってレスポンスデータを抽出または整形します。
--debugリクエストとレスポンスの詳細を stderr に出力します。Authorization はマスクされますが、ログを共有する前にヘッダーを確認してください。

このガイドでは CLI の使い方を中心に説明します。各 API の最新の引数やレスポンスの構造については、オンラインの API リファレンスを参照してください。

対応するモデルが異なるデプロイ先や、API の一部の機能のみをサポートするデプロイ先など、別の互換エンドポイントに CLI を接続する必要がある場合は、ベース URL も変更できます。

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 レスポンスオブジェクト全体を出力します。このページの例では、idstatusmodeloutputusage などの代表的なフィールドを残し、ほかは省略しています。

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 つの入力から複数のレコードが生成される場合は、モデルに配列を返すよう求め、それを 1 行に 1 レコードの JSONL に変換します。これにより、後続のシェル処理で各行を処理できます。

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

この方法なら、モデルのレスポンスの構造を保ちながら、後続のシェル処理に使えるよう、1 行に 1 つの JSON オブジェクトを出力できます。

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.

最近の自動生成ビルドでは、フラグで指定したローカルファイルを、ファイル名とコンテンツタイプのメタデータを含むマルチパートのファイルパートとして送信します。ローカルファイルのアップロードコマンドが 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 transparentpng(デフォルト)または 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

文字起こし

シェルのパイプラインで使えるよう、文字起こしをプレーンテキストで出力します:

コマンド:

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-1jsontextsrtverbose_jsonvtt に対応しています。diarized_jsonsegments[].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.jsonservice-account.json.env.gitignore に追加してください。

その他の機能については、管理 API ガイドと最新の管理 API リファレンスを参照してください。信頼性を確認していない相手に管理キーへのアクセスを許可する際は、十分に注意してください。