Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 60 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
# hermes-gemini-api-plugin

Native Google AI Studio Gemini (**Nano Banana**) image generation and editing backend plugin for [Hermes Agent](https://github.com/NousResearch/hermes-agent).
Google AI Studio Gemini plugin (`gemini-api`) for [Hermes Agent](https://github.com/NousResearch/hermes-agent), powered end-to-end by the official [gemini-api CLI](https://github.com/google-gemini/gemini-api-cli) (Interactions API) under a single `GEMINI_API_KEY`:

Calls the Gemini REST endpoint (`POST /v1beta/models/{model}:generateContent` with `responseModalities: ["TEXT", "IMAGE"]`), decodes returned `inlineData` images into `$HERMES_HOME/cache/generated/images/`, and records token usage (including Nano Banana 2.1 and Nano Banana Pro thinking tokens) into Hermes session accounting.
1. **Image Generation (`GeminiImageGenProvider`, `image_gen.provider: gemini`)** — **Nano Banana 2.1**, **Nano Banana 2**, **Nano Banana 2 Lite**, and **Nano Banana Pro** generation and multi-reference editing via `gemini-api image` (`-i`, `--aspect-ratio`, `--image-size`, optional Google Search grounding), saving images to `$HERMES_HOME/cache/generated/images/`.
2. **Video Generation & CLI Tools (`GeminiVideoGenProvider` + 6 Tools + Skill)** — Native `video_generate` (`video_gen.provider: gemini`), Lyria music generation, Gemini 3.8 Flash single/two-speaker TTS, multimodal file & YouTube analysis, speaker-diarized transcription (`.md` / `.srt`), Gemini Deep Research interactions, and resumable Files API uploads (up to 2 GB).

## Supported Models
## Capabilities Overview

### 1. Image Generation (`image_gen.provider: gemini`)

| Model ID | Display Name | Speed | Capabilities |
| :--- | :--- | :--- | :--- |
Expand All @@ -13,12 +16,27 @@ Calls the Gemini REST endpoint (`POST /v1beta/models/{model}:generateContent` wi
| `gemini-3.1-flash-lite-image` | **Nano Banana 2 Lite** (Gemini 3.1 Flash Lite Image) | Fastest | Lowest latency & cost; 10 aspect ratios, `1K` output resolution, up to 14 reference images |
| `gemini-3-pro-image` | **Nano Banana Pro** (Gemini 3 Pro Image) | Slower | Highest fidelity & reasoning; 10 aspect ratios, `1K` / `2K` / `4K` output resolution, Google Search grounding, up to 14 reference images |

### 2. Video Generation & `gemini-api` CLI Tools

| Surface | CLI Default Model / Agent (`v0.5.0`) | Description |
| :--- | :--- | :--- |
| `video_generate` (`video_gen.provider: gemini`) | `gemini-omni-1.2-flash` | Text-to-video and image-to-video generation (`--aspect-ratio`, `--resolution`, `-i`) saved to `$HERMES_HOME/cache/videos/` |
| `gemini_music` | `lyria-3.5` | Instrumental and vocal music generation saved to `$HERMES_HOME/cache/generated/audio/` |
| `gemini_tts` | `gemini-3.8-flash-tts` | 24 kHz WAV speech synthesis with single-speaker voices (`Kore`, `Puck`, etc.) and 2-speaker scripts |
| `gemini_analyze` | `gemini-4-hydrogen` | Multimodal Q&A over PDFs, videos, audio, images, CSVs, `files/<id>` handles, and YouTube URLs (seamlessly auto-uploads binary media >14 MB via Files API) |
| `gemini_transcribe` | `gemini-3.5-transcribe` | Speaker-diarized and timestamped transcripts in `md`, `text`, `json`, or `srt` captions (seamlessly auto-uploads media >14 MB) |
| `gemini_deep_research` | `deep-research-preview-04-2026` | Start (`run`, async `background: true` by default), poll (`status`), or stop (`cancel`) Gemini Deep Research & Interactions API agent runs |
| `gemini_files_upload` | Gemini Files API | Resumable upload up to 2 GB (`--wait` until `ACTIVE`), returning a reusable 48-hour `files/<id>` handle |
| Skill `gemini-api-cli` | `SKILL.md` | Read-only reference (`skill_view`) for ad-hoc `gemini-api` commands (`models`, `--dry-run`, `video --resume`, `--help`) |

## Installation

### 1. Install the Hermes Plugin

Install from the Hermes Plugin Catalog:

```bash
hermes plugins install gemini-image
hermes plugins install gemini-api
```

Or install directly from GitHub:
Expand All @@ -27,6 +45,20 @@ Or install directly from GitHub:
hermes plugins install https://github.com/google-gemini/hermes-gemini-api-plugin
```

> **Migrating from `gemini-image`:** If you previously installed the v0.1.0 `gemini-image` plugin, uninstall it first (`hermes plugins uninstall gemini-image`) before installing `gemini-api` so both do not register the `gemini` image provider concurrently. Your `image_gen.gemini.*` settings and `GEMINI_API_KEY` remain compatible.

### 2. Install `gemini-api` CLI *(required)*

Install [`google-gemini/gemini-api-cli`](https://github.com/google-gemini/gemini-api-cli) (`v0.5.0`+) onto your `PATH` or `~/.hermes/bin/gemini-api` (or opt into `auto_install_cli: true` in `config.yaml` below):

```bash
# Option A: Install with Go 1.22+
go install github.com/google-gemini/gemini-api-cli/cmd/gemini-api@v0.5.0

# Option B: Download a prebuilt archive from GitHub Releases and verify checksums.txt
# https://github.com/google-gemini/gemini-api-cli/releases/tag/v0.5.0
```

## Configuration

### 1. API Key (`.env`)
Expand All @@ -37,9 +69,7 @@ Set your Google AI Studio API key ([get one here](https://aistudio.google.com/ap
GEMINI_API_KEY="your-api-key"
```

### 2. Provider & Generation Settings (`~/.hermes/config.yaml`)

Select `gemini` as your image generation provider (or run `hermes tools` → **Image Generation** → **Google AI Studio (direct)**):
### 2. Provider & Plugin Settings (`~/.hermes/config.yaml`)

```yaml
image_gen:
Expand All @@ -49,34 +79,40 @@ image_gen:
image_size: 2K # 1K | 2K | 4K (or 512 on gemini-3.1-flash-image)
aspect_ratio: "16:9" # exact ratio override (e.g. 1:1, 16:9, 9:16, 21:9, 1:4, 4:1, 1:8, 8:1)
google_search: false # enable Google Search grounding on supported models
# Optional custom endpoint / credential routing:
# base_url: https://generativelanguage.googleapis.com/v1beta
# key_env: GEMINI_API_KEY
# provider: my-custom-gemini-endpoint

video_gen:
provider: gemini
gemini:
model: "" # optional explicit override (empty uses gemini-api CLI's built-in default)

plugins:
entries:
gemini-api:
settings:
cli_path: "" # optional explicit path to gemini-api binary
# timeout_seconds: 180 # optional override (when omitted: 180s TTS, 300s music/analyze/transcribe/upload, 900s video/sync research)
auto_install_cli: false # opt-in download of pinned v0.5.0 verified against hardcoded SHA-256 digests into $HERMES_HOME/bin
```

Optional environment variable overrides for model and endpoint:
Optional environment variable overrides for image model and endpoint:

- `GEMINI_IMAGE_MODEL` — Override the Gemini image model ID (strips any optional `google/` prefix).
- `GEMINI_BASE_URL` — Override the Gemini API base URL.

## Features

- **Multi-reference image editing**: Pass `image_url` and/or `reference_image_urls` (up to 14 reference images across HTTP(S) URLs, `data:` URIs, or local file paths) to edit, restyle, or combine images.
- **Safety & size guards**: Uses Hermes's SSRF-safe HTTP client for remote URLs, blocks local credential store reads via `raise_if_read_blocked`, sniffs magic bytes (`PNG`, `JPEG`, `WebP`, `GIF`) before upload, and enforces a 25 MB per-image cap plus an 80 MB total inline payload ceiling.
- **Session token accounting**: Reports `promptTokenCount`, `candidatesTokenCount`, `thoughtsTokenCount`, and `cachedContentTokenCount` to Hermes's `record_token_usage`.
- `GEMINI_BASE_URL` — Override the Gemini API base URL (`https://` required; `http://` allowed for localhost testing only).

## Security & Privacy Disclosure

- **External network calls**: Sends text prompts and optional inline reference images over HTTPS to `https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent` (or a custom `image_gen.gemini.base_url`) authenticated via `GEMINI_API_KEY`. Remote `http(s)://` reference image URLs passed to `image_generate` are fetched through Hermes's SSRF-safe HTTP client.
- **Filesystem access**: Reads local reference image paths explicitly passed by the caller (guarded by `agent.file_safety.raise_if_read_blocked`) and writes generated output images to `$HERMES_HOME/cache/generated/images/`.
- **No background processes or telemetry**: Spawns no shell commands or background workers and collects no telemetry.
- **External network calls**: All Gemini API requests (image, video, music, TTS, analyze, transcribe, Deep Research, and Files upload) are sent by `gemini-api` over HTTPS to `generativelanguage.googleapis.com` (or a validated `https://` `image_gen.gemini.base_url` / `GEMINI_BASE_URL` — cleartext non-loopback `http://` URLs are refused) authenticated via `GEMINI_API_KEY`. Remote `http(s)://` reference image URLs are fetched through Hermes's SSRF-safe HTTP client. If `auto_install_cli: true` is explicitly opted into by the user, downloads the pinned `gemini-api` `v0.5.0` release archive (capped at 64 MiB) from `github.com/google-gemini/gemini-api-cli/releases` and verifies it against hardcoded SHA-256 digests before atomic extraction.
- **Subprocess execution**: Invokes the local `gemini-api` binary (`--no-interactive -o json`, `stdin=DEVNULL`, `--` end-of-flags guard on positional prompts/paths) inside an allowlisted, secret-scrubbed environment carrying only the active `GEMINI_API_KEY` (never inheriting unrelated API keys or conflicting `GEMINI_*` / `GOOGLE_API_KEY` variables).
- **Filesystem access**: Validates all caller-supplied local file paths against `agent.file_safety.raise_if_read_blocked` and regular-file checks before reading or passing them to `gemini-api`, and writes generated outputs only under `$HERMES_HOME/cache/` (`generated/images/`, `generated/audio/`, `videos/`, `transcripts/`). Cached media persists until cleaned up by Hermes or the user.
- **Session token accounting**: Reports CLI `usage` token counts (Interactions API `total_*_tokens` and porcelain `thoughts_tokens`) to Hermes's session accounting.

## Development & Testing

Run tests using Hermes's virtual environment and validate the plugin manifest with the Hermes CLI:

```bash
PYTHONPATH=/path/to/hermes-agent:. pytest tests/ -v
PYTHONPATH=/path/to/hermes-agent python -m hermes_cli.main plugins validate .
PYTHONPATH=/path/to/hermes-agent:. /path/to/hermes-agent/.venv/bin/python -m pytest tests/ -v
hermes plugins validate .
```

## Acknowledgments
Expand Down
54 changes: 54 additions & 0 deletions SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
name: gemini-api-cli
description: "Headless usage patterns, flags, and JSON envelopes for google-gemini/gemini-api-cli when invoking gemini-api from Hermes."
---

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

Prefer the structured plugin tools (`image_generate`, `video_generate`, `gemini_music`, `gemini_tts`, `gemini_analyze`, `gemini_transcribe`, `gemini_deep_research`, `gemini_files_upload`) for standard media generation, multimodal analysis, transcription, and Deep Research tasks. Use the `gemini-api` CLI directly only when inspecting model catalogs, previewing request payloads with `--dry-run`, resuming async videos (`video --resume <id>`), or calling advanced Interactions API, webhooks, or triggers subcommands.

## Mandatory Headless Rules

1. **Always disable interactive prompts and request JSON output**: pass `--no-interactive -o json` on every automated command so Cobra never opens a TUI picker on missing arguments.
2. **Disable SSE streaming when parsing JSON**: `generate`, `agent run`, and `agent status` stream SSE by default; add `--stream=false` whenever parsing a single JSON response object.
3. **Authenticate via `GEMINI_API_KEY`**: `gemini-api` reads `GEMINI_API_KEY` from the environment automatically; never pass API keys on the command line where process listings can expose them. Note that `GEMINI_ACCESS_TOKEN` takes precedence over `GEMINI_API_KEY` if set in your shell.
4. **Upload large local files when invoking the CLI directly**: `gemini_analyze` and `gemini_transcribe` plugin tools automatically upload local binary media >14 MiB, but direct `gemini-api` commands inline files up to 14 MiB only. For larger media (up to 2 GiB), run `gemini-api files upload <path> --wait -o json --no-interactive` and pass the returned `files/<id>` handle to `-i`.
5. **Avoid raw `--usage` and `--schema` dumps**: use `gemini-api <subcommand> --help` to inspect flags; raw `--usage` emits ~45 KB of KDL and raw `--schema` emits ~92 KB of JSON (pipe `--schema | jq ...` if you need specific fields).

## Exit Codes & Structured Errors

- `0` — Success (JSON object emitted on `stdout`; for `agent run` / `agent status`, still inspect `.status` and `.errors` because failed interactions exit `0`).
- `1` — Runtime or upstream Gemini API error.
- `2` — CLI flag or argument validation error.
- `3` — Missing or invalid `GEMINI_API_KEY` authentication.

With `-o json` or `--agent-mode`, failures emit structured diagnostics on `stderr`:

```json
{"error": "missing required flag --id", "exit_code": 2, "hints": ["pass --id <interaction_id>"]}
```

## Common Ad-Hoc Commands

```bash
# List available Gemini models as JSON
gemini-api models list --no-interactive -o json

# Inspect CLI flags concisely without flooding context
gemini-api video --help
gemini-api agent run --help

# Preview the outgoing HTTP request without sending network traffic
gemini-api generate "Summarize quantum error correction" --stream=false --dry-run --no-interactive -o json

# Upload a large video or PDF once and reuse its 48-hour files/<id> handle
gemini-api files upload ./lecture.mp4 --wait --no-interactive -o json
gemini-api analyze -i files/abc123xyz "List key equations and timestamps" --no-interactive -o json

# Resume polling an async video job
gemini-api video --resume <interaction_id> --out ./clip.mp4 --no-interactive -o json

# Run and poll a background Deep Research interaction
gemini-api agent run "Compare solid-state battery electrolytes" --agent deep-research-preview-04-2026 --background --stream=false --no-interactive -o json
gemini-api agent status --id <interaction_id> --stream=false --no-interactive -o json
```
Loading