gemini-api-cli
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseThe CLI exposes every Gemini API resource as a shell subcommand. Compared to : media and transcription commands decode output to disk and print only the file path, attaches local files or URIs, extracts fields in-process (raw strings by default, no external ), previews redacted HTTP requests offline, and list endpoints auto-paginate with (cap pages with ; sets server page size).
gemini-apicurl-ifiles/<id>--jqjq--dry-run--all--max-pages N--page-sizegemini-apicurl-ifiles/<id>--jqjq--dry-run--all--max-pages N--page-sizeCLI vs SDK
CLI 与 SDK
CLI for shell work, SDK for application code. Use from terminals, scripts, and CI jobs to generate media files, analyze local PDFs or recordings, run Deep Research, and manage agent sandboxes ( is a stateless Gemini API client, distinct from the interactive coding agent). Use the Google GenAI SDKs (, ) when calls live inside application source or need bidirectional Live API WebSockets.
gemini-apigemini-api@google/gemini-cligemini-api-devgemini-live-api-dev用于 shell 操作的 CLI,用于应用代码的 SDK。 在终端、脚本和 CI 作业中使用 ,可生成媒体文件、分析本地 PDF 或录音、执行 Deep Research,并管理 Agent 沙箱( 是无状态的 Gemini API 客户端,不同于交互式 编程 Agent)。当调用位于应用程序源代码内部,或需要双向 Live API WebSockets 时,请使用 Google GenAI SDK(、)。
gemini-apigemini-api@google/gemini-cligemini-api-devgemini-live-api-devInstall and auth
安装与身份验证
sh
undefinedsh
undefinedmacOS / Linux (set GEMINI_VERSION=<tag> to pin a release)
macOS / Linux(设置 GEMINI_VERSION=<tag> 可固定版本)
curl -fsSL https://raw.githubusercontent.com/google-gemini/gemini-api-cli/main/scripts/install.sh | bash
Credentials resolve in order (first match wins): `--api-key` / `--access-token` flags, `GEMINI_API_KEY` / `GEMINI_ACCESS_TOKEN` env vars, the OS keychain, then `~/.config/gemini-api/config.yaml`.
- Env var (agents and CI): `export GEMINI_API_KEY="..."`
- Workstation key: `gemini-api configure --api-key "..."` saves to the OS keychain. Pass `--no-keyring` or `GEMINI_NO_KEYRING=1` on headless Linux to use `config.yaml`; `gemini-api auth logout` clears stored keys.
- Active auth check: `gemini-api whoami` (add `-o json` for JSON) prints masked credentials and the winning source.
> **The #1 auth trap:** an exported `GEMINI_API_KEY` overrides credentials stored in the keychain or `config.yaml`, billing whichever project that env var belongs to. Check `gemini-api whoami` to see which source won, or run `env -u GEMINI_API_KEY gemini-api ...` to ignore the env var.curl -fsSL https://raw.githubusercontent.com/google-gemini/gemini-api-cli/main/scripts/install.sh | bash
凭据按以下顺序解析(匹配到第一个即停止):`--api-key` / `--access-token` 标志、`GEMINI_API_KEY` / `GEMINI_ACCESS_TOKEN` 环境变量、OS 密钥链,最后是 `~/.config/gemini-api/config.yaml`。
- 环境变量(Agent 和 CI):`export GEMINI_API_KEY="..."`
- 工作站密钥:`gemini-api configure --api-key "..."` 会将密钥保存到 OS 密钥链。在无头 Linux 上传入 `--no-keyring` 或设置 `GEMINI_NO_KEYRING=1`,即可使用 `config.yaml`;`gemini-api auth logout` 会清除已存储的密钥。
- 当前身份验证检查:`gemini-api whoami`(添加 `-o json` 可获得 JSON)会打印经过掩码的凭据和最终生效的来源。
> **首要的身份验证陷阱:** 已导出的 `GEMINI_API_KEY` 会覆盖密钥链或 `config.yaml` 中存储的凭据,并为该环境变量所属的项目计费。运行 `gemini-api whoami` 查看哪个来源生效,或运行 `env -u GEMINI_API_KEY gemini-api ...` 忽略该环境变量。Command structure
命令结构
text
gemini-api <intent> [prompt] [flags] # task commands with model and modality presets
gemini-api <resource> <action> [flags] # REST resource groupsRun to list commands, or for flags and examples ( dumps a 45 KB KDL spec, so stick to to save context).
gemini-api --help<subcommand> --help--usage--help| Command | Key flags / actions | Default model & behavior |
|---|---|---|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | Runs models or managed agents; manages custom agent definitions |
| | Uploads reusable |
| (bare), | Bare |
| | Remote sandboxes and workspace snapshots ( |
Model selection: use (default), (hard reasoning and coding), or (high throughput); for images, , , or . Avoid deprecated , , and models.
gemini-3.8-flashgemini-4-argongemini-3.5-flash-litegemini-nano-banana-2.1gemini-3.1-flash-lite-imagegemini-3-pro-imagegemini-2.5-*gemini-2.0-*gemini-1.5-*text
gemini-api <intent> [prompt] [flags] # 带模型和模态预设的任务命令
gemini-api <resource> <action> [flags] # REST 资源组运行 可列出命令,或使用 查看标志和示例( 会输出 45 KB 的 KDL 规范,因此为节省上下文请使用 )。
gemini-api --help<subcommand> --help--usage--help| 命令 | 主要标志/操作 | 默认模型与行为 |
|---|---|---|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | 运行模型或托管 Agent;管理自定义 Agent 定义 |
| | 上传可复用的 |
| 不带子命令、 | 不带子命令的 |
| | 远程沙箱和工作区快照(Agent 基础设施的 |
模型选择: 使用 (默认)、(复杂推理与编程)或 (高吞吐量);图像使用 、 或 。避免使用已弃用的 、 和 模型。
gemini-3.8-flashgemini-4-argongemini-3.5-flash-litegemini-nano-banana-2.1gemini-3.1-flash-lite-imagegemini-3-pro-imagegemini-2.5-*gemini-2.0-*gemini-1.5-*Global flags
全局标志
| Flag | Purpose |
|---|---|
| |
| Filter JSON output with a built-in jq expression ( |
| Compact TOON on stdout and structured JSON errors on stderr |
| Disable prompts, TUI forms, and |
| Validate inputs and preview redacted HTTP requests offline ( |
| Log HTTP request and response details to stderr |
Exit codes: 0 ok, 1 runtime or API error (including failed or incomplete runs), 2 usage or validation error, 3 auth error. See for , pagination, and auth flags.
gemini-api --help-global--server-url| 标志 | 用途 |
|---|---|
| |
| 使用内置 jq 表达式筛选 JSON 输出( |
| 在 stdout 输出紧凑 TOON,在 stderr 输出结构化 JSON 错误 |
| 禁用提示、TUI 表单和 |
| 离线验证输入并预览已脱敏的 HTTP 请求( |
| 将 HTTP 请求和响应详情记录到 stderr |
退出码:0 表示成功,1 表示运行时或 API 错误(包括失败或未完成的运行),2 表示用法或验证错误,3 表示身份验证错误。有关 、分页和身份验证标志,请参阅 。
--server-urlgemini-api --help-globalOutput
输出
Media (, , , ) and write files locally and print only the file path on stdout. Adding still writes the file and prints .
imagettsmusicvideotranscribe-o json{path, mime_type, size_bytes, response_id, status}Streaming and JSON shape: and stream plain reply text by default, so alone emits NDJSON events. Pass for one JSON object (bare prints metadata YAML, and or disables streaming automatically). Reply text lives under (see below) rather than . On paginated commands, runs per page envelope (, ).
generateagent run-o json--stream=false -o json{id, status, steps, usage}--stream=false--jq--background.steps[]model_outputagent status.candidates[]list--jq.models[]?.name.agents[]?.id媒体命令(、、、)和 会在本地写入文件,并仅在 stdout 打印文件路径。即使添加 ,仍会写入文件,并打印 。
imagettsmusicvideotranscribe-o json{path, mime_type, size_bytes, response_id, status}流式传输与 JSON 结构: 和 默认以流式形式输出纯回复文本,因此仅使用 会发出 NDJSON 事件。传入 可获得一个 JSON 对象 (仅使用 会打印元数据 YAML,而 或 会自动禁用流式传输)。回复文本位于 的 下(参见下文 ),而不是 。在分页的 命令中, 会针对每个页面封装结构运行(、)。
generateagent run-o json--stream=false -o json{id, status, steps, usage}--stream=false--jq--background.steps[]model_outputagent status.candidates[]list--jq.models[]?.name.agents[]?.idInput
输入
- /
-iattaches media and documents on--input,generate,image,video,analyze, andtranscribe(repeatable). Accepts local paths up to ~14 MB (20 MB base64 cap),agent runURIs, or YouTube URLs. Upload larger or reused files once withfiles/<id>.gemini-api files upload <path> --wait - /
-freads prompt text from a file on--fileandtts. Piped text needsmusic: when piping plain text into--stdin,generate,image, orvideo, passanalyzeor piped input gets parsed as a JSON--stdin.--body - passes raw Gemini API JSON inline, from
--body, or via@file.json(merges with flags; exits 2 on duplicate keys). Use it for@-schemas,response_format(tools,google_search,code_execution, function declarations),url_context,generation_config, orenvironment.store - Don't dump raw: it prints ~91 KB of minified JSON and exits before
--schemaruns. Pipe it to--jq:jqshgemini-api generate --schema | jq '."$defs".ModelInteraction.properties | keys'
- /
-i可在--input、generate、image、video、analyze和transcribe中附加媒体和文档(可重复使用)。接受最大约 14 MB 的本地路径(base64 上限为 20 MB)、agent runURI 或 YouTube URL。更大或需要重复使用的文件,可通过files/<id>上传一次。gemini-api files upload <path> --wait - /
-f可在--file和tts中从文件读取提示文本。管道输入的文本需要music: 将纯文本传入--stdin、generate、image或video时,必须传入analyze,否则管道输入会被解析为 JSON--stdin。--body - 可传入原始 Gemini API JSON 内容,支持直接提供、从
--body读取或通过@file.json传入(与标志合并;存在重复键时以退出码 2 退出)。可用于设置@-schema、response_format(tools、google_search、code_execution、函数声明)、url_context、generation_config或environment。store - 不要直接输出原始 : 它会打印约 91 KB 的压缩 JSON,并在
--schema运行前退出。请将其传给--jq:jqshgemini-api generate --schema | jq '."$defs".ModelInteraction.properties | keys'
Media, analysis, and transcription
媒体、分析与转录
sh
HERO=$(gemini-api image "Isometric cloud database icon" --aspect-ratio 16:9 --image-size 2K --out ./hero.jpg)
gemini-api image "Add warm sunset lighting" -i "$HERO" --out ./hero-sunset.jpg
gemini-api tts "Alice: Ready to ship? Bob: Checks are green." \
--multi-speaker "Alice=Kore,Bob=Puck" --out ./dialogue.wav
VID_ID=$(gemini-api video "Aerial coastal cliffs at sunrise" --aspect-ratio 16:9 --resolution 1080p --async)
gemini-api video --resume "$VID_ID" --out ./cliffs.mp4
FILE_URI=$(gemini-api files upload ./call.mp4 --wait) # prints files/<id>
gemini-api analyze -i "$FILE_URI" "List action items with owners and timestamps."
gemini-api transcribe -i "$FILE_URI" --format srt --out ./call.srtsh
HERO=$(gemini-api image "Isometric cloud database icon" --aspect-ratio 16:9 --image-size 2K --out ./hero.jpg)
gemini-api image "Add warm sunset lighting" -i "$HERO" --out ./hero-sunset.jpg
gemini-api tts "Alice: Ready to ship? Bob: Checks are green." \
--multi-speaker "Alice=Kore,Bob=Puck" --out ./dialogue.wav
VID_ID=$(gemini-api video "Aerial coastal cliffs at sunrise" --aspect-ratio 16:9 --resolution 1080p --async)
gemini-api video --resume "$VID_ID" --out ./cliffs.mp4
FILE_URI=$(gemini-api files upload ./call.mp4 --wait) # prints files/<id>
gemini-api analyze -i "$FILE_URI" "List action items with owners and timestamps."
gemini-api transcribe -i "$FILE_URI" --format srt --out ./call.srtManaged agents and sandboxes
托管 Agent 与沙箱
- and
deep-research-preview-04-2026: run withdeep-research-max-preview-04-2026and poll--background.agent status - (Linux sandbox with Bash, Python, Node, file ops, and web search): pass
antigravity-preview-09-2026("remote") orenvironmentinenvironment_id.--body
ID boundary: , , and take a run ID (). , , , and manage custom agents only (built-in agents appear in ; cap and with ).
agent statusagent cancelagent delete-interactionv1_...agent createagent getagent listagent deletegemini-api modelsagent listenvironments list--page-size 10sh
RUN_ID=$(gemini-api agent run "Compare WebRTC SFU architectures with primary sources." \
--agent deep-research-preview-04-2026 --background --jq '.id')
gemini-api agent status "$RUN_ID" --jq '.status' # queued | in_progress | completed | failed
gemini-api agent status "$RUN_ID" \
--jq '[.steps[]? | select(.type=="model_output") | .content[]? | select(.type=="text") | .text] | join("")'
ENV_ID=$(gemini-api agent run "Benchmark radix sort vs timsort in Python and write results.csv." \
--agent antigravity-preview-09-2026 --body '{"environment": "remote"}' --jq '.environment_id')
gemini-api environments files list -e "$ENV_ID" -r
gemini-api environments files download "$ENV_ID" results.csv --out ./results.csv
gemini-api agent create --id code-reviewer --base-agent antigravity-preview-09-2026 \
--system-instruction "Review diffs for race conditions and auth bugs."- 和
deep-research-preview-04-2026:使用deep-research-max-preview-04-2026运行,并轮询--background。agent status - (Linux 沙箱,支持 Bash、Python、Node、文件操作和 Web 搜索):在
antigravity-preview-09-2026中传入--body(environment)或"remote"。environment_id
ID 边界: 、 和 接受运行 ID()。、、 和 仅管理自定义 Agent(内置 Agent 会显示在 中;使用 限制 和 的输出)。
agent statusagent cancelagent delete-interactionv1_...agent createagent getagent listagent deletegemini-api models--page-size 10agent listenvironments listsh
RUN_ID=$(gemini-api agent run "Compare WebRTC SFU architectures with primary sources." \
--agent deep-research-preview-04-2026 --background --jq '.id')
gemini-api agent status "$RUN_ID" --jq '.status' # queued | in_progress | completed | failed
gemini-api agent status "$RUN_ID" \
--jq '[.steps[]? | select(.type=="model_output") | .content[]? | select(.type=="text") | .text] | join("")'
ENV_ID=$(gemini-api agent run "Benchmark radix sort vs timsort in Python and write results.csv." \
--agent antigravity-preview-09-2026 --body '{"environment": "remote"}' --jq '.environment_id')
gemini-api environments files list -e "$ENV_ID" -r
gemini-api environments files download "$ENV_ID" results.csv --out ./results.csv
gemini-api agent create --id code-reviewer --base-agent antigravity-preview-09-2026 \
--system-instruction "Review diffs for race conditions and auth bugs."Multi-turn and structured output
多轮对话与结构化输出
Calls store state server-side by default ( is true), so multi-turn chains only need (, , and apply per turn; setting to false disables and ):
store--previous-interaction-idsystem_instructiontoolsgeneration_configstoreprevious_interaction_idbackgroundsh
TURN1=$(gemini-api generate "Propose 2 indexing strategies for time-series logs." --jq '.id')
gemini-api generate "Compare them for write-heavy workloads." --previous-interaction-id "$TURN1"Combine with for schema-constrained JSON output:
--stdin--bodysh
cat build.log | gemini-api generate "Extract unique compiler errors." --stdin --stream=false --body '{
"response_format": {
"type": "text", "mime_type": "application/json",
"schema": {"type": "object", "properties": {"errors": {"type": "array", "items": {"type": "string"}}}, "required": ["errors"]}
},
"store": false
}'Full CLI reference: aistudio.google.com/docs/cli.md; docs index: llms.txt.
默认情况下,调用会在服务端存储状态( 为 true),因此多轮对话链只需 (、 和 每轮生效;将 设为 false 会禁用 和 ):
store--previous-interaction-idsystem_instructiontoolsgeneration_configstoreprevious_interaction_idbackgroundsh
TURN1=$(gemini-api generate "Propose 2 indexing strategies for time-series logs." --jq '.id')
gemini-api generate "Compare them for write-heavy workloads." --previous-interaction-id "$TURN1"将 与 结合使用,可生成受 schema 约束的 JSON 输出:
--stdin--bodysh
cat build.log | gemini-api generate "Extract unique compiler errors." --stdin --stream=false --body '{
"response_format": {
"type": "text", "mime_type": "application/json",
"schema": {"type": "object", "properties": {"errors": {"type": "array", "items": {"type": "string"}}}, "required": ["errors"]}
},
"store": false
}'完整 CLI 参考:aistudio.google.com/docs/cli.md;文档索引:llms.txt。