gemini-api-cli

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
The
gemini-api
CLI exposes every Gemini API resource as a shell subcommand. Compared to
curl
: media and transcription commands decode output to disk and print only the file path,
-i
attaches local files or
files/<id>
URIs,
--jq
extracts fields in-process (raw strings by default, no external
jq
),
--dry-run
previews redacted HTTP requests offline, and list endpoints auto-paginate with
--all
(cap pages with
--max-pages N
;
--page-size
sets server page size).
gemini-api
CLI 将每个 Gemini API 资源都暴露为 shell 子命令。与
curl
相比:媒体和转录命令会将输出解码后写入磁盘,并且只打印文件路径;
-i
可附加本地文件或
files/<id>
URI;
--jq
可在进程内提取字段(默认输出原始字符串,无需外部
jq
);
--dry-run
可离线预览已脱敏的 HTTP 请求;列表端点可通过
--all
自动分页(使用
--max-pages N
限制页数;
--page-size
设置服务器端页面大小)。

CLI vs SDK

CLI 与 SDK

CLI for shell work, SDK for application code. Use
gemini-api
from terminals, scripts, and CI jobs to generate media files, analyze local PDFs or recordings, run Deep Research, and manage agent sandboxes (
gemini-api
is a stateless Gemini API client, distinct from the interactive
@google/gemini-cli
coding agent). Use the Google GenAI SDKs (
gemini-api-dev
,
gemini-live-api-dev
) when calls live inside application source or need bidirectional Live API WebSockets.
用于 shell 操作的 CLI,用于应用代码的 SDK。 在终端、脚本和 CI 作业中使用
gemini-api
,可生成媒体文件、分析本地 PDF 或录音、执行 Deep Research,并管理 Agent 沙箱(
gemini-api
是无状态的 Gemini API 客户端,不同于交互式
@google/gemini-cli
编程 Agent)。当调用位于应用程序源代码内部,或需要双向 Live API WebSockets 时,请使用 Google GenAI SDK(
gemini-api-dev
、
gemini-live-api-dev
)。

Install and auth

安装与身份验证

sh
undefined
sh
undefined

macOS / Linux (set GEMINI_VERSION=<tag> to pin a release)

macOS / Linux(设置 GEMINI_VERSION=<tag> 可固定版本)


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.

