헤드리스 모드
헤드리스 모드를 사용하면 대화형 UI 없이 명령줄 스크립트 및 자동화 도구에서 프로그래밍 방식으로 Gemini CLI를 실행할 수 있습니다. 이는 스크립팅, 자동화, CI/CD 파이프라인 및 AI 기반 도구 구축에 이상적입니다.
개요
헤드리스 모드는 다음과 같은 Gemini CLI에 대한 헤드리스 인터페이스를 제공합니다:
- 명령줄 인수 또는 stdin을 통해 프롬프트를 받습니다.
- 구조화된 출력(텍스트 또는 JSON)을 반환합니다.
- 파일 리디렉션 및 파이핑을 지원합니다.
- 자동화 및 스크립팅 워크플로를 활성화합니다.
- 오류 처리를 위한 일관된 종료 코드를 제공합니다.
기본 사용법
직접 프롬프트
--prompt (또는 -p) 플래그를 사용하여 헤드리스 모드로 실행합니다:
gemini --prompt "What is machine learning?"Stdin 입력
터미널에서 Gemini CLI로 입력을 파이프합니다:
echo "Explain this code" | gemini파일 입력과 결합
파일에서 읽고 Gemini로 처리합니다:
cat README.md | gemini --prompt "Summarize this documentation"출력 형식
텍스트 출력 (기본값)
표준 사람이 읽을 수 있는 출력:
gemini -p "What is the capital of France?"응답 형식:
The capital of France is Paris.JSON 출력
응답, 통계 및 메타데이터를 포함한 구조화된 데이터를 반환합니다. 이 형식은 프로그래밍 방식 처리 및 자동화 스크립트에 이상적입니다.
응답 스키마
JSON 출력은 다음의 상위 수준 구조를 따릅니다:
{
"response": "string", // The main AI-generated content answering your prompt
"stats": {
// Usage metrics and performance data
"models": {
// Per-model API and token usage statistics
"[model-name]": {
"api": {
/* request counts, errors, latency */
},
"tokens": {
/* prompt, response, cached, total counts */
}
}
},
"tools": {
// Tool execution statistics
"totalCalls": "number",
"totalSuccess": "number",
"totalFail": "number",
"totalDurationMs": "number",
"totalDecisions": {
/* accept, reject, modify, auto_accept counts */
},
"byName": {
/* per-tool detailed stats */
}
},
"files": {
// File modification statistics
"totalLinesAdded": "number",
"totalLinesRemoved": "number"
}
},
"error": {
// Present only when an error occurred
"type": "string", // Error type (e.g., "ApiError", "AuthError")
"message": "string", // Human-readable error description
"code": "number" // Optional error code
}
}사용 예시
gemini -p "What is the capital of France?" --output-format json응답:
{
"response": "The capital of France is Paris.",
"stats": {
"models": {
"gemini-2.5-pro": {
"api": {
"totalRequests": 2,
"totalErrors": 0,
"totalLatencyMs": 5053
},
"tokens": {
"prompt": 24939,
"candidates": 20,
"total": 25113,
"cached": 21263,
"thoughts": 154,
"tool": 0
}
},
"gemini-2.5-flash": {
"api": {
"totalRequests": 1,
"totalErrors": 0,
"totalLatencyMs": 1879
},
"tokens": {
"prompt": 8965,
"candidates": 10,
"total": 9033,
"cached": 0,
"thoughts": 30,
"tool": 28
}
}
},
"tools": {
"totalCalls": 1,
"totalSuccess": 1,
"totalFail": 0,
"totalDurationMs": 1881,
"totalDecisions": {
"accept": 0,
"reject": 0,
"modify": 0,
"auto_accept": 1
},
"byName": {
"google_web_search": {
"count": 1,
"success": 1,
"fail": 0,
"durationMs": 1881,
"decisions": {
"accept": 0,
"reject": 0,
"modify": 0,
"auto_accept": 1
}
}
}
},
"files": {
"totalLinesAdded": 0,
"totalLinesRemoved": 0
}
}
}스트리밍 JSON 출력
실시간 이벤트를 줄바꿈으로 구분된 JSON(JSONL)으로 반환합니다. 각 중요한 작업(초기화, 메시지, 도구 호출, 결과)은 발생 즉시 방출됩니다. 이 형식은 장기 실행 작업을 모니터링하고, 실시간 진행 상황을 보여주는 UI를 구축하고, 이벤트에 반응하는 자동화 파이프라인을 만드는 데 이상적입니다.
스트리밍 JSON을 사용하는 경우
--output-format stream-json은 다음과 같은 경우에 사용하세요:
- 실시간 진행 상황 모니터링 - 도구 호출 및 응답이 발생하는 즉시 확인
- 이벤트 기반 자동화 - 특정 이벤트(예: 도구 실패)에 반응
- 실시간 UI 업데이트 - AI 에이전트 활동을 실시간으로 보여주는 인터페이스 구축
- 상세 실행 로그 - 타임스탬프와 함께 완전한 상호 작용 기록 캡처
- 파이프라인 통합 - 로깅/모니터링 시스템으로 이벤트 스트리밍
이벤트 유형
스트리밍 형식은 6가지 이벤트 유형을 방출합니다:
init- 세션 시작 (session_id, 모델 포함)message- 사용자 프롬프트 및 어시스턴트 응답tool_use- 매개변수가 포함된 도구 호출 요청tool_result- 도구 실행 결과 (성공/오류)error- 치명적이지 않은 오류 및 경고result- 집계된 통계가 포함된 최종 세션 결과
기본 사용법
# Stream events to console
gemini --output-format stream-json --prompt "What is 2+2?"
# Save event stream to file
gemini --output-format stream-json --prompt "Analyze this code" > events.jsonl
# Parse with jq
gemini --output-format stream-json --prompt "List files" | jq -r '.type'출력 예시
각 줄은 완전한 JSON 이벤트입니다:
{"type":"init","timestamp":"2025-10-10T12:00:00.000Z","session_id":"abc123","model":"gemini-2.0-flash-exp"}
{"type":"message","role":"user","content":"List files in current directory","timestamp":"2025-10-10T12:00:01.000Z"}
{"type":"tool_use","tool_name":"Bash","tool_id":"bash-123","parameters":{"command":"ls -la"},"timestamp":"2025-10-10T12:00:02.000Z"}
{"type":"tool_result","tool_id":"bash-123","status":"success","output":"file1.txt\nfile2.txt","timestamp":"2025-10-10T12:00:03.000Z"}
{"type":"message","role":"assistant","content":"Here are the files...","delta":true,"timestamp":"2025-10-10T12:00:04.000Z"}
{"type":"result","status":"success","stats":{"total_tokens":250,"input_tokens":50,"output_tokens":200,"duration_ms":3000,"tool_calls":1},"timestamp":"2025-10-10T12:00:05.000Z"}파일 리디렉션
출력을 파일에 저장하거나 다른 명령으로 파이프합니다:
# Save to file
gemini -p "Explain Docker" > docker-explanation.txt
gemini -p "Explain Docker" --output-format json > docker-explanation.json
# Append to file
gemini -p "Add more details" >> docker-explanation.txt
# Pipe to other tools
gemini -p "What is Kubernetes?" --output-format json | jq '.response'
gemini -p "Explain microservices" | wc -w
gemini -p "List programming languages" | grep -i "python"구성 옵션
헤드리스 사용을 위한 주요 명령줄 옵션:
| 옵션 | 설명 | 예시 |
|---|---|---|
--prompt, -p | 헤드리스 모드에서 실행 | gemini -p "query" |
--output-format | 출력 형식 지정 (text, json) | gemini -p "query" --output-format json |
--model, -m | Gemini 모델 지정 | gemini -p "query" -m gemini-2.5-flash |
--debug, -d | 디버그 모드 활성화 | gemini -p "query" --debug |
--include-directories | 추가 디렉터리 포함 | gemini -p "query" --include-directories src,docs |
--yolo, -y | 모든 작업 자동 수락 | gemini -p "query" --yolo |
--approval-mode | 승인 모드 설정 | gemini -p "query" --approval-mode auto_edit |
사용 가능한 모든 구성 옵션, 설정 파일 및 환경 변수에 대한 전체 세부 정보는 구성 가이드를 참조하세요.
예시
코드 리뷰
cat src/auth.py | gemini -p "Review this authentication code for security issues" > security-review.txt커밋 메시지 생성
result=$(git diff --cached | gemini -p "Write a concise commit message for these changes" --output-format json)
echo "$result" | jq -r '.response'API 문서화
result=$(cat api/routes.js | gemini -p "Generate OpenAPI spec for these routes" --output-format json)
echo "$result" | jq -r '.response' > openapi.json일괄 코드 분석
for file in src/*.py; do
echo "Analyzing $file..."
result=$(cat "$file" | gemini -p "Find potential bugs and suggest improvements" --output-format json)
echo "$result" | jq -r '.response' > "reports/$(basename "$file").analysis"
echo "Completed analysis for $(basename "$file")" >> reports/progress.log
done코드 리뷰
result=$(git diff origin/main...HEAD | gemini -p "Review these changes for bugs, security issues, and code quality" --output-format json)
echo "$result" | jq -r '.response' > pr-review.json로그 분석
grep "ERROR" /var/log/app.log | tail -20 | gemini -p "Analyze these errors and suggest root cause and fixes" > error-analysis.txt릴리스 노트 생성
result=$(git log --oneline v1.0.0..HEAD | gemini -p "Generate release notes from these commits" --output-format json)
response=$(echo "$result" | jq -r '.response')
echo "$response"
echo "$response" >> CHANGELOG.md모델 및 도구 사용 추적
result=$(gemini -p "Explain this database schema" --include-directories db --output-format json)
total_tokens=$(echo "$result" | jq -r '.stats.models // {} | to_entries | map(.value.tokens.total) | add // 0')
models_used=$(echo "$result" | jq -r '.stats.models // {} | keys | join(", ") | if . == "" then "none" else . end')
tool_calls=$(echo "$result" | jq -r '.stats.tools.totalCalls // 0')
tools_used=$(echo "$result" | jq -r '.stats.tools.byName // {} | keys | join(", ") | if . == "" then "none" else . end')
echo "$(date): $total_tokens tokens, $tool_calls tool calls ($tools_used) used with models: $models_used" >> usage.log
echo "$result" | jq -r '.response' > schema-docs.md
echo "Recent usage trends:"
tail -5 usage.log