gemini-api-cli
v0.1.1
Published
Discovery-first command-line interface for the Gemini API and managed agents.
Maintainers
Readme
gemini-api-cli
gemini-api-cli is a discovery-first command-line interface for the Gemini API and managed-agents platform.
It exists so that agents (priority 0) and humans (priority 1) can:
- Operate the managed-agents platform — create, run, monitor, continue, cancel, and harvest managed agents and their environments; and
- Reach full generation access to every modality of the Gemini model family: text, structured output, images, video, speech, music, transcription, embeddings, tokens, files.
It is not a 1:1 mapping of the GenAI SDK. The SDK is the implementation detail behind the product. The command grammar is an AI/human-readable discovery mechanism with all the knobs exposed rather than reflecting SDK namespaces directly.
- Discovery first:
--helpat every level tells an agent what exists and how to call it;modelsreveals routes, defaults, and limits;--dry-runreveals exactly what would happen without spending quota;--jsongives one stable envelope everywhere. - All the knobs: Every meaningful capability control is a visible, validated option — never a hidden default, never a flag that silently does nothing.
- Product grammar over SDK symmetry: Commands are named for user intent (
generate,image,video,tts,transcribe,music,embed,tokens,files,agent), not for SDK namespaces. - Plain stdout is the deliverable: text, a count, or an absolute artifact path. Progress, spinners, and diagnostics go to stderr. Machine mode is first-class; humans get the same truth.
Status
Every capability below was exercised against the live Gemini API, not just unit-tested. 21 live tests pass end to end, each judged on real evidence:
- Text — plain inference, JSON envelope with real token usage, single-value extraction
- Embeddings — a real, non-empty vector
- Tokens — bare integer counts
- Files — upload returning a server-assigned id
- Image — a JPEG verified by
file - Speech — RIFF WAVE PCM audio
- Transcription — a full synthesize-then-transcribe roundtrip
- Music — MP3, with the extension corrected to match the returned MIME type
- Video — a real MP4 through async polling, and Omni planning without spending
- Agents — create, inspect, delete round-trip; a foreground run returning real output;
a background run whose interaction id pipes into
statusandcancel; and a snapshot pull that fails cleanly without leaving a partial archive behind
240 unit tests pass offline and keyless. No command prints an API key: agent definitions can carry inline environment files, and any credential in them is redacted before output.
Proof of concept — published for testing, not a supported release.
Installation & Requirements
System Requirements
- Node.js: Minimum version 22+ (
node -v>= 22.0.0).
Install from npm
Install the CLI globally:
npm install --global gemini-api-cli
gemini-api-cli --helpOr run it without a global install:
npx gemini-api-cli --helpBuild from Clone
Clone the repository, then:
npm install
npm run build
npm testLink the locally built package, then use the same command as the published CLI:
npm link
gemini-api-cli --helpAuthentication & Security
Providing an API Key
An API key can be supplied via three mechanisms:
- Environment Variables:
export GEMINI_API_KEY="your-api-key-here" # or export GOOGLE_API_KEY="your-api-key-here" - Project
.envFile: A.envfile in the current working directory or any parent directory:GEMINI_API_KEY=your-api-key-here - Persistent User Configuration:
Save an API key to local persistent user storage (
~/.config/gemini-api-cli/config.json,$GEMINI_CONFIG_DIR, or$XDG_CONFIG_HOME):echo "your-api-key-here" | gemini-api-cli config set-key --stdin
Precedence
The CLI resolves authentication credentials in strict priority order:
- Environment variable (
GEMINI_API_KEY/GOOGLE_API_KEY) - Project
.envfile (searched upward from current working directory) - Persistent user configuration file (
0600permission mode)
Security Guarantee
- Zero Key Leaks: Runtime code never embeds, logs, or prints an API key on stdout or stderr.
config status: Reports key presence and source category (env,project .env,user config, ornone) without revealing credential values.
Machine Interface & Standard Conventions
Output Discipline
- Stdout: Plain deliverable content — generated text, token integer count, or absolute file path.
- Stderr: Diagnostics, progress indicators, spinners, and debug logging.
- Clean machine mode: Experimental SDK warnings and dependency chatter are contained at the client boundary. Successful
--jsonruns keep stderr completely empty.
JSON Envelope Format (--json)
Every command accepts --json to output a structured JSON envelope.
Success Envelope
{
"ok": true,
"capability": "generate",
"model": "gemini-2.5-flash",
"stdout": "Quantum computing processes information using qubits.",
"details": {
"usage": {
"promptTokens": 10,
"candidatesTokens": 12,
"totalTokens": 22
}
}
}Failure Envelope
{
"ok": false,
"capability": "generate",
"error": {
"name": "CliError",
"message": "Invalid API key supplied"
}
}Extraction (--transform & --raw)
--transform <dot.path>: Extracts a specific property value from the JSON envelope (e.g.--transform details.usage.totalTokens).--raw: When combined with--transform, outputs unquoted raw string values directly to stdout for shell pipelines.
Exit Codes
| Exit Code | Classification | Description |
| :---: | :--- | :--- |
| 0 | Success | Command executed successfully. |
| 1 | RuntimeError | API network failure, remote service failure, or execution error. |
| 2 | InvalidUsage | Invalid flags, missing required arguments, or unreadable local files. |
| 3 | AuthError | Missing, empty, or invalid authentication credentials. |
Quota Spending & Artifact Delivery
Dry Run (--dry-run)
All quota-spending commands (generate, embed, tokens, image, tts, transcribe, music, video) support --dry-run.
When --dry-run is passed:
- Local inputs (prompts, options, schemas) are fully validated.
- Local input files (
-f,--system-file, etc.) are checked for existence and readability. - Model selection and execution parameters are resolved.
- An execution plan is printed to stdout (or as a JSON envelope if combined with
--json). - No network request is made, no API client is constructed, and zero quota or credits are spent.
Artifact File Delivery
Binary outputs (images, audio, video, files, archives) are written directly to disk — never to stdout.
- Default output paths are timestamped and collision-resistant.
- Output locations can be specified using
-o, --out <path>. - Reported file paths on stdout are always absolute paths.
Commands that write local files: generate (-o), embed (-o), image (-o), tts (-o), transcribe (-o), music (-o), video (-o), files download (--out), agent pull (-o).
Command Reference & Examples
Every command family in the CLI help tree is listed below with runnable examples:
models
Print the curated offline model registry, routes, and limits.
# Print all models in registry
gemini-api-cli models
# Filter models by capability route
gemini-api-cli models --route text --jsondoctor
Report CLI runtime, authentication status, config path, and registry sanity.
gemini-api-cli doctor
gemini-api-cli doctor --jsonconfig
Manage persistent user configuration (status, set-key, clear-key).
# Check key presence and resolution source
gemini-api-cli config status
# Save an API key securely (0600 permissions)
echo "AIzaSy..." | gemini-api-cli config set-key --stdin
# Remove saved API key
gemini-api-cli config clear-keygenerate
Text generation, multimodal prompts, structured JSON output, and grounded search.
# Validate generation prompt with --dry-run (quota spending)
gemini-api-cli generate "Summarize the history of space travel" --dry-run
# Multimodal text generation with image input
gemini-api-cli generate "Describe this diagram" -f diagram.png --model gemini-2.5-flash
# Structured JSON output using a local schema file
gemini-api-cli generate "List 3 colors" --schema colors-schema.json -o response.jsonembed
Generate dense vector embeddings for text or media.
# Dry-run validation (quota spending)
gemini-api-cli embed "Semantic search text" --dry-run
# Generate 768-dimensional embedding vector
gemini-api-cli embed "Search query text" --dimensions 768 -o embedding.jsontokens
Calculate input token counts without calling generation endpoints.
# Dry-run validation (quota spending)
gemini-api-cli tokens "Count tokens in this string" --dry-run
# Count tokens in a local document file
gemini-api-cli tokens -f document.pdf --model gemini-2.5-flashfiles
Manage Gemini API remote file asset lifecycle (upload, list, get, download, delete).
# Upload a local file asset
gemini-api-cli files upload presentation.pdf
# List uploaded files
gemini-api-cli files list
# Get file metadata by ID
gemini-api-cli files get files/1234567890
# Download a generated file artifact
gemini-api-cli files download files/1234567890 --out output.mp4
# Delete a file asset
gemini-api-cli files delete files/1234567890image
Image generation, editing, inpainting, and outpainting.
# Dry-run validation (quota spending)
gemini-api-cli image "A vibrant sunset over mountain peaks" --dry-run
# Generate an image with explicit aspect ratio
gemini-api-cli image "A futuristic city skyline" --aspect 16:9 -o city.jpg
# Edit an existing image using reference files
gemini-api-cli image "Add a blue sky" -f original.png -o edited.pngtts
Text-to-speech audio synthesis.
# Dry-run validation (quota spending)
gemini-api-cli tts "Welcome to Gemini API CLI" --dry-run
# Synthesize speech with selected voice
gemini-api-cli tts "Hello world" --voice Kore -o speech.wavtranscribe
Audio-to-text transcription with timestamping and speaker diarization controls.
# Dry-run validation (quota spending)
gemini-api-cli transcribe recording.mp3 --dry-run
# Transcribe audio file with markdown output and timestamps
gemini-api-cli transcribe meeting.wav -f md --timestamps -o transcript.mdmusic
Lyria music generation.
# Dry-run validation (quota spending)
gemini-api-cli music "Uplifting synthwave melody" --dry-run
# Generate instrumental pro-tier music
gemini-api-cli music "Energetic acoustic guitar" --quality pro --instrumental -o song.mp3video
Asynchronous Veo and Omni video generation with polling controls.
# Dry-run validation (quota spending)
gemini-api-cli video "A drone shot over coastal cliffs" --dry-run
# Generate video clip with Veo lite route
gemini-api-cli video "A cat wearing a party hat" --quality lite --duration 8 -o clip.mp4agent
Managed-agent platform execution, agent definitions, interactions, webhooks, triggers, and environment snapshots.
# Create a managed agent definition
gemini-api-cli agent create research-bot --system-instruction "You are a research agent" --agent-config-model gemini-2.5-pro
# List registered agents
gemini-api-cli agent list
# Get agent definition
gemini-api-cli agent get research-bot
# Synchronously run an agent interaction
gemini-api-cli agent run research-bot "Analyze market trends"
# Check status of an interaction
gemini-api-cli agent status interactions/1234567890
# Cancel an active interaction
gemini-api-cli agent cancel interactions/1234567890
# Delete an interaction record
gemini-api-cli agent delete-interaction interactions/1234567890
# Delete an agent definition
gemini-api-cli agent delete research-bot
# List contents of an environment snapshot archive
gemini-api-cli agent ls env-1234567890
# Download environment snapshot archive
gemini-api-cli agent pull env-1234567890 -o snapshot.tar.gzSDK Surface Coverage & Deferred Capabilities
This CLI maps the public @google/genai (v2.13.0) SDK surface into intent-focused command families. Derived from docs/sdk-map.md, the following table details covered vs. deliberately deferred surfaces:
| SDK Surface | Status | CLI Mapping / Intent & Rationale |
| :--- | :---: | :--- |
| models.generateContent / generateContentStream | Covered | Exposed via generate, tts, transcribe. |
| models.generateImages / editImage / upscaleImage / recontextImage / segmentImage | Covered | Exposed via image. |
| models.generateVideos / operations.get / getVideosOperation | Covered | Exposed via video. |
| models.embedContent | Covered | Exposed via embed. |
| models.countTokens / computeTokens | Covered | Exposed via tokens. |
| models.list / get | Covered | Exposed via models. |
| files.upload / get / list / delete / download / registerFiles | Covered | Exposed via files. |
| chats.create | Covered | Continuation history handled via generate, image, and video --previous flags. |
| interactions.* / agents.* / triggers.* / webhooks.* | Covered | Exposed via agent. |
| live.music.connect | Covered | Exposed via music. |
| batches.* (create, createEmbeddings, get, list, cancel, delete) | Deferred | Offline bulk batch processing is out of scope for interactive CLI usage. |
| caches.* (create, get, update, delete, list) | Deferred | Context caching service management deferred. |
| tunings.* (tune, get, list, cancel) | Deferred | Fine-tuning and model training lifecycle deferred. |
| fileSearchStores.* (create, get, list, delete, uploadToFileSearchStore, importFile, downloadMedia) | Deferred | RAG vector store index management deferred. |
| live.connect | Deferred | Bi-directional WebSocket low-latency voice session streaming deferred. |
| authTokens.create | Inapplicable | Short-lived client auth token minting inapplicable; CLI uses direct API key authentication. |
| models.update | Inapplicable | Model definition mutation inapplicable. |
