Gemini API CLI

Gemini API CLI (gemini-api) 是無狀態、零依附元件的指令列用戶端,專為具備殼層存取權的 AI 代理建構,可透過指令碼和 CI 使用。接著,程式設計代理可以生成文字和媒體、分析檔案,並將工作委派給 Gemini 代管代理。支援 Antigravity、Claude Code、Codex、Cursor、OpenClaw、Hermes 或任何殼層環境。

每項功能都會在 Interactions API 上以標準殼層指令的形式執行。從代理子程序、終端機或 CI 管道執行相同指令:

# 1. Install on macOS or Linux
curl -fsSL https://raw.githubusercontent.com/google-gemini/gemini-api-cli/main/scripts/install.sh | bash

# 2. Set your API key
export GEMINI_API_KEY="YOUR_API_KEY"

# 3. Generate media, analyze a file, or launch a background managed agent
gemini-api image "Minimalist isometric icon of a cloud database" --out ./assets/db-icon.jpg
gemini-api analyze -i ./docs/quarterly-report.pdf "Summarize the key findings in three bullets."
gemini-api agent run "Compare WebRTC SFU architectures and cite sources" \
  --agent deep-research-preview-04-2026 \
  --background \
  --stream=false

選擇合適的 Gemini 工具

如果代理或指令碼需要直接從殼層呼叫 Gemini,而不將 SDK 程式碼新增至專案,請使用 gemini-api。建構 Gemini 應用程式時,請使用 SDK 和程式設計代理設定:

工具 用途 適用時機
Gemini API CLI (gemini-api) 從任何殼層呼叫 Gemini 模型和代管代理。 您的程式設計代理、殼層指令碼或 CI 工作需要生成式媒體、分析檔案,或執行背景研究代理,且不依賴任何專案。
Google GenAI SDK 將 Gemini 用戶端程式庫匯入 Python、TypeScript、JavaScript、Go、Java 或 C# 程式碼。 您正在將 Gemini 功能建構至應用程式、後端服務或即時 Live API 工作階段。
Gemini 文件 MCP 和技能 為程式設計代理提供即時文件搜尋和最新 SDK 規則。 程式設計代理正在編寫應用程式程式碼,匯入 Google GenAI SDK。

運作方式

原始 REST 呼叫和互動式 CLI 經常會導致程式設計代理發生問題。Base64 媒體會填滿脈絡視窗,互動式提示會封鎖子程序,而過時的訓練資料會導致幻覺標記。

gemini-api 採用四項設計,確保服務專員能可靠地使用:

  • 離線結構定義查詢:傳遞 --usage 以列印指令樹狀結構 (KDL 格式),或傳遞 --schema 以列印 --body 要求的 JSON 結構定義。
  • 磁碟上的檔案、stdout 上的路徑:媒體和轉錄指令會將檔案寫入磁碟,並僅輸出路徑,將二進位資料排除在內容之外。
  • 模擬測試和結構化輸出: --dry-run 會驗證輸入內容、遮蓋憑證,並離線預覽 HTTP 要求。傳遞 -o json、-o toon 或 --jq,即可取得機器可讀的輸出內容。新增 --agent-mode,在 stderr 傳回結構化 JSON 錯誤,並檢查結束代碼來處理失敗。除非您傳遞 --interactive,否則指令一律不會提示。
  • 預設為無狀態:指令不會保留任何隱藏的本機狀態。使用 --previous-interaction-id、上傳的 files/<id> URI 或背景互動 ID,明確鏈結多步驟工作。

使用 -o json 時,媒體指令仍會將檔案寫入磁碟,並將中繼資料輸出至 stdout:

{
  "kind": "image",
  "mime_type": "image/jpeg",
  "path": "/path/to/project/assets/db-icon.jpg",
  "response_id": "v1_...",
  "size_bytes": 2914159,
  "status": "completed"
}

開始使用

安裝 CLI、將 gemini-api 放入 PATH、設定 GEMINI_API_KEY,並為程式設計代理新增使用規則。

1. 安裝二進位檔

macOS 和 Linux

curl -fsSL https://raw.githubusercontent.com/google-gemini/gemini-api-cli/main/scripts/install.sh | bash

如要安裝特定版本,請將 GEMINI_VERSION 設為版本標記:

curl -fsSL https://raw.githubusercontent.com/google-gemini/gemini-api-cli/main/scripts/install.sh | GEMINI_VERSION=<release-tag> bash

Windows (PowerShell)

iwr -useb https://raw.githubusercontent.com/google-gemini/gemini-api-cli/main/scripts/install.ps1 | iex

Go

go install github.com/google-gemini/gemini-api-cli/cmd/gemini-api@latest

預先建構的二進位檔

從 GitHub 版本下載 macOS、Linux 和 Windows 的版本封存檔,並將 gemini-api 放在 PATH 上。使用預先建構的封存檔,在 Docker 映像檔和 CI 中固定確切版本。

2. 設定驗證機制並驗證

在 Google AI Studio 建立 API 金鑰 (請參閱 API 金鑰)。在殼層和代理的子程序環境中設定 GEMINI_API_KEY:

