For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
기본 탐색 메뉴
Theme

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를 처음 설치하는 경우에는 이 문제가 발생하지 않습니다.

명령어 탐색하기

API 키를 설정하기 전에도 터미널에서 openai explore를 실행해 명령어를 찾아볼 수 있습니다. 수행할 작업을 입력하세요. 예를 들어 count tokens offline을 입력하면 openai tokenizer count를 찾을 수 있습니다. 방향키로 원하는 검색 결과에 커서를 옮기세요. Enter를 누르면 해당 명령어가 선택되고 Escape를 누르면 선택이 취소됩니다.

탐색 화면에서는 선택한 명령어를 실행하지 않고 표시만 합니다. 셸 연동을 사용하면 셸 프롬프트에서 선택한 명령어를 수정할 수 있습니다. 지원되는 셸과 단축키를 확인하려면 openai explore --help를 실행하세요.

인증

CLI는 OPENAI_API_KEY에서 API 키를 읽습니다.

명령어:

export OPENAI_API_KEY="sk-..."

아직 API 키가 없다면 대시보드에서 API 키를 생성하세요.

Admin API 엔드포인트를 호출할 때는 OPENAI_ADMIN_KEY를 대신 설정하세요. SDK 계층에서 호출할 엔드포인트에 따라 관리자 키 또는 기본 API 키를 선택합니다.

다른 API 호스트에 연결하려면 OPENAI_BASE_URL을 설정하세요.

활용 사례

다음과 같이 터미널에서 처리하기 좋은 작업에 CLI를 사용하세요.

  • 이미지나 음성 파일 등의 결과물을 로컬에 생성합니다.
  • 구조화된 데이터를 JSONL로 추출해 후속 셸 작업에서 처리합니다.
  • 클라우드에서 Responses로 파일, 컴퓨터 사용 기능, 최신 웹 컨텍스트를 활용합니다.
  • Admin API로 프로젝트와 API 키를 생성합니다.

일회성 요청은 터미널에서 CLI로 직접 실행하세요. 에이전트가 파일과 생성된 결과물을 대상으로 일괄 작업을 반복해야 한다면 스크립트에서 CLI를 호출하세요.

Codex에서 CLI와 하위 에이전트 선택하기

데이터 일괄 추출, 파일 변환, 결과물 생성처럼 실행 내용을 확인하고 다시 실행할 API 작업이나 모델을 직접 지정할 작업에는 CLI를 사용하세요. 코드 탐색, 가설 비교, 디버깅, 변경 사항 검토처럼 작업 과정에서 판단이 필요할 때는 하위 에이전트를 사용하세요.

전역 플래그

다음 옵션은 여러 명령어에서 공통으로 사용할 수 있습니다.

플래그 용도
--format 응답을 auto, json, jsonl, pretty, raw, yaml, explore 중 하나의 형식으로 출력합니다.
--transform 출력 전에 GJSON 경로를 사용해 응답 데이터를 추출하거나 구조를 변경합니다.
--debug 요청과 응답의 세부 정보를 stderr로 출력합니다. Authorization 헤더 값은 가려집니다. 로그를 공유하기 전에 헤더를 확인하세요.

이 가이드에서는 CLI 사용 방법을 중심으로 설명합니다. 각 API의 최신 인수와 응답 구조는 API 레퍼런스에서 확인하세요.

CLI를 다른 호환 엔드포인트에 연결해야 할 때는 기본 URL도 변경할 수 있습니다. 예를 들어 지원하는 모델 구성이 다르거나 API 기능 중 일부만 지원하는 배포 환경에 연결할 때 사용합니다.

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 히어 도큐먼트를 사용하세요. 플래그로 전달할 수 있는 요청 필드는 히어 도큐먼트에도 그대로 넣을 수 있습니다.

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로 저장하기

입력 하나에서 여러 레코드가 나올 수 있다면 모델에 배열을 요청하고 각 요소를 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

이렇게 하면 모델 응답의 구조를 유지하면서 후속 셸 작업에 사용할 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처럼 업로드해서 사용할 파일은 먼저 API에 파일을 생성한 다음 반환된 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 모델은 사용 중단 예정(deprecated)이며 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

음성 전사

셸 파이프라인에서 사용할 전사 결과를 일반 텍스트로 출력하세요.

명령어:

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는 사용 중단 예정(deprecated)이며 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 레퍼런스를 참고하세요. 신뢰성을 확인하지 않은 사용자나 시스템에 관리자 키 접근 권한을 부여할 때는 주의하세요.