SPB Git

Repository Public

openai-cli.md 16.5 KB 595 lines markdown

1# OpenAI CLI23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45Interact with the OpenAI API directly from your terminal with the `openai` command-line tool.67## Installation89Install the CLI with Homebrew:1011```bash12brew install openai/tools/openai13```1415Or install it with Go 1.25 or later:1617```bash18go install 'github.com/openai/openai-cli/cmd/openai@latest'19```2021Older versions of the Python SDK also installed a legacy `openai` command. If you already had that package installed and the command you see does not match this guide, your shell may still be resolving the older binary. Fresh CLI installs are not affected.2223## Authentication2425The CLI reads your API key from `OPENAI_API_KEY`:2627Command:2829```bash30export OPENAI_API_KEY="sk-..."31```3233If you don't have an API key yet, [create one in the dashboard](https://platform.openai.com/api-keys).3435For Admin API endpoints, set `OPENAI_ADMIN_KEY` instead. The SDK layer selects the admin key or default API key based on the endpoint being called.3637To point at a different API host, set `OPENAI_BASE_URL`.3839## Use cases4041Use the CLI when the work belongs naturally in the terminal:4243- Generate local artifacts such as images or speech.44- Extract structured data into JSONL for later shell steps.45- Use Responses with files, computer use, and current web context in the cloud.46- Create projects and API keys with Admin APIs.4748Use it directly for one-off terminal requests, or from scripts when agents need repeatable batch work over files and generated artifacts.4950## CLI vs subagents for Codex5152Use the CLI for repeatable API work you want to inspect and rerun, such as batch extraction, file transforms, artifact generation, or deliberate model selection. Use subagents when the work still needs judgment, such as exploring code, comparing hypotheses, debugging, or reviewing changes.5354## Global flags5556These options work across commands:5758| Flag          | Use                                                                                                          |59| ------------- | ------------------------------------------------------------------------------------------------------------ |60| `--format`    | Print responses as `auto`, `json`, `jsonl`, `pretty`, `raw`, `yaml`, or `explore`.                           |61| `--transform` | Extract or reshape response data with a GJSON path before printing.                                          |62| `--debug`     | Print request and response details to stderr. Authorization is redacted; review headers before sharing logs. |6364This guide focuses on CLI patterns. For the latest arguments and response shapes for any API family, use the live [API reference](https://developers.openai.com/api/reference/overview).6566You can also change the base URL when you need to point the CLI at another compatible endpoint, such as a deployment that supports a different model set or only a subset of the API surface.6768## Responses6970Use Responses for text generation, structured extraction, web search, file understanding, and repeatable Codex-authored batch scripts.7172### Send your first request7374Command:7576```bash77openai responses create \78  --model gpt-6-astra \79  --input "Say hello in one sentence."80```818283Output:8485```json86{87  "id": "resp_...",88  "object": "response",89  "status": "completed",90  "model": "gpt-5.5-...",91  "output": [92    {93      "type": "message",94      "role": "assistant",95      "content": [96        {97          "type": "output_text",98          "text": "Hello!"99        }100      ]101    }102  ],103  "usage": {104    "input_tokens": 12,105    "output_tokens": 6,106    "total_tokens": 18107  },108  "...": "additional response fields omitted"109}110```111112The CLI prints the full API response object by default. Examples on this page keep representative fields such as `id`, `status`, `model`, `output`, and `usage`, and omit the rest.113114Responses output can include non-message items, such as reasoning items, before the assistant message. When you need assistant text, select the message item by type instead of assuming it is always `output[0]`:115116```bash117--transform 'output.#(type=="message").content.0.text'118```119120### Add a local file to the prompt121122For a simple local file, build the prompt inline with command substitution:123124```bash125openai responses create \126  --model gpt-6-astra \127  --input "Summarize this note in one sentence.128129<note>130$(cat ./note.md)131</note>" \132  --format yaml \133  --transform 'output.#(type=="message").content.0.text'134```135136137Output:138139```text140The note says the launch checklist is ready except for final support ownership.141```142143### Passing request bodies144145Use flags for short scalar inputs. Use a YAML heredoc for multiline prompts, tools, files, or nested request bodies. The heredoc can contain the same request fields you would otherwise pass as flags.146147Be careful with string values that look like YAML, especially prompts that contain `:` or `{}`. On flags, the generated parser may interpret those values as structured YAML instead of plain text. If a prompt starts looking like configuration, put it under `input: |` in a YAML body instead:148149Command:150151```bash152openai responses create \153  --format yaml \154  --transform 'output.#(type=="message").content.0.text' <<'YAML'155model: gpt-5.5156instructions: Return exactly one sentence.157max_output_tokens: 120158input: |159  Summarize this release note in one sentence.160161  <release_note>162  Fixed the image generation example and added CLI installation guidance.163  </release_note>164YAML165```166167168Output:169170```text171The release note updates the CLI docs with corrected image generation and installation guidance.172```173174When the prompt itself needs shell assembly, build a YAML body and pipe it into the command:175176```bash177{178  printf 'input: |\n'179  printf '  Summarize this note in one sentence.\n\n'180  printf '  <note>\n'181  sed 's/^/  /' ./note.md182  printf '  </note>\n'183} | openai responses create \184  --model gpt-6-astra \185  --format yaml \186  --transform 'output.#(type=="message").content.0.text'187```188189190### Write structured data to JSON191192Use structured outputs when downstream scripts need stable JSON. Save reusable schemas to disk:193194Save as `schema.json`:195196```json197{198  "type": "json_schema",199  "name": "fact",200  "strict": true,201  "schema": {202    "type": "object",203    "additionalProperties": false,204    "properties": {205      "person": { "type": "string" },206      "topic": { "type": "string" }207    },208    "required": ["person", "topic"]209  }210}211```212213Command:214215```bash216openai responses create \217  --model gpt-6-astra \218  --instructions "Extract the person and topic from the input." \219  --input "Ada Lovelace wrote notes about the Analytical Engine." \220  --text.format "$(cat ./schema.json)" \221  --format yaml \222  --transform 'output.#(type=="message").content.0.text'223```224225226Output:227228```json229{ "person": "Ada Lovelace", "topic": "notes about the Analytical Engine" }230```231232### Write structured records to JSONL233234When one input may produce many records, ask the model for an array and flatten it into JSONL so later shell steps can process one record per line:235236Save as `records-schema.json`:237238```json239{240  "type": "json_schema",241  "name": "items",242  "strict": true,243  "schema": {244    "type": "object",245    "additionalProperties": false,246    "properties": {247      "items": {248        "type": "array",249        "items": {250          "type": "object",251          "additionalProperties": false,252          "properties": {253            "title": { "type": "string" },254            "summary": { "type": "string" },255            "evidence": { "type": "string" }256          },257          "required": ["title", "summary", "evidence"]258        }259      }260    },261    "required": ["items"]262  }263}264```265266Command:267268```bash269: > records.jsonl270271for file in notes/*.md; do272  extracted="$(273    openai responses create \274      --model gpt-5.5 \275      --text.format "$(cat ./records-schema.json)" \276      --raw-output \277      --transform 'output.#(type=="message").content.0.text' <<YAML278input: |279  <note path="$file">280$(sed 's/^/  /' "$file")281  </note>282YAML283  )"284285  jq -r --arg source "$file" \286    '.items[]? + {source: $source} | @json' \287    <<<"$extracted" >> records.jsonl288done289```290291292This keeps the model response structured while producing one JSON object per line for later shell steps.293294### Web search295296Responses can call hosted tools from the same YAML request body:297298Command:299300```bash301openai responses create \302  --model gpt-6-astra \303  --format yaml \304  --transform 'output.#(type=="message").content.0.text' <<'YAML'305tools:306  - type: web_search307input: |308  Research the latest material news for AAPL.309  Return three concise bullets and cite sources in the text.310YAML311```312313314Output:315316```text317- Apple announced ...318- Analysts highlighted ...319- The company said ...320```321322### File inputs323324For uploaded files such as PDFs, create the file first, capture its ID, and pass it as `input_file.file_id`:325326Command:327328```bash329FILE_ID=$(330  openai files create \331    --file ./brief.pdf \332    --purpose user_data \333    --format yaml \334    --transform id335)336337openai responses create \338  --model gpt-5.5 \339  --format yaml \340  --transform 'output.#(type=="message").content.0.text' <<YAML341input:342  - role: user343    content:344      - type: input_text345        text: Summarize this brief and list three risks.346      - type: input_file347        file_id: ${FILE_ID}348YAML349```350351352Output:353354```text355- The brief proposes ...356- Risks: migration timing, unclear rollback criteria, and unresolved support ownership.357```358359Recent generated builds send local file flags as multipart file parts with filename and content type metadata. If a local upload command fails with an `UploadFile` type error, update the CLI and retry.360361## Images362363### Generate an image364365Generate an image, extract the base64 payload, and decode it into a normal asset file:366367Command:368369```bash370openai images generate \371  --model gpt-image-2 \372  --prompt "A simple product-style render of a translucent green cube on a neutral background." \373  --format yaml \374  --transform 'data.0.b64_json' | base64 --decode > hero.png375printf 'wrote hero.png\n'376```377378379Output:380381```text382wrote hero.png383```384385Current limitation: image commands do not yet have native `--output` support, so image generation still requires extracting `b64_json` and decoding it yourself.386387For `gpt-image-2`, omit `--input-fidelity`; image inputs are always processed at high fidelity. Transparent backgrounds are available in preview; use `--background transparent` with `png` (the default) or `webp`. `jpeg` isn't supported with transparent backgrounds. The model also supports broader `--size` values than earlier GPT Image models, as long as the requested resolution satisfies the Image API size constraints.388389### Edit an image390391Image editing uses the same base64 extraction pattern after the edit request succeeds:392393Command:394395```bash396openai images edit \397  --model gpt-image-2 \398  --image ./hero.png \399  --prompt "Turn the cube bright green." \400  --format yaml \401  --transform 'data.0.b64_json' | base64 --decode > hero-edited.png402printf 'wrote hero-edited.png\n'403```404405406Output:407408```text409wrote hero-edited.png410```411412If a local image edit upload fails with an `UploadFile` type error, update the CLI and retry.413414## Speech415416Create an MP3 locally with the speech API:417418Command:419420```bash421openai audio:speech create \422  --model gpt-4o-mini-tts \423  --voice marin \424  --input "The OpenAI CLI can call the API from ordinary shell scripts." \425  --output speech.mp3426```427428429Output:430431```text432Wrote output to: speech.mp3433```434435Play it with whatever local audio tool is available on your machine. On macOS:436437```bash438afplay speech.mp3439```440441Use `--instructions` to shape delivery and `--input` for the words that should be spoken. Instructions work well for cues such as pace, energy, warmth, formality, emphasis, or audience:442443```bash444openai audio:speech create \445  --model gpt-4o-mini-tts \446  --voice marin \447  --instructions "Whisper very quickly, like a hurried stage cue, while staying clear and intelligible." \448  --input "The launch checklist is ready. Please send final feedback by Friday at noon." \449  --output reminder.mp3450```451452453## Transcription454455Print plain transcript text for shell pipelines:456457Command:458459```bash460openai audio:transcriptions create \461  --model gpt-4o-transcribe \462  --file ./speech.mp3 \463  --transform text \464  --raw-output465```466467468Output:469470```text471The OpenAI CLI can call the API from ordinary shell scripts.472```473474Use the response format that matches the artifact you need:475476| Need                        | Command shape                                                        |477| --------------------------- | -------------------------------------------------------------------- |478| Plain transcript text       | `--model gpt-4o-transcribe --transform text --raw-output`            |479| Subtitle files              | `--model whisper-1 --response-format srt` or `--response-format vtt` |480| Segment or word timestamps  | `--model whisper-1 --response-format verbose_json`                   |481| Speaker-labeled diarization | `--model gpt-4o-transcribe-diarize --response-format diarized_json`  |482483For word-level timing, request the verbose transcription shape:484485Command:486487```bash488openai audio:transcriptions create \489  --model whisper-1 \490  --file ./speech.mp3 \491  --response-format verbose_json \492  --timestamp-granularity word \493  --format json494```495496497Output:498499```json500{501  "task": "transcribe",502  "language": "english",503  "duration": 6,504  "text": "The OpenAI CLI can call the API from ordinary shell scripts.",505  "words": [506    { "word": "The", "start": 0, "end": 0.42 },507    { "word": "OpenAI", "start": 0.42, "end": 1.22 }508  ],509  "...": "additional response fields omitted"510}511```512513For speaker-labeled output, use the diarization model and request `diarized_json`:514515Command:516517```bash518openai audio:transcriptions create \519  --model gpt-4o-transcribe-diarize \520  --file ./speech.mp3 \521  --response-format diarized_json \522  --format json523```524525526Output:527528```json529{530  "text": "The OpenAI CLI can call the API from ordinary shell scripts.",531  "segments": [532    {533      "type": "transcript.text.segment",534      "id": "seg_0",535      "start": 0.05,536      "end": 5.25,537      "text": " The OpenAI CLI can call the API from ordinary shell scripts.",538      "speaker": "A"539    }540  ],541  "...": "additional response fields omitted"542}543```544545`whisper-1` supports `json`, `text`, `srt`, `verbose_json`, and `vtt`. `diarized_json` is the format that carries `segments[].speaker`; with the same diarization model and plain `json`, the response contains transcript text but not speaker labels.546547## Admin APIs548549Use Admin APIs for organization management, credential provisioning, compliance, and usage-monitoring workflows. Set `OPENAI_ADMIN_KEY`, then call the generated `admin:organization:*` commands.550551To provision a new machine credential, [create a project](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/projects/methods/create), [create a service account](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/projects/subresources/service_accounts/methods/create) inside that project, and use the returned API key.552553### Create a project, service account, and API key554555Creating a service account in that project returns an unredacted API key for the service account.556557Command:558559```bash560# Create the project that will own this app or agent and save the response.561openai admin:organization:projects create \562  --name "automation project" \563  --format json > project.json564PROJECT_ID="$(jq -r '.id' project.json)"565566# Create a service account inside the project and save the full response.567openai admin:organization:projects:service-accounts create \568  --project-id "$PROJECT_ID" \569  --name "automation bot" \570  --format json > service-account.json571572# Extract the returned API key into an env file for the workload to use.573jq -r '.api_key.value | "OPENAI_API_KEY=\(.)"' \574  service-account.json > .env575```576577578Output:579580```json581{582  "object": "organization.project.service_account",583  "id": "svc_acct_...",584  "name": "automation bot",585  "role": "member",586  "api_key": {587    "id": "key_...",588    "value": "sk-..."589  }590}591```592593This writes the project response to `project.json`, parses its ID into the next command, writes the service-account response to `service-account.json`, and writes the returned credential to `.env` as `OPENAI_API_KEY=...`. Treat both JSON files as secrets, and add `project.json`, `service-account.json`, and `.env` to `.gitignore` before using this pattern in a repository.594595For the rest of the surface, see the [Admin APIs guide](https://developers.openai.com/api/docs/guides/admin-apis) and the current [Administration API reference](https://developers.openai.com/api/reference/administration/overview). Be careful about giving unvetted actors access to admin keys.
Files main
Menu

Theme