export GEMINI_API_KEY="YOUR_API_KEY"

在本機工作站上,您可以將金鑰儲存在 OS 鑰匙圈 (macOS 鑰匙圈、Linux Secret Service 或 Windows Credential Manager)。傳遞 --no-keyring,改為將金鑰儲存在 ~/.config/gemini-api/config.yaml 中:

# Save to your OS keychain (or run gemini-api configure --interactive)
gemini-api configure --api-key "YOUR_API_KEY"

# Check the active credential source, then preview a request offline
gemini-api whoami
gemini-api generate "Confirm CLI setup in one sentence." --dry-run

3. 給 AI 代理一些指示

將這段程式碼片段新增至專案的 AGENTS.md、CLAUDE.md、.cursorrules 或系統提示,讓程式設計代理瞭解如何使用 gemini-api:

## Gemini API CLI (`gemini-api`)

You have access to `gemini-api` through the shell. Use it to generate text or media (images, speech, music, video), analyze documents and recordings, or run and manage Gemini managed agents.

1. Run `gemini-api --help` or `gemini-api --usage` to choose a command, and `gemini-api <command> --schema` before building a `--body` JSON payload.
2. Preview unfamiliar or complex calls offline with `--dry-run -o json`.
3. For a single JSON result or `--jq` filtering on `generate` or `agent run`, pass `--stream=false -o json`.
4. To chain multi-step workflows, capture the output paths that media and transcription commands print to stdout, and the `id` values returned by `generate` or `agent run`.

接著,照常提示程式設計代理:

Build a landing page for our developer tool. Use Gemini to generate a hero
illustration and a 15-second welcome voiceover, and start a background Deep
Research agent to compare competing CLI onboarding flows. Wire the assets and
findings into the page.

指令

執行 gemini-api --help 即可列出所有指令,或執行 gemini-api explore 以互動方式瀏覽指令。

群組 指令 用途
建立 image 生成或編輯圖片 (-i)、寫入 JPEG 檔案,並輸出檔案路徑。
建立 tts 合成 24 kHz 單聲道 WAV 語音 (一或兩位說話者),並輸出路徑。
建立 music 生成音樂曲目或循環播放、寫入音訊檔案,並輸出路徑。
建立 video 生成或編輯 MP4 短片,並等待作業完成 (--async 會立即傳回 ID)。
建立 generate 生成文字並串流至 stdout (--stream=false 會傳回一項完整結果)。
瞭解 analyze 回答有關 PDF、圖片、音訊、影片、CSV 和文字檔案,或公開 YouTube 網址的問題。
瞭解 transcribe 寫入含有講者標籤和時間戳記的轉錄稿 (md、text、json 或 srt),並輸出路徑。
管理代理 agent 執行代管代理程式 (run、status、cancel、delete-interaction),並管理自訂代理程式定義 (create、list、get、delete)。
管理代理 environments、credentials、webhooks、triggers 設定沙箱環境、儲存的憑證、Webhook 傳送,以及代管代理的排定執行作業。
設定和檔案 configure、auth、whoami 設定憑證和預設值,並顯示有效的驗證狀態。
設定和檔案 files 在 Files API 中上傳、列出、檢查及刪除檔案。
設定和檔案 models 列出可用模型。

Workflows

每項指令預設會使用適合該工作的模型。傳遞 --model (-m) 即可選擇其他模型。執行 gemini-api models 即可列出可用選項。

生成及編輯圖像

建構網頁或行動裝置 UI 的代理,可以使用 Nano Banana 生成預留位置、圖示和主頁橫幅。使用 -i 傳回生成的路徑,即可編輯圖片:

# Generate a 16:9 image at 2K resolution (512, 1K, 2K, or 4K) and capture its path
HERO_PATH=$(gemini-api image "Friendly robot mascot in a sunlit workshop, space on left for headline" \
  --aspect-ratio 16:9 \
  --image-size 2K \
  --out ./public/images/hero.jpg)

# Edit the generated image
gemini-api image "Add a winter scarf and soft snowfall outside the window" \
  -i "$HERO_PATH" \
  --out ./public/images/hero-winter.jpg

多次傳遞 -i,即可合併參考圖像,例如角色和樣式指南。

語音合成

gemini-api tts 會合成 24 kHz WAV 音訊,用於 UI 提示、無障礙預覽和口述逐步操作說明。預設語音為 Kore,請使用 --voice 選擇其他語音。如果是雙人對話,請在提示中標示每個對話回合,並將說話者對應至聲音:

gemini-api tts "Build succeeded. All integration tests passed." \
  --voice Aoede \
  --out ./public/audio/build-ok.wav

gemini-api tts "Alice: Welcome to the release walkthrough! Bob: Let's look at what shipped today." \
  --multi-speaker "Alice=Kore,Bob=Puck" \
  --out ./public/audio/release-intro.wav

音樂和影片

使用 Lyria 創作原創曲目,並用 Gemini Omni 生成 MP4 短片:

gemini-api music "Warm ambient synth and acoustic guitar background loop, 95 BPM" \
  --out ./public/audio/bg-loop.mp3