凭据按以下顺序解析(匹配到第一个即停止):`--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 groups
Run
gemini-api --help
to list commands, or
<subcommand> --help
for flags and examples (
--usage
dumps a 45 KB KDL spec, so stick to
--help
to save context).
CommandKey flags / actionsDefault model & behavior
generate [prompt]
-m
,
-i
,
--stdin
,
--system
,
--previous-interaction-id
,
--stream=false
,
--body
gemini-3.8-flash
; streams text deltas to stdout
image [prompt]
-m
,
-i
,
--aspect-ratio
,
--image-size
(512..4K),
--previous-interaction-id
,
--out
gemini-nano-banana-2.1
; writes image, prints path
tts [text]
-f
,
--stdin
,
--voice
(default Kore),
--multi-speaker
,
--language
,
--out
gemini-3.8-flash-tts
; writes 24 kHz WAV, prints path (unstored)
music [prompt]
-m
,
-f
,
--stdin
,
--out
,
--body
lyria-3.5
; writes audio track, prints path
video [prompt]
-m
,
-i
,
--aspect-ratio
,
--resolution
(360p..4k),
--async
,
--resume
,
--out
gemini-omni-1.1-flash
; polls until done, writes MP4, prints path
analyze [question]
-i
(required, repeatable),
--stdin
,
--system
,
-m
gemini-3.8-flash
; answers over PDFs, media, CSV/text, YouTube URLs (unstored)
transcribe
-i
(required, repeatable),
--format
(md, text, json, srt),
--no-speakers
,
--no-timestamps
,
--out
gemini-3.8-flash
; writes
--out
(or
./transcript-*
), prints path (unstored)
agent
run
,
status
,
cancel
,
delete-interaction
;
create
,
list
,
get
,
delete
Runs models or managed agents; manages custom agent definitions
files
upload [--wait]
,
list
,
get
,
generated-files-list
,
register
,
delete
Uploads reusable
files/<id>
URIs (48h TTL; up to 2 GB, 50 MB PDFs)
models
(bare),
list [--all]
,
get <id>
Bare
models
prints an offline catalog;
list
and
get
query the live API
environments
create
,
list
,
get
,
delete
,
files
,
connect
,
poll
,
serve
Remote sandboxes and workspace snapshots (
credentials
,
webhooks
,
triggers
for agent infra)
Model selection: use
gemini-3.8-flash
(default),
gemini-4-argon
(hard reasoning and coding), or
gemini-3.5-flash-lite
(high throughput); for images,
gemini-nano-banana-2.1
,
gemini-3.1-flash-lite-image
, or
gemini-3-pro-image
. Avoid deprecated
gemini-2.5-*
,
gemini-2.0-*
, and
gemini-1.5-*
models.
text
gemini-api <intent> [prompt] [flags]          # 带模型和模态预设的任务命令
gemini-api <resource> <action> [flags]        # REST 资源组
运行
gemini-api --help
可列出命令,或使用
<subcommand> --help
查看标志和示例(
--usage
会输出 45 KB 的 KDL 规范,因此为节省上下文请使用
--help
)。
命令主要标志/操作默认模型与行为
generate [prompt]
-m
、
-i
、
--stdin
、
--system
、
--previous-interaction-id
、
--stream=false
、
--body
gemini-3.8-flash
;以流式形式将文本增量输出到 stdout
image [prompt]
-m
、
-i
、
--aspect-ratio
、
--image-size
(512..4K)、
--previous-interaction-id
、
--out
gemini-nano-banana-2.1
;写入图像并打印路径
tts [text]
-f
、
--stdin
、
--voice
(默认 Kore)、
--multi-speaker
、
--language
、
--out
gemini-3.8-flash-tts
;写入 24 kHz WAV 并打印路径(不存储)
music [prompt]
-m
、
-f
、
--stdin
、
--out
、
--body
lyria-3.5
;写入音轨并打印路径
video [prompt]
-m
、
-i
、
--aspect-ratio
、
--resolution
(360p..4k)、
--async
、
--resume
、
--out
gemini-omni-1.1-flash
;轮询直至完成,写入 MP4 并打印路径
analyze [question]
-i
(必需,可重复)、
--stdin
、
--system
、
-m
gemini-3.8-flash
;基于 PDF、媒体、CSV/文本、YouTube URL(不存储)进行回答
transcribe
-i
(必需,可重复)、
--format
(md、text、json、srt)、
--no-speakers
、
--no-timestamps
、
--out
gemini-3.8-flash
;写入
--out
(或
./transcript-*
),打印路径(不存储)
agent
run
、
status
、
cancel
、
delete-interaction
;
create
、
list
、
get
、
delete
运行模型或托管 Agent;管理自定义 Agent 定义
files
upload [--wait]
、
list
、
get
、
generated-files-list
、
register
、
delete
上传可复用的
files/<id>
URI(48 小时 TTL;最大 2 GB,PDF 最大 50 MB)
models
不带子命令、
list [--all]
、
get <id>
不带子命令的
models
会打印离线目录;
list
和
get
会查询实时 API
environments
create
、
list
、
get
、
delete
、
files
、
connect
、
poll
、
serve
远程沙箱和工作区快照(Agent 基础设施的
credentials
、
webhooks
、
triggers
)
模型选择: 使用
gemini-3.8-flash
(默认)、
gemini-4-argon
(复杂推理与编程)或
gemini-3.5-flash-lite
(高吞吐量);图像使用
gemini-nano-banana-2.1
、
gemini-3.1-flash-lite-image
或
gemini-3-pro-image
。避免使用已弃用的
gemini-2.5-*
、
gemini-2.0-*
和
gemini-1.5-*
模型。

Global flags

全局标志

FlagPurpose
-o
,
--output-format
pretty
(default),
json
,
toon
,
yaml
,
table
-q
,
--jq
Filter JSON output with a built-in jq expression (
--raw-output
is true by default)
--agent-mode
Compact TOON on stdout and structured JSON errors on stderr
--no-interactive
Disable prompts, TUI forms, and
explore
--dry-run
Validate inputs and preview redacted HTTP requests offline (
-o json
outputs JSON)
-d
,
--debug
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
gemini-api --help-global
for
--server-url
, pagination, and auth flags.
标志用途
-o
、
--output-format
pretty
(默认)、
json
、
toon
、
yaml
、
table
-q
、
--jq
使用内置 jq 表达式筛选 JSON 输出(
--raw-output
默认值为 true)
--agent-mode
在 stdout 输出紧凑 TOON,在 stderr 输出结构化 JSON 错误
--no-interactive
禁用提示、TUI 表单和
explore
--dry-run
离线验证输入并预览已脱敏的 HTTP 请求(
-o json
会输出 JSON)
-d
、
--debug
将 HTTP 请求和响应详情记录到 stderr
退出码:0 表示成功,1 表示运行时或 API 错误(包括失败或未完成的运行),2 表示用法或验证错误,3 表示身份验证错误。有关
--server-url
、分页和身份验证标志,请参阅
gemini-api --help-global
。

Output

输出

Media (
image
,
tts
,
music
,
video
) and
transcribe
write files locally and print only the file path on stdout. Adding
-o json
still writes the file and prints
{path, mime_type, size_bytes, response_id, status}
.
Streaming and JSON shape:
generate
and
agent run
stream plain reply text by default, so
-o json
alone emits NDJSON events. Pass
--stream=false -o json
for one JSON object
{id, status, steps, usage}
(bare
--stream=false
prints metadata YAML, and
--jq
or
--background
disables streaming automatically). Reply text lives under
.steps[]
model_output
(see
agent status
below) rather than
.candidates[]
. On paginated
list
commands,
--jq
runs per page envelope (
.models[]?.name
,
.agents[]?.id
).
媒体命令(
image
、
tts
、
music
、
video
)和
transcribe
会在本地写入文件,并仅在 stdout 打印文件路径。即使添加
-o json
,仍会写入文件,并打印
{path, mime_type, size_bytes, response_id, status}
。
流式传输与 JSON 结构:
generate
和
agent run
默认以流式形式输出纯回复文本,因此仅使用
-o json
会发出 NDJSON 事件。传入
--stream=false -o json
可获得一个 JSON 对象
{id, status, steps, usage}
(仅使用
--stream=false
会打印元数据 YAML,而
--jq
或
--background
会自动禁用流式传输)。回复文本位于
.steps[]
的
model_output
下(参见下文
agent status
),而不是
.candidates[]
。在分页的
list
命令中,
--jq
会针对每个页面封装结构运行(
.models[]?.name
、
.agents[]?.id
)。

Input

输入

  • -i
    /
    --input
    attaches media and documents on
    generate
    ,
    image
    ,
    video
    ,
    analyze
    ,
    transcribe
    , and
    agent run
    (repeatable). Accepts local paths up to ~14 MB (20 MB base64 cap),
    files/<id>
    URIs, or YouTube URLs. Upload larger or reused files once with
    gemini-api files upload <path> --wait
    .
  • -f
    /
    --file
    reads prompt text from a file on
    tts
    and
    music
    . Piped text needs
    --stdin
    :
    when piping plain text into
    generate
    ,
    image
    ,
    video
    , or
    analyze
    , pass
    --stdin
    or piped input gets parsed as a JSON
    --body
    .
  • --body
    passes raw Gemini API JSON inline, from
    @file.json
    , or via
    @-
    (merges with flags; exits 2 on duplicate keys). Use it for
    response_format
    schemas,
    tools
    (
    google_search
    ,
    code_execution
    ,
    url_context
    , function declarations),
    generation_config
    ,
    environment
    , or
    store
    .
  • Don't dump
    --schema
    raw:
    it prints ~91 KB of minified JSON and exits before
    --jq
    runs. Pipe it to
    jq
    :
    sh
    gemini-api generate --schema | jq '."$defs".ModelInteraction.properties | keys'
  • -i
    /
    --input
    可在
    generate
    、
    image
    、
    video
    、
    analyze
    、
    transcribe
    和
    agent run
    中附加媒体和文档(可重复使用)。接受最大约 14 MB 的本地路径(base64 上限为 20 MB)、
    files/<id>
    URI 或 YouTube URL。更大或需要重复使用的文件,可通过
    gemini-api files upload <path> --wait
    上传一次。
  • -f
    /
    --file
    可在
    tts
    和
    music
    中从文件读取提示文本。管道输入的文本需要
    --stdin
    :
    将纯文本传入
    generate
    、
    image
    、
    video
    或
    analyze
    时,必须传入
    --stdin
    ,否则管道输入会被解析为 JSON
    --body
    。
  • --body
    可传入原始 Gemini API JSON 内容,支持直接提供、从
    @file.json
    读取或通过
    @-
    传入(与标志合并;存在重复键时以退出码 2 退出)。可用于设置
    response_format
    schema、
    tools
    (
    google_search
    、
    code_execution
    、
    url_context
    、函数声明)、
    generation_config
    、
    environment
    或
    store
    。
  • 不要直接输出原始
    --schema
    :
    它会打印约 91 KB 的压缩 JSON,并在
    --jq
    运行前退出。请将其传给
    jq
    :
    sh
    gemini-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.srt
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.srt

Managed agents and sandboxes

托管 Agent 与沙箱

  • deep-research-preview-04-2026
    and
    deep-research-max-preview-04-2026
    : run with
    --background
    and poll
    agent status
    .
  • antigravity-preview-09-2026
    (Linux sandbox with Bash, Python, Node, file ops, and web search): pass
    environment
    ("remote") or
    environment_id
    in
    --body
    .
ID boundary:
agent status
,
agent cancel
, and
agent delete-interaction
take a run ID (
v1_...
).
agent create
,
agent get
,
agent list
, and
agent delete
manage custom agents only (built-in agents appear in
gemini-api models
; cap
agent list
and
environments list
with
--page-size 10
).
sh
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
    。
  • antigravity-preview-09-2026
    (Linux 沙箱,支持 Bash、Python、Node、文件操作和 Web 搜索):在
    --body
    中传入
    environment
    (
    "remote"
    )或
    environment_id
    。
ID 边界:
agent status
、
agent cancel
和
agent delete-interaction
接受运行 ID(
v1_...
)。
agent create
、
agent get
、
agent list
和
agent delete
仅管理自定义 Agent(内置 Agent 会显示在
gemini-api models
中;使用
--page-size 10
限制
agent list
和
environments list
的输出)。
sh
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 (
store
is true), so multi-turn chains only need
--previous-interaction-id
(
system_instruction
,
tools
, and
generation_config
apply per turn; setting
store
to false disables
previous_interaction_id
and
background
):
sh
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
--stdin
with
--body
for schema-constrained JSON output:
sh
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.
默认情况下,调用会在服务端存储状态(
store
为 true),因此多轮对话链只需
--previous-interaction-id
(
system_instruction
、
tools
和
generation_config
每轮生效;将
store
设为 false 会禁用
previous_interaction_id
和
background
):
sh
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"
将
--stdin
与
--body
结合使用,可生成受 schema 约束的 JSON 输出:
sh
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。