OpenAI CLI
OpenAI CLI
터미널에서 바로 OpenAI API를 호출할 수 있는 openai 커맨드라인 도구를 다뤄요. 셸 스크립트와 자연스럽게 붙어서 쓰기 좋아요.
출처: 문서
본문
설치
Homebrew로 설치:
brew install openai/tools/openai
또는 Go 1.25 이상이 있다면 Go로 설치:
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 키가 없다면 대시보드에서 만드세요. Admin API 엔드포인트에는 OPENAI_ADMIN_KEY를 설정해요. SDK 레이어가 호출하는 엔드포인트에 따라 admin 키나 기본 API 키를 골라 써요. 다른 API 호스트를 가리키려면 OPENAI_BASE_URL을 설정하면 돼요.
활용 사례
작업이 터미널에 자연스럽게 맞다면 CLI를 써요.
- 이미지나 음성 같은 로컬 산출물 생성
- 이후 셸 단계를 위해 구조화된 데이터를 JSONL로 추출
- 파일, 컴퓨터 사용, 최신 웹 컨텍스트를 활용한 Responses 사용
- Admin API로 프로젝트·API 키 생성
일회성 요청에는 직접, 파일과 생성 산출물을 반복 처리해야 하는 에이전트에는 스크립트에서 사용하면 돼요.
Codex에서 CLI vs 서브에이전트
배치 추출, 파일 변환, 산출물 생성, 의도적 모델 선택처럼 다시 실행하며 검토하고 싶은 반복 API 작업에는 CLI가 좋아요. 코드 탐색, 가설 비교, 디버깅, 변경 검토처럼 여전히 판단이 필요한 작업에는 서브에이전트를 써요.
전역 플래그
여러 명령에서 공통으로 쓰는 옵션이에요.
| Flag | 용도 |
|---|---|
--format |
응답을 auto, json, jsonl, pretty, raw, yaml, explore 중 하나로 출력 |
--transform |
출력 전에 GJSON 경로로 응답 데이터 추출·재구성 |
--debug |
요청·응답 상세를 stderr로 출력. 인증 정보는 가려지고, 로그 공유 전에 헤더를 검토하세요. |
이 가이드는 CLI 패턴에 집중해요. 어떤 API 패밀리의 최신 인자와 응답 형태는 라이브 API reference를 참고하세요. 다른 호환 엔드포인트(다른 모델 세트를 지원하거나 API 일부만 제공하는 배포 등)를 가리킬 때는 base URL도 바꿀 수 있어요.
Responses
텍스트 생성, 구조화 추출, 웹 검색, 파일 이해, 반복적인 Codex 작성 배치 스크립트에 Responses를 써요.
첫 요청 보내기:
openai responses create \
--model gpt-6-astra \
--input "Say hello in one sentence."
CLI는 기본적으로 전체 API 응답 객체를 출력해요. 이 페이지 예시는 id, status, model, output, usage 같은 대표 필드만 남겨두고 나머지를 생략해요. Responses 출력에는 어시스턴트 메시지 앞에 reasoning 항목 같은 비메시지 항목이 섞일 수 있어요. 어시스턴트 텍스트가 필요하면 항상 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'
요청 바디 전달하기: 짧은 스칼라 입력은 플래그로, 여러 줄 프롬프트·도구·파일·중첩 요청 바디는 YAML 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
프롬프트 자체를 셸에서 조립해야 한다면 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을 필요로 하면 구조화 출력(structured outputs)을 써요. 재사용할 스키마는 디스크에 저장해 두면 좋아요. (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'
구조화 레코드를 JSONL로 쓰기: 입력 하나가 여러 레코드를 만들 수 있을 때는 배열을 만들어 JSONL로 평탄화하면 셸 단계에서 한 줄에 레코드 하나씩 처리할 수 있어요. (records-schema.json)
: > 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
웹 검색: 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
파일 입력: 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
최근 생성된 빌드에서는 로컬 파일 플래그가 파일명·콘텐츠 타입 메타데이터를 포함한 multipart 파일로 전송돼요. 로컬 업로드 명령이 UploadFile 타입 오류로 실패하면 CLI를 업데이트하고 다시 시도하세요.
이미지
이미지 생성:
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'
현재 제한: 이미지 명령에는 아직 --output 지원이 없어서 b64_json을 직접 추출해 디코딩해야 해요. gpt-image-2는 --input-fidelity를 생략하고, 이미지 입력은 항상 high fidelity로 처리돼요. 투명 배경은 프리뷰에서 지원하며 --background transparent를 png(기본값)나 webp와 함께 써요. jpeg는 투명 배경을 지원하지 않아요. 이 모델은 Image API 크기 제약만 충족하면 이전 GPT Image 모델보다 더 넓은 --size 값을 지원해요.
이미지 편집:
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'
로컬 이미지 편집 업로드가 UploadFile 타입 오류로 실패하면 CLI를 업데이트하고 다시 시도하세요.
음성
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
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
필요한 산출물에 맞는 응답 형식을 골라요.
| 필요한 것 | 명령 형태 |
|---|---|
| 평문 전사 텍스트 | --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 |
단어 단위 타임스탬프가 필요하면 verbose 전사 형태를 요청해요.
openai audio:transcriptions create \
--model whisper-1 \
--file ./speech.mp3 \
--response-format verbose_json \
--timestamp-granularity word \
--format json
화자 라벨 출력은 다이어라이제이션 모델로 diarized_json을 요청해요.
openai audio:transcriptions create \
--model gpt-4o-transcribe-diarize \
--file ./speech.mp3 \
--response-format diarized_json \
--format json
whisper-1은 json, text, srt, verbose_json, vtt를 지원해요. diarized_json이 segments[].speaker를 담는 형식이에요. 같은 다이어라이제이션 모델로 일반 json을 요청하면 전사 텍스트는 있지만 화자 라벨은 빠져요.
Admin API
조직 관리, 자격증명 프로비저닝, 컴플라이언스, 사용량 모니터링 워크플로에 Admin API를 써요. OPENAI_ADMIN_KEY를 설정한 뒤 생성된 admin:organization:* 명령을 호출해요.
새 머신 자격증명을 프로비저닝하려면 프로젝트를 만들고, 그 프로젝트 안에 서비스 계정을 만든 뒤 반환된 API 키를 사용해요.
프로젝트·서비스 계정·API 키 만들기:
# 이 앱·에이전트를 소유할 프로젝트를 만들고 응답을 저장합니다.
openai admin:organization:projects create \
--name "automation project" \
--format json > project.json
PROJECT_ID="$(jq -r '.id' project.json)"
# 프로젝트 안에 서비스 계정을 만들고 전체 응답을 저장합니다.
openai admin:organization:projects:service-accounts create \
--project-id "$PROJECT_ID" \
--name "automation bot" \
--format json > service-account.json
# 반환된 API 키를 워크로드가 쓸 env 파일로 추출합니다.
jq -r '.api_key.value | "OPENAI_API_KEY=\\(.)"' \
service-account.json > .env
이 패턴은 프로젝트 응답을 project.json에, ID를 다음 명령에 넘기고, 서비스 계정 응답을 service-account.json에, 자격증명을 .env에 OPENAI_API_KEY=...로 써요. 두 JSON 파일 모두 비밀로 취급하고, 저장소에서 이 패턴을 쓰기 전에 project.json, service-account.json, .env를 .gitignore에 추가하세요.
나머지 표면은 Admin APIs 가이드와 현재 Administration API reference를 참고해요. 검증되지 않은 사람에게 admin 키 접근을 주는 일은 신중해야 해요.
더 알아보기 (Learn more)
CLI는 반복적인 셸 워크플로에 특히 좋아요. SDK 사용이 더 익숙하다면 SDK 및 CLI 개요를 참고하세요. 공식 저장소는 openai/openai-cli에서 확인할 수 있어요.