npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

gemini-api-cli

v0.1.1

Published

Discovery-first command-line interface for the Gemini API and managed agents.

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:

  1. Operate the managed-agents platform — create, run, monitor, continue, cancel, and harvest managed agents and their environments; and
  2. 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: --help at every level tells an agent what exists and how to call it; models reveals routes, defaults, and limits; --dry-run reveals exactly what would happen without spending quota; --json gives 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 status and cancel; 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 --help

Or run it without a global install:

npx gemini-api-cli --help

Build from Clone

Clone the repository, then:

npm install
npm run build
npm test

Link the locally built package, then use the same command as the published CLI:

npm link
gemini-api-cli --help

Authentication & Security

Providing an API Key

An API key can be supplied via three mechanisms:

  1. Environment Variables:
    export GEMINI_API_KEY="your-api-key-here"
    # or
    export GOOGLE_API_KEY="your-api-key-here"
  2. Project .env File: A .env file in the current working directory or any parent directory:
    GEMINI_API_KEY=your-api-key-here
  3. 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:

  1. Environment variable (GEMINI_API_KEY / GOOGLE_API_KEY)
  2. Project .env file (searched upward from current working directory)
  3. Persistent user configuration file (0600 permission 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, or none) 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 --json runs 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:

  1. Local inputs (prompts, options, schemas) are fully validated.
  2. Local input files (-f, --system-file, etc.) are checked for existence and readability.
  3. Model selection and execution parameters are resolved.
  4. An execution plan is printed to stdout (or as a JSON envelope if combined with --json).
  5. 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 --json

doctor

Report CLI runtime, authentication status, config path, and registry sanity.

gemini-api-cli doctor
gemini-api-cli doctor --json

config

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-key

generate

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.json

embed

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.json

tokens

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-flash

files

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/1234567890

image

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.png

tts

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.wav

transcribe

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.md

music

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.mp3

video

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.mp4

agent

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.gz

SDK 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. |