跳转到内容

无头模式

无头模式允许您从命令行脚本和自动化工具中以编程方式运行 Gemini CLI,而无需任何交互式 UI。这对于脚本编写、自动化、CI/CD 管道以及构建人工智能驱动的工具非常理想。

无头模式为 Gemini CLI 提供了一个无头接口,它:

  • 通过命令行参数或标准输入接受提示
  • 返回结构化输出(文本或 JSON)
  • 支持文件重定向和管道传输
  • 启用自动化和脚本工作流
  • 为错误处理提供一致的退出代码

使用 --prompt(或 -p)标志以无头模式运行:

从您的终端将输入传递给 Gemini CLI:

Terminal window
echo "Explain this code" | gemini

从文件读取并使用 Gemini 进行处理:

Terminal window
cat README.md | gemini --prompt "Summarize this documentation"

标准的人类可读输出:

Terminal window
gemini -p "What is the capital of France?"

响应格式:

The capital of France is Paris.

返回包括响应、统计信息和元数据在内的结构化数据。这种格式非常适合编程处理和自动化脚本。

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
}
}
Terminal window
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(JSONL)实时返回事件。每个重要动作(初始化、消息、工具调用、结果)在其发生时立即发出。这种格式非常适合监控长时间运行的操作、构建实时进度显示的 UI 以及创建对事件做出反应的自动化管道。

当您需要:

  • 实时进度监控 - 观察工具调用和响应的发生
  • 事件驱动自动化 - 对特定事件做出反应(例如,工具故障)
  • 实时 UI 更新 - 构建实时显示 AI 代理活动的界面
  • 详细的执行日志 - 捕获带时间戳的完整交互历史
  • 管道集成 - 将事件流式传输到日志/监控系统

流式格式发出以下 6 种事件类型:

  1. init - 会话开始(包括 session_id、模型)
  2. message - 用户提示和助手响应
  3. tool_use - 带参数的工具调用请求
  4. tool_result - 工具执行结果(成功/错误)
  5. error - 非致命错误和警告
  6. result - 最终会话结果及汇总统计
Terminal window
# 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"}

将输出保存到文件或管道传输到其他命令:

Terminal window
# 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指定输出格式(文本,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

有关所有可用配置选项、设置文件和环境变量的完整详细信息,请参阅配置指南

Terminal window
cat src/auth.py | gemini -p "Review this authentication code for security issues" > security-review.txt
Terminal window
result=$(git diff --cached | gemini -p "Write a concise commit message for these changes" --output-format json)
echo "$result" | jq -r '.response'
Terminal window
result=$(cat api/routes.js | gemini -p "Generate OpenAPI spec for these routes" --output-format json)
echo "$result" | jq -r '.response' > openapi.json
Terminal window
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
Terminal window
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
Terminal window
grep "ERROR" /var/log/app.log | tail -20 | gemini -p "Analyze these errors and suggest root cause and fixes" > error-analysis.txt
Terminal window
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
Terminal window
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