gemini-api video "A drone shot of a mountain landscape at sunrise." \
  --aspect-ratio 16:9 \
  --resolution 1080p \
  --out ./public/video/mountain-sunrise.mp4

根據預設,video 指令會等待生成作業完成,並將 MP4 檔案寫入磁碟。傳遞 --async 即可立即傳回互動 ID,然後在稍後執行 gemini-api video --resume <id> --out <path>。傳遞 -i 即可為現有圖片加上動畫效果。

文字生成

gemini-api generate 將文字串流至 stdout:

gemini-api generate "Write a one-paragraph welcome message for new users of a note-taking app."

新增 --stdin,將文字傳送至提示詞。傳遞 --previous-interaction-id 即可繼續先前的互動。

文件分析和轉錄

analyze 可回答有關 PDF、試算表、螢幕截圖、音訊和影片檔案,以及公開 YouTube 網址的問題。transcribe 會將格式化轉錄稿 (md、text、json 或 srt) 寫入磁碟:

gemini-api analyze -i ./docs/product-brief.pdf "List the open questions and who owns each one." > open-questions.md

gemini-api transcribe -i ./fixtures/customer-call.mp4 --format srt --out ./fixtures/customer-call.srt

多次將 -i 傳遞至 analyze,以比較檔案,例如前後螢幕截圖。

gemini-api 會傳送內嵌本機檔案,大小上限為 14 MB (base64 編碼後為 20 MB)。如果是較大的檔案,請使用 files upload --wait 上傳一次,並重複使用傳回的 files/<id> URI:

FILE_URI=$(gemini-api files upload ./recordings/all-hands.mp4 --wait)

gemini-api analyze -i "$FILE_URI" "List action items with owners and timestamps."
gemini-api transcribe -i "$FILE_URI" --format json --out ./recordings/all-hands.json

執行及管理代理

程式設計代理可將多步驟研究或沙箱工作委派給 Gemini 代管代理,例如 Deep Research 代理。傳遞 --background --stream=false 即可立即取得互動 ID,不必保持串流開啟:

# Launch a Deep Research job in the background and capture its interaction ID
RESEARCH_ID=$(gemini-api agent run "Compare open-source vector index benchmarks and cite primary papers." \
  --agent deep-research-preview-04-2026 \
  --background \
  --stream=false \
  --jq '.id')

# Check status or fetch the finished result while continuing other work
gemini-api agent status "$RESEARCH_ID" -o json

執行 gemini-api agent cancel <id> 即可停止執行中的工作。您也可以使用 agent run 在遠端沙箱中啟動 Antigravity 代理程式,或使用 agent create、list、get 和 delete 管理自訂代理程式。如要設定代理沙箱,請參閱「環境」。

自訂要求主體

如果選項沒有專屬旗標,請使用 --body (內嵌或 @file.json) 傳遞原始 Interactions API JSON 酬載。傳遞 --body 即可設定 response_format 結構定義、呼叫函式工具、generation_config 或 "store": false。請先執行 gemini-api <command> --schema,查看有效欄位:

# Inspect the JSON Schema for the request body
gemini-api generate --schema > generate-schema.json

# Return schema-constrained JSON and skip storing the interaction
cat logs.txt | gemini-api generate "Extract every error message from these logs." \
  --stdin \
  --body '{
    "response_format": {
      "type": "text",
      "mime_type": "application/json",
      "schema": {
        "type": "object",
        "properties": {"errors": {"type": "array", "items": {"type": "string"}}},
        "required": ["errors"]
      }
    },
    "store": false
  }'

--body 會與指令旗標合併。如果兩者設定相同的鍵,指令會失敗並傳回結束代碼 2,因此衝突的輸入內容會快速失敗。

結束代碼

每個指令都會傳回類型化的結束代碼,因此指令碼和代理程式可以處理失敗,而不必剖析錯誤文字。例如,3 表示驗證問題,2 則表示指令語法無效:

程式碼 意義
0 指令執行成功。
1 執行階段或 API 錯誤,例如網路故障、頻率限制或背景工作失敗。
2 使用或驗證錯誤,例如不明旗標、缺少輸入內容或重複的 --body 鍵。
3 驗證或授權失敗,例如缺少 API 金鑰/權杖,或 API 金鑰/權杖無效。

執行 gemini-api --help-global,列出每個指令共用的全域旗標 (驗證、輸出、網路和診斷)。

限制

  • 串流指令 (generate 和 agent run) 與 -o json 或 --jq 搭配使用時,必須加上 --stream=false,才能傳回單一 JSON 回應物件。
  • 內嵌 -i 檔案輸入內容的原始檔案資料上限為 14 MB (要求酬載為 20 MB,包括 base64 編碼)。使用 gemini-api files upload 上傳大型檔案。Files API 會在 48 小時後刪除上傳的檔案。
  • gemini-api 支援標準 HTTP 要求、SSE 串流和非同步輪詢,但不支援雙向 WebSocket。如要即時串流語音和影片,請搭配使用 Live API 和 Google GenAI SDK。

後續步驟