Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install gemini-api@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin gemini-api v1.0.0 follows the Agent Plugins spec.
gh skills-hub install gemini-api Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/gemini-api/ Extract the ZIP to .github/skills/ in your repo. The folder name must match gemini-api for Copilot to auto-discover it.
Skill Files (12)
SKILL.md 8.3 KB
---
name: gemini-api
metadata:
version: "1.0.4"
category: AiAndMachineLearning
description: >-
Integrates Gemini models on Gemini platform (formerly Gemini Enterprise Agent
Platform and Vertex AI) using the unified Google Gen AI SDK across Python,
TypeScript/JavaScript, Go, Java, and C#. Use for Google Cloud AI workloads:
text/multimodal generation, structured JSON, function calling, Search
grounding, code execution, URL context, Nano Banana images, Gemini Omni and
Veo video, TTS, Lyria music, embeddings, caching, batch, thinking, safety,
Live API, or model tuning. Don't use for server-managed stateful agent
sessions (gemini-interactions-api), Managed Agent CRUD (gemini-agents-api),
raw BidiGenerateContent WebSocket scaffolding/audio debugging
(gemini-live-api), open-model SFT or tuning job management
(agent-platform-tuning, agent-platform-tuning-management), or OpenMaaS,
OpenAI SDK, numeric endpoints, and 429 DSQ debugging
(agent-platform-inference).
compatibility: Requires active Google Cloud credentials, billing enabled, and the Gemini platform API (aiplatform.googleapis.com) enabled.
---
# Gemini API in Gemini platform
> [!IMPORTANT]
> **Gemini platform** was formerly named **Gemini Enterprise Agent Platform** and **Vertex AI**.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Core Directives & Prerequisites
- **Unified Gen AI SDK ONLY**: Python `google-genai` (`pip install "google-genai>=2.33.0,<3"`), TS/JS `@google/genai` (`npm install @google/genai`), Go `google.golang.org/genai` (`go get google.golang.org/genai`), Java `com.google.genai:google-genai:2.6.0`, C# `Google.GenAI` (`dotnet add package Google.GenAI`).
- **NEVER use deprecated SDKs**: `google-cloud-aiplatform` (`vertexai`), `@google-cloud/vertexai`, `cloud.google.com/go/vertexai`, `google-cloud-vertexai`, or `google-generativeai` ([Migration Guide](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/deprecations/genai-vertexai-sdk.md.txt)).
- **Prerequisites**: Active billing ([Pricing](https://cloud.google.com/pricing)), `roles/aiplatform.user`, API enabled (`gcloud config set project {project_id}`, `gcloud services enable aiplatform.googleapis.com`), ADC (`gcloud auth application-default login`).
- **Efficiency**: Model IDs and SDK signatures here and in `references/` are verified against the current SDK. Respond directly if answered below; otherwise read **only** the matching line range in [Reference Routing](#reference-routing) without reading unrelated references or running speculative repo/web searches unless inspecting user files or unlisted APIs.
## Authentication & Python Quick Start
Prefer environment variables ([GCP Auth](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/start/gcp-auth.md.txt), [Locations](https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations.md.txt), [Express Mode](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/start/api-keys.md.txt)):
```bash
# ADC ('global' default; Live API and Tuning require regional, e.g. 'us-central1')
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='global'
export GOOGLE_GENAI_USE_ENTERPRISE=true
# Express Mode API key (mutually exclusive with project/location — unset GOOGLE_CLOUD_PROJECT & GOOGLE_CLOUD_LOCATION):
# export GOOGLE_API_KEY='your-api-key' GOOGLE_GENAI_USE_ENTERPRISE=true
# Explicit Express Mode: enterprise=True+api_key (Py); enterprise:true+apiKey (TS/Java/C#); BackendEnterprise+APIKey (Go) — omit project/location
```
```python
from google import genai
from google.genai import types # Only needed when passing optional config
# Zero-arg Client() reads env vars; explicit: genai.Client(enterprise=True, project="your-project-id", location="global")
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Explain quantum computing",
# Optional config:
# config=types.GenerateContentConfig(
# system_instruction="Be concise.",
# max_output_tokens=256,
# ),
)
print(response.text)
```
## Models
> [!WARNING]
> **NEVER** recommend deprecated models: `gemini-2.5-*`, `gemini-2.0-*`, `gemini-1.5-*`, `gemini-1.0-*`, `gemini-pro*`, `gemini-pro-vision`, `text-embedding-004`, `multimodal-embedding-001`, `imagen-3.0*`.
| Capability | Recommended Model(s) | Notes |
| :--- | :--- | :--- |
| General text, multimodal, coding, agents | `gemini-4-hydrogen` | Default; 1M ctx, fast & balanced |
| Complex reasoning & enterprise SWE | `gemini-4-neon` | 1M ctx, long-term GA, broad regions |
| Frontier reasoning, security & research | `gemini-4-carbon` | Max reasoning depth; 1M ctx, select regions |
| High-frequency / lightweight tasks | `gemini-3.5-flash-lite` | Low latency & cost; 1M ctx |
| Text & multimodal embeddings | `gemini-embedding-2` | Shared space: text, image, PDF, audio, video |
| Image generation & editing | `gemini-nano-banana-2.1`, `gemini-3.1-flash-lite-image` | Pro/high-res (2.1) or fast Lite |
| Video generation & editing (Omni) | `gemini-omni-1.2-flash` | Up to 4K + audio via `client.interactions.create` |
| Video generation (Veo async) | `veo-3.1-fast-generate-001` | Default fast; also `veo-3.1-lite-generate-001`, `veo-3.1-generate-001` |
| Live bidirectional audio/video | `gemini-3.8-live` | `client.aio.live.connect` (regional endpoint) |
| Text-to-Speech (TTS) | `gemini-3.8-flash-tts`, `gemini-3.8-flash-lite-tts` | Studio (132 langs) or low-latency (103 langs) |
| Music generation | `lyria-3-pro-preview`, `lyria-3-clip-preview`, `lyria-002` | `<=184s` / `30s` (`interactions.create`); `lyria-002` (GA `:predict`) |
**Use ONLY if explicitly requested** (or required by feature): `gemini-4-argon`, `gemini-3.8-flash` (explicit context caching), `gemini-3.1-pro-preview`, `gemini-3.7-flash`, `gemini-3.6-flash`, `gemini-3.5-flash`, `gemini-3.1-flash-lite` (SFT tuning), `gemini-3-pro-image`, `gemini-3.1-flash-image`.
## Reference Routing
| Task | Reference & Line Range |
| :--- | :--- |
| TS/JS (`L12-L32`), Go (`L34-L67`), Java (`L69-L102`), C# (`L104-L123`) | [references/sdks.md](references/sdks.md) |
| Chat (`L11-L26`), streaming (`L28-L38`), multimodal/`media_resolution` (`L40-L89`), async `client.aio` (`L91-L111`), `count_tokens`/usage (`L113-L133`) | [references/text_and_multimodal.md](references/text_and_multimodal.md) |
| JSON schema (`L10-L36`), function calling (`L38-L92`), Search & Agent Search grounding (`L94-L132`), code exec & URL context (`L134-L161`) | [references/structured_and_tools.md](references/structured_and_tools.md) |
| Nano Banana images (`L11-L53`), Omni t2v (`L55-L92`), Omni i2v/ref/edit/async/multi-turn (`L55-L155`), Veo (`L157-L187`), TTS single/multi-speaker (`L189-L268`), Lyria (`L270-L291`) | [references/media_generation.md](references/media_generation.md) |
| Text, image, and segmented video embeddings (`EmbedContentConfig`) | [references/embeddings.md](references/embeddings.md) |
| Explicit caching (`L10-L47`), batch (`L49-L74`), thinking (`L76-L108`), MCP tools (`L110-L138`) | [references/advanced_features.md](references/advanced_features.md) |
| Safety filters (`HarmCategory`, `HarmBlockThreshold`) & ratings | [references/safety.md](references/safety.md) |
| Bounding box detection (`[y_min, x_min, y_max, x_max]`, `0-1000`) | [references/bounding_box.md](references/bounding_box.md) |
| Live API WebSockets (`client.aio.live.connect`, PCM audio) | [references/live_api.md](references/live_api.md) |
| Supervised Fine-Tuning (SFT) & Preference Tuning (`client.tunings.tune`) | [references/model_tuning.md](references/model_tuning.md) |
## Official Docs & Endpoints
- [Gemini platform Overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/overview.md.txt) | [REST Reference](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest.md.txt) (global: `https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT}/locations/global/publishers/google/models/{MODEL}:generateContent`; regional: `https://{LOCATION}-aiplatform.googleapis.com/...`) | [Python Samples](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/genai)
- If `search_documents` / `get_document` (Developer Knowledge MCP) are available, query them when unlisted API details are needed.
advanced_features.md 4.6 KB
# Advanced Features
## Contents
- [Content Caching](#content-caching) (L10-L47)
- [Batch Prediction](#batch-prediction) (L49-L74)
- [Thinking (Reasoning)](#thinking-reasoning) (L76-L108)
- [Model Context Protocol (MCP) Support (Experimental)](#model-context-protocol-mcp-support-experimental) (L110-L138)
## Content Caching
Implicit caching is enabled automatically on supported Gemini models and saves cost on repeated prefixes without extra setup. Use **explicit caching** (`client.caches.create`) only when explicitly requested:
- Explicit caching is **not supported** on `gemini-4-carbon`, `gemini-4-neon`, `gemini-4-argon`, or `gemini-4-hydrogen`; use a supported model such as `gemini-3.8-flash` (and do not use deprecated `gemini-1.5-*` or `gemini-pro` models).
```python
from google import genai
from google.genai import types
client = genai.Client()
content_cache = client.caches.create(
model="gemini-3.8-flash",
config=types.CreateCachedContentConfig(
contents=[
types.Content(
role="user",
parts=[
types.Part.from_uri(
file_uri="gs://your-bucket/large.pdf",
mime_type="application/pdf",
)
],
)
],
system_instruction="You are an expert researcher.",
display_name="example-cache",
ttl="86400s",
),
)
response = client.models.generate_content(
model="gemini-3.8-flash",
contents="Summarize the key findings in the PDF.",
config=types.GenerateContentConfig(cached_content=content_cache.name),
)
print(response.text)
```
## Batch Prediction
Process large JSONL or BigQuery datasets asynchronously with `client.batches.create`.
```python
import time
from google import genai
from google.genai import types
client = genai.Client()
job = client.batches.create(
model="gemini-4-hydrogen",
src="gs://your-bucket/prompts.jsonl",
config=types.CreateBatchJobConfig(dest="gs://your-bucket/outputs"),
)
terminal_states = {
types.JobState.JOB_STATE_SUCCEEDED,
types.JobState.JOB_STATE_FAILED,
types.JobState.JOB_STATE_CANCELLED,
}
while job.state not in terminal_states:
time.sleep(30)
job = client.batches.get(name=job.name)
```
## Thinking (Reasoning)
Thinking is enabled by default (`MEDIUM` on `gemini-4-carbon` and `gemini-4-argon`; `HIGH` on `gemini-4-hydrogen` and `gemini-4-neon`; `MINIMAL` on `gemini-3.5-flash-lite`). Configure depth and thought summaries via `types.ThinkingConfig`:
- **`MINIMAL`**: Lowest thinking budget for simple tasks (**not supported** on `gemini-4-carbon`, `gemini-4-neon`, `gemini-4-argon`, or `gemini-4-hydrogen`).
- **`LOW`**: Light reasoning with low latency.
- **`MEDIUM`**: Balanced reasoning for moderate multi-step tasks.
- **`HIGH`**: Deep reasoning for complex coding, architecture, math, and research.
- **`XHIGH`**: Maximum reasoning depth on supported models (such as `gemini-4-hydrogen`).
- **`include_thoughts=True`**: Required in `ThinkingConfig` when reading `part.thought` summaries from response parts.
```python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-carbon",
contents="Design a zero-trust mTLS rotation protocol with zero downtime.",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level=types.ThinkingLevel.HIGH,
include_thoughts=True,
)
),
)
for part in response.candidates[0].content.parts:
if part.thought:
print(f"Thought Summary: {part.text}")
elif part.text:
print(f"Final Answer: {part.text}")
```
## Model Context Protocol (MCP) Support (Experimental)
Pass an initialized `mcp.ClientSession` directly in `tools=[session]` to `client.aio.models.generate_content` for automatic MCP tool execution.
```python
import asyncio
from google import genai
from google.genai import types
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
client = genai.Client()
server_params = StdioServerParameters(command="npx", args=["-y", "@philschmid/weather-mcp"])
async def run() -> None:
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
response = await client.aio.models.generate_content(
model="gemini-4-hydrogen",
contents="What is the current weather in London?",
config=types.GenerateContentConfig(tools=[session]),
)
print(response.text)
asyncio.run(run())
```
attribution.md 1.8 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gemini-api)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:gemini-api)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:gemini-api)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
bounding_box.md 1.8 KB
# Bounding Box Detection
Detect and localize objects within images or videos using bounding boxes. The model returns coordinates in the format `[y_min, x_min, y_max, x_max]`, normalized from 0 to 1000.
## Implementation (Python)
To ensure structured output, define a `BoundingBox` class and provide it as the `response_schema`.
```python
from google import genai
from google.genai.types import (
GenerateContentConfig,
Part,
)
from pydantic import BaseModel
# Define the schema for the bounding box
class BoundingBox(BaseModel):
box_2d: list[int]
label: str
client = genai.Client()
config = GenerateContentConfig(
system_instruction="""
Return bounding boxes as an array with labels.
Never return masks. Limit to 25 objects.
""",
response_mime_type="application/json",
response_schema=list[BoundingBox],
)
image_uri = "gs://cloud-samples-data/generative-ai/image/socks.jpg"
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[
Part.from_uri(file_uri=image_uri, mime_type="image/jpeg"),
"Detect the socks in the image and provide bounding boxes.",
],
config=config,
)
# Access the detected boxes
for bbox in response.parsed:
print(f"Label: {bbox.label}, Box: {bbox.box_2d}")
```
## Coordinate System
- **Format**: `[y_min, x_min, y_max, x_max]`
- **Normalization**: Coordinates are integers from `0` to `1000`.
- **Origin**: `[0, 0]` is the top-left corner of the image.
## Visualization Helper
To visualize the results, scale the normalized coordinates back to the original image dimensions.
```python
def scale_box(box_2d, width, height):
y_min, x_min, y_max, x_max = box_2d
return [
int(y_min / 1000 * height),
int(x_min / 1000 * width),
int(y_max / 1000 * height),
int(x_max / 1000 * width),
]
```
embeddings.md 2.4 KB
# Text and Multimodal Embeddings
Generate embeddings across text, images, documents, audio, and video in a single shared semantic space using `gemini-embedding-2` and `client.models.embed_content`. Do not use deprecated legacy models (`text-embedding-004`, `multimodal-embedding-001`, `multimodalembedding@001`).
**Key `types.EmbedContentConfig` options**:
- `output_dimensionality` (`int`, e.g., `768`, `1536`, `3072`): Truncates output vectors to the target dimension.
- `task_type` (`str`): e.g., `"RETRIEVAL_DOCUMENT"`, `"RETRIEVAL_QUERY"`, `"SEMANTIC_SIMILARITY"`, `"CLASSIFICATION"`, `"CLUSTERING"`.
- `title` (`str`): Optional document title (valid only when `task_type="RETRIEVAL_DOCUMENT"`).
- `auto_truncate` (`bool`), `document_ocr` (`bool`), `audio_track_extraction` (`bool`): Gemini platform controls for long inputs, PDFs, and video audio tracks.
```python
from google import genai
from google.genai import types
client = genai.Client()
# 1. Text embeddings (batch list of strings)
text_resp = client.models.embed_content(
model="gemini-embedding-2",
contents=[
"How do I get a driver's license?",
"How long is my driver's license valid?",
],
config=types.EmbedContentConfig(
task_type="RETRIEVAL_DOCUMENT",
output_dimensionality=768,
),
)
text_vectors = [emb.values for emb in text_resp.embeddings]
# 2. Image embedding from Cloud Storage (or use types.Part.from_bytes for local files)
image_resp = client.models.embed_content(
model="gemini-embedding-2",
contents=types.Part.from_uri(
file_uri="gs://your-bucket/product.jpg",
mime_type="image/jpeg",
),
config=types.EmbedContentConfig(output_dimensionality=768),
)
image_vector = image_resp.embeddings[0].values
# 3. Video embeddings (returns one embedding vector per processed video segment)
video_resp = client.models.embed_content(
model="gemini-embedding-2",
contents=types.Part.from_uri(
file_uri="gs://your-bucket/video.mp4",
mime_type="video/mp4",
),
config=types.EmbedContentConfig(output_dimensionality=768),
)
video_segment_vectors = [emb.values for emb in video_resp.embeddings]
```
Because text, image, and video vectors share the same embedding space, compute cosine similarity or dot products directly across modalities (for example, matching a `"RETRIEVAL_QUERY"` text vector against stored image or video segment vectors).
live_api.md 1.8 KB
# Live API
Stream low-latency bidirectional voice, video, and text over WebSockets using `gemini-3.8-live` and `client.aio.live.connect`.
- **Regional endpoint required**: Live API on Gemini platform requires a regional endpoint (for example, `location="us-central1"`), not `location="global"`.
- **Realtime chunks**: Pass exactly one keyword argument per `session.send_realtime_input(...)` call (`audio=types.Blob(...)` for raw 16kHz PCM audio or `media=types.Blob(...)` / PIL image for video frames).
```python
import asyncio
from google import genai
from google.genai import types
async def run_live_session(audio_bytes: bytes | None = None) -> None:
# Live API requires a regional endpoint (e.g., us-central1), not global
client = genai.Client(
enterprise=True,
project="your-project-id",
location="us-central1",
)
config = types.LiveConnectConfig(
response_modalities=[types.Modality.AUDIO], # Or types.Modality.TEXT
)
async with client.aio.live.connect(model="gemini-3.8-live", config=config) as session:
if audio_bytes is not None:
await session.send_realtime_input(
audio=types.Blob(data=audio_bytes, mime_type="audio/pcm;rate=16000")
)
else:
await session.send_client_content(
turns=types.Content(
role="user",
parts=[types.Part.from_text(text="Hello! Can you hear me?")],
),
turn_complete=True,
)
async for message in session.receive():
if message.text:
print(message.text, end="")
elif message.data:
# Raw PCM audio output bytes when Modality.AUDIO is active
pass
asyncio.run(run_live_session())
```
media_generation.md 11.1 KB
# Media Generation
## Contents
- [Image Generation and Editing (Nano Banana)](#image-generation-and-editing-nano-banana) (L11-L53)
- [Video Generation and Editing with Gemini Omni](#video-generation-and-editing-with-gemini-omni) (L55-L155)
- [Video Generation with Veo](#video-generation-with-veo) (L157-L187)
- [Text-to-Speech (TTS)](#text-to-speech-tts) (L189-L268)
- [Music Generation with Lyria](#music-generation-with-lyria) (L270-L291)
## Image Generation and Editing (Nano Banana)
Use `gemini-nano-banana-2.1` for high-resolution/pro image generation and editing, or `gemini-3.1-flash-lite-image` for fast, lightweight generation (do not use deprecated `imagen-3.0*` models). Configure `types.ImageConfig` with `aspect_ratio` (e.g., `"1:1"`, `"16:9"`, `"9:16"`, `"4:3"`, `"3:4"`) and `image_size` (`"1K"`, `"2K"`, or `"4K"`).
```python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents="A futuristic city at sunset",
config=types.GenerateContentConfig(
image_config=types.ImageConfig(aspect_ratio="16:9", image_size="2K")
),
)
for part in response.parts:
if part.text is not None:
print(part.text)
elif part.inline_data is not None:
image = part.as_image()
image.save("generated_image.png")
```
For iterative image editing, use multi-turn chat (`client.chats.create`):
```python
from google import genai
from PIL import Image
client = genai.Client()
chat = client.chats.create(model="gemini-nano-banana-2.1")
response = chat.send_message(["Add lemons and limes to this ceramic bowl", Image.open("bowl.png")])
for i, part in enumerate(response.parts):
if part.inline_data is not None:
part.as_image().save(f"edited_{i}.png")
# Continue refining in subsequent turns
followup = chat.send_message("Now change the bowl color to cobalt blue")
```
## Video Generation and Editing with Gemini Omni
`gemini-omni-1.2-flash` generates and edits video with synchronized audio at up to 4K via the **Interactions API** (`client.interactions.create` — **not** `generate_content` or `generate_videos`). Every output includes [C2PA metadata](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/content-credentials.md.txt) and a [SynthID watermark](https://deepmind.google/technologies/synthid/).
- **Task (`interactions.VideoConfig.task`)**: `"text_to_video"`, `"image_to_video"` (first frame), `"reference_to_video"` (style/subject guide images, audio, or video), `"edit"` (source video <= 15s + optional ref images), `"upscale"`, or `"extend"`.
- **Format (`interactions.VideoResponseFormat`)**: `aspect_ratio` (`"16:9"` or `"9:16"`), `duration` (`"3s"` to `"15s"`, e.g. `"10s"`), `resolution` (lowercase `"360p"`, `"720p"`, `"1080p"`, or `"4k"`), `delivery` (`"uri"` with `gcs_uri="gs://your-bucket/..."`, or omit for inline base64 bytes).
```python
import base64
import time
from google import genai
from google.genai import interactions
client = genai.Client()
omni_model = "gemini-omni-1.2-flash"
def save_video(interaction, path: str = "output.mp4") -> None:
contents = [c for step in interaction.steps if step.type == "model_output" for c in step.content]
with open(path, "wb") as f:
f.write(base64.b64decode(contents[0].data))
# 1. Text-to-video (up to 4K; set delivery="uri" + gcs_uri="gs://..." to write to GCS)
interaction = client.interactions.create(
model=omni_model,
input="A hard-shell suitcase rolling down a city street at sunset, cinematic tracking shot.",
generation_config=interactions.GenerationConfig(
video_config=interactions.VideoConfig(task="text_to_video")
),
response_format=interactions.VideoResponseFormat(
aspect_ratio="16:9",
duration="10s",
resolution="4k",
),
)
save_video(interaction)
```
```python
# 2. Image-to-video (first frame via inline base64 or {"type": "image", "mime_type": ..., "uri": "gs://..."})
with open("suitcase.png", "rb") as f:
img_b64 = base64.b64encode(f.read()).decode("utf-8")
i2v = client.interactions.create(
model=omni_model,
input=[
{"type": "text", "text": "The suitcase stands up, unzips, and travel stickers pop out."},
{"type": "image", "mime_type": "image/png", "data": img_b64},
],
generation_config=interactions.GenerationConfig(
video_config=interactions.VideoConfig(task="image_to_video")
),
)
save_video(i2v, "i2v.mp4")
# 3. Reference-to-video (multiple subject/style reference images)
ref_inputs = []
for img_path, mime in [("woman.jpeg", "image/jpeg"), ("arcade-game.png", "image/png")]:
with open(img_path, "rb") as f:
ref_inputs.append({"type": "image", "mime_type": mime, "data": base64.b64encode(f.read()).decode("utf-8")})
r2v = client.interactions.create(
model=omni_model,
input=[{"type": "text", "text": "The woman walks up to the arcade game and starts playing."}, *ref_inputs],
generation_config=interactions.GenerationConfig(
video_config=interactions.VideoConfig(task="reference_to_video")
),
response_format=interactions.VideoResponseFormat(aspect_ratio="9:16", duration="7s"),
)
save_video(r2v, "r2v.mp4")
# 4. Video editing (source video <= 15s + optional reference image)
edited = client.interactions.create(
model=omni_model,
input=[
{"type": "text", "text": "Change the dog to a cat, remove the backpack, and add a propeller hat."},
{"type": "image", "mime_type": "image/png", "uri": "gs://your-bucket/ref-cat.png"},
{"type": "video", "mime_type": "video/mp4", "uri": "gs://your-bucket/source_dog.mp4"},
],
generation_config=interactions.GenerationConfig(video_config=interactions.VideoConfig(task="edit")),
)
save_video(edited, "edited.mp4")
# 5. Async background generation & polling
bg = client.interactions.create(model=omni_model, input="Ocean waves crashing on basalt cliffs.", background=True)
while bg.status not in ("completed", "failed"):
time.sleep(10)
bg = client.interactions.get(id=bg.id)
if bg.status == "completed":
save_video(bg, "async.mp4")
# 6. Multi-turn iterative refinement (pass prior interaction.steps + new user_input)
turn2 = client.interactions.create(
model=omni_model,
input=interaction.steps + [
{"type": "user_input", "content": [{"type": "text", "text": "Restyle this video as stop-motion claymation."}]}
],
)
save_video(turn2, "turn2.mp4")
```
## Video Generation with Veo
Start with `veo-3.1-fast-generate-001` (fast, cost-efficient default) or `veo-3.1-lite-generate-001` (low-cost preview), and upgrade to `veo-3.1-generate-001` when needed. Veo runs asynchronously via `client.models.generate_videos` + `client.operations.get` (never `generate_content`).
```python
import time
from google import genai
from google.genai import types
client = genai.Client()
operation = client.models.generate_videos(
model="veo-3.1-fast-generate-001",
prompt="A cat floating in space",
# image=Image.open("first_frame.png"), # Optional starting PIL image
config=types.GenerateVideosConfig(
aspect_ratio="16:9",
duration_seconds=6, # Veo 3.1 supports 4, 6, or 8 seconds
number_of_videos=1,
person_generation="dont_allow",
output_gcs_uri="gs://your-bucket/veo-outputs",
),
)
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
if operation.response:
print(operation.result.generated_videos[0].video.uri)
```
## Text-to-Speech (TTS)
Synthesize single- or multi-speaker WAV audio with `gemini-3.8-flash-tts` (studio fidelity, 132 languages) or `gemini-3.8-flash-lite-tts` (low latency, 103 languages; requires `google-genai>=2.33.0`). Expressive style is controlled via `types.SpeechMetadata(style=...)` (plus `speaker=...` with `multi_speaker_voice_config`) and inline vocal tags (`<laugh>`, `<sigh>`, `<short pause>`).
```python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.8-flash-tts",
contents=[
types.Content(
role="user",
parts=[
types.Part(
text="Have a wonderful day! <short pause> Welcome aboard.",
speech_metadata=types.SpeechMetadata(style="cheerful and friendly"),
)
],
)
],
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
)
),
),
)
# inline_data.data contains decoded WAV bytes
with open("out.wav", "wb") as f:
f.write(response.candidates[0].content.parts[0].inline_data.data)
# Multi-speaker TTS (mutually exclusive with voice_config; provide exactly 2 speakers)
dialogue = client.models.generate_content(
model="gemini-3.8-flash-tts",
contents=[
types.Content(
role="user",
parts=[
types.Part(
text="Welcome to the show!",
speech_metadata=types.SpeechMetadata(speaker="Alex", style="cheerful"),
),
types.Part(
text="Thanks for having me.",
speech_metadata=types.SpeechMetadata(speaker="Sam", style="warm"),
),
],
)
],
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
multi_speaker_voice_config=types.MultiSpeakerVoiceConfig(
speaker_voice_configs=[
types.SpeakerVoiceConfig(
speaker="Alex",
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
),
),
types.SpeakerVoiceConfig(
speaker="Sam",
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Puck")
),
),
]
)
),
),
)
with open("dialogue.wav", "wb") as f:
f.write(dialogue.candidates[0].content.parts[0].inline_data.data)
```
## Music Generation with Lyria
Generate `audio/mp3` music from text (and optional image) prompts via `client.interactions.create` (`location="global"`) using `lyria-3-pro-preview` (full tracks up to 184s) or `lyria-3-clip-preview` (30s clips). For GA `:predict` WAV output (32.8s), use `lyria-002`.
```python
import base64
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="lyria-3-clip-preview",
input="Upbeat synthwave track with a driving bassline and retro arpeggios.",
)
for step in interaction.steps:
if step.type == "model_output":
for item in step.content:
if item.type == "audio":
with open("music.mp3", "wb") as f:
f.write(base64.b64decode(item.data))
```
model_tuning.md 2.0 KB
# Model Tuning
Run Supervised Fine-Tuning (SFT, default) or Preference Tuning on JSONL datasets in Cloud Storage using `client.tunings.tune`.
- **Endpoint location**: Tuning jobs require a regional endpoint (for example, `location="us-central1"`), not `location="global"`.
- **Supported models**: Not all models support tuning (commonly tuned base models include `gemini-3.1-flash-lite` and `gemini-3.5-flash-lite`). Check [Supervised Tuning documentation](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/tuning/supervised-tuning.md.txt) for current model and region support.
- **Key `types.CreateTuningJobConfig` options**: `tuned_model_display_name`, `epoch_count`, `learning_rate_multiplier`, `adapter_size`, `validation_dataset` (`types.TuningValidationDataset(gcs_uri=...)`), and `method` (`SUPERVISED_FINE_TUNING` or `PREFERENCE_TUNING`).
```python
import time
from google import genai
from google.genai import types
# Use a supported regional location for tuning jobs
client = genai.Client(enterprise=True, project="your-project-id", location="us-central1")
tuning_job = client.tunings.tune(
base_model="gemini-3.1-flash-lite",
training_dataset=types.TuningDataset(
gcs_uri="gs://your-bucket/sft_train_data.jsonl",
),
config=types.CreateTuningJobConfig(
tuned_model_display_name="example-tuned-model",
epoch_count=3,
),
)
running_states = {
types.JobState.JOB_STATE_QUEUED,
types.JobState.JOB_STATE_PENDING,
types.JobState.JOB_STATE_RUNNING,
}
while tuning_job.state in running_states:
time.sleep(60)
tuning_job = client.tunings.get(name=tuning_job.name)
if tuning_job.state != types.JobState.JOB_STATE_SUCCEEDED:
raise RuntimeError(f"Tuning failed with state {tuning_job.state}: {tuning_job.error}")
# Run inference by passing tuning_job.tuned_model.endpoint directly as model
response = client.models.generate_content(
model=tuning_job.tuned_model.endpoint,
contents="Why is the sky blue?",
)
print(response.text)
```
safety.md 1.8 KB
# Safety Settings and Responsible AI
You can adjust safety settings to control the thresholds for harmful content generation. Standard safety filters are applied by default.
## Adjusting Safety Thresholds
```python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Write a list of 5 disrespectful things that I might say to the universe after stubbing my toe in the dark.",
config=types.GenerateContentConfig(
system_instruction="Be as mean as possible.",
safety_settings=[
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=types.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold=types.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=types.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold=types.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
),
],
),
)
# Response will be `None` if it is blocked.
if response.text is None:
print(f"Content Blocked. Finish Reason: {response.candidates[0].finish_reason}")
else:
print(response.text)
# Inspect safety ratings for each category
for rating in response.candidates[0].safety_ratings or []:
print(f"Category: {rating.category}")
print(f"Is Blocked: {rating.blocked}")
print(f"Probability: {rating.probability}")
print(f"Severity: {rating.severity}")
```
sdks.md 3.7 KB
# Language SDK Quick Starts (TypeScript, Go, Java, C#)
## Contents
- [TypeScript / JavaScript (`@google/genai`)](#typescript--javascript-googlegenai) (L12-L32)
- [Go (`google.golang.org/genai`)](#go-googlegolangorggenai) (L34-L67)
- [Java (`com.google.genai:google-genai`)](#java-comgooglegenaigoogle-genai) (L69-L102)
- [C# / .NET (`Google.GenAI`)](#c--net-googlegenai) (L104-L123)
Set standard Gemini platform env vars (`GOOGLE_CLOUD_PROJECT`, `GOOGLE_CLOUD_LOCATION="global"`, `GOOGLE_GENAI_USE_ENTERPRISE=true`) or pass explicit client parameters as shown. For Express Mode API key auth, set `GOOGLE_API_KEY` + `GOOGLE_GENAI_USE_ENTERPRISE=true` and unset `GOOGLE_CLOUD_PROJECT`/`GOOGLE_CLOUD_LOCATION` (or pass `apiKey` in TS/Java/C#, `APIKey` in Go, alongside `enterprise`/`BackendEnterprise` without `project`/`location`). Do not use deprecated legacy packages (`@google-cloud/vertexai`, `cloud.google.com/go/vertexai`, `google-cloud-vertexai`).
## TypeScript / JavaScript (`@google/genai`)
Install: `npm install @google/genai`
```typescript
import { GoogleGenAI } from "@google/genai";
// Uses GOOGLE_GENAI_USE_ENTERPRISE, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION if no args passed:
// const ai = new GoogleGenAI();
const ai = new GoogleGenAI({
enterprise: true, // boolean flag (do not pass a nested object)
project: "your-project-id",
location: "global",
});
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: "Explain quantum computing",
});
console.log(response.text);
```
## Go (`google.golang.org/genai`)
Install: `go get google.golang.org/genai`
```go
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
// Pass nil to read GOOGLE_GENAI_USE_ENTERPRISE, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION from env.
client, err := genai.NewClient(ctx, &genai.ClientConfig{
Backend: genai.BackendEnterprise,
Project: "your-project-id",
Location: "global",
})
if err != nil {
log.Fatal(err)
}
resp, err := client.Models.GenerateContent(ctx, "gemini-4-hydrogen", genai.Text("Explain quantum computing"), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Text())
}
```
## Java (`com.google.genai:google-genai`)
Requires `2.6.0` or newer (see [Maven Central](https://central.sonatype.com/artifact/com.google.genai/google-genai/versions) for the latest `2.x` release):
- **Gradle (`build.gradle`)**: `implementation("com.google.genai:google-genai:2.6.0")`
- **Maven (`pom.xml`)**:
```xml
<dependency>
<groupId>com.google.genai</groupId>
<artifactId>google-genai</artifactId>
<version>2.6.0</version>
</dependency>
```
```java
import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;
public class GenerateTextFromTextInput {
public static void main(String[] args) {
// new Client() reads GOOGLE_GENAI_USE_ENTERPRISE, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION
Client client =
Client.builder()
.enterprise(true)
.project("your-project-id")
.location("global")
.build();
GenerateContentResponse response =
client.models.generateContent("gemini-4-hydrogen", "Explain quantum computing", null);
System.out.println(response.text());
}
}
```
## C# / .NET (`Google.GenAI`)
Install: `dotnet add package Google.GenAI`
```csharp
using Google.GenAI;
// new Client() reads GOOGLE_GENAI_USE_ENTERPRISE, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION
using var client = new Client(
enterprise: true,
project: "your-project-id",
location: "global"
);
var response = await client.Models.GenerateContentAsync(
model: "gemini-4-hydrogen",
contents: "Explain quantum computing"
);
Console.WriteLine(response.Text);
```
structured_and_tools.md 5.5 KB
# Structured Output and Tools
## Contents
- [Structured Output (JSON Schema)](#structured-output-json-schema) (L10-L36)
- [Function Calling](#function-calling) (L38-L92)
- [Search Grounding](#search-grounding) (L94-L132)
- [Code Execution & URL Context](#code-execution--url-context) (L134-L161)
## Structured Output (JSON Schema)
Enforce a JSON schema by passing a Pydantic `BaseModel` or Python type annotation (e.g., `list[Movie]`) to `response_schema` with `response_mime_type="application/json"`.
```python
from google import genai
from google.genai import types
from pydantic import BaseModel
class Recipe(BaseModel):
recipe_name: str
ingredients: list[str]
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="List a few popular cookie recipes.",
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=list[Recipe],
),
)
print(response.text) # Valid JSON string matching the schema
print(response.parsed) # Parsed list[Recipe] instances
```
## Function Calling
Declare Python functions with type annotations and docstrings in `GenerateContentConfig(tools=[...])`.
- **Automatic Function Calling (default when passing Python callables)**: `generate_content` (or `chat.send_message`) automatically executes the Python function and returns the final natural-language answer in `response.text` (leaving `response.function_calls` empty on the final turn).
- **Manual Function Calling (`response.function_calls`)**: Set `automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)` to inspect `response.function_calls`, run the function yourself, and return `types.Part.from_function_response`.
```python
from google import genai
from google.genai import types
def get_current_weather(location: str) -> str:
"""Returns the current weather for a city and state (e.g., Boston, MA)."""
return "Snowing" if "boston" in location.lower() else "Sunny"
client = genai.Client()
# Option A: Manual inspection & execution via response.function_calls
manual_config = types.GenerateContentConfig(
tools=[get_current_weather],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True),
)
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="What is the weather like in Boston?",
config=manual_config,
)
if response.function_calls:
call = response.function_calls[0]
result = get_current_weather(**dict(call.args))
followup = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[
types.Content(role="user", parts=[types.Part.from_text(text="What is the weather like in Boston?")]),
response.candidates[0].content,
types.Content(
role="user",
parts=[types.Part.from_function_response(name=call.name, response={"result": result})],
),
],
config=manual_config,
)
print(followup.text)
# Option B: Automatic execution (SDK calls get_current_weather and returns final text)
auto_response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="What is the weather like in Boston?",
config=types.GenerateContentConfig(tools=[get_current_weather]),
)
print(auto_response.text)
```
## Search Grounding
Ground responses in Google Search (or enterprise data via Agent Search, formerly Vertex AI Search) and read `grounding_metadata` from `response.candidates[0]`.
```python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="When is the next total solar eclipse in the US?",
config=types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
),
)
print(response.text)
metadata = response.candidates[0].grounding_metadata
print("Search Queries:", metadata.web_search_queries)
print("Pages:", [chunk.web.title for chunk in (metadata.grounding_chunks or []) if chunk.web])
# Ground on enterprise data via Agent Search (Vertex AI Search) datastore or engine
enterprise_resp = client.models.generate_content(
model="gemini-4-hydrogen",
contents="What is our parental leave policy?",
config=types.GenerateContentConfig(
tools=[
types.Tool(
retrieval=types.Retrieval(
vertex_ai_search=types.VertexAISearch(
datastore="projects/your-project-id/locations/global/collections/default_collection/dataStores/your-datastore-id"
)
)
)
]
),
)
print(enterprise_resp.text)
```
## Code Execution & URL Context
```python
from google import genai
from google.genai import types
client = genai.Client()
# Server-side Python code execution
code_resp = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Calculate the 20th fibonacci number.",
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution())],
),
)
print(code_resp.executable_code, code_resp.code_execution_result)
# Retrieve and ground on public web URLs supplied in the prompt
url_resp = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Compare https://example.com and https://www.iana.org/domains/reserved",
config=types.GenerateContentConfig(
tools=[types.Tool(url_context=types.UrlContext())],
),
)
print(url_resp.text, url_resp.candidates[0].url_context_metadata)
```
text_and_multimodal.md 3.7 KB
# Text and Multimodal Generation
## Contents
- [Chat (Multi-turn conversations)](#chat-multi-turn-conversations) (L11-L26)
- [Streaming (`generate_content_stream`)](#streaming-generate_content_stream) (L28-L38)
- [Multimodal Inputs (GCS URIs, Local Bytes, and YouTube URLs)](#multimodal-inputs-gcs-uris-local-bytes-and-youtube-urls) (L40-L89)
- [Async Generation (`client.aio`)](#async-generation-clientaio) (L91-L111)
- [Token Counting & Usage Metadata](#token-counting--usage-metadata) (L113-L133)
## Chat (Multi-turn conversations)
```python
from google import genai
from google.genai import types
client = genai.Client()
chat = client.chats.create(
model="gemini-4-hydrogen",
history=[
types.UserContent(parts=[types.Part.from_text(text="Hello")]),
types.ModelContent(parts=[types.Part.from_text(text="Hi! How can I help?")]),
],
)
response = chat.send_message("Tell me a short story.")
print(response.text)
```
## Streaming (`generate_content_stream`)
```python
from google import genai
client = genai.Client()
for chunk in client.models.generate_content_stream(
model="gemini-4-hydrogen", contents="Tell me a story in 300 words."
):
print(chunk.text, end="")
```
## Multimodal Inputs (GCS URIs, Local Bytes, and YouTube URLs)
Pass images, PDFs, audio, or video alongside text prompts inside `contents=[...]`:
- **Cloud Storage (`gs://...`) or public/YouTube URLs**: `types.Part.from_uri(file_uri=..., mime_type=...)`
- **Local files**: Read binary bytes (`"rb"`) and wrap in `types.Part.from_bytes(data=..., mime_type=...)`
```python
from google import genai
from google.genai import types
client = genai.Client()
gcs_image = types.Part.from_uri(
file_uri="gs://cloud-samples-data/generative-ai/image/scones.jpg",
mime_type="image/jpeg",
)
with open("local_image.jpg", "rb") as f:
local_image = types.Part.from_bytes(data=f.read(), mime_type="image/jpeg")
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[
"Compare all objects visible in both images.",
gcs_image,
local_image,
],
# Optional: control multimodal token cost (MEDIA_RESOLUTION_LOW / MEDIUM / HIGH)
# config=types.GenerateContentConfig(media_resolution=types.MediaResolution.MEDIA_RESOLUTION_LOW),
)
print(response.text)
```
### YouTube Videos
```python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[
types.Part.from_uri(
file_uri="https://www.youtube.com/watch?v=3KtWfp0UopM",
mime_type="video/mp4",
),
"Summarize the key takeaways from this video.",
],
)
print(response.text)
```
## Async Generation (`client.aio`)
Use `client.aio.models` for async frameworks (FastAPI, Cloud Run):
```python
import asyncio
from google import genai
client = genai.Client()
async def generate_async() -> None:
response = await client.aio.models.generate_content(
model="gemini-4-hydrogen",
contents="Summarize the benefits of async I/O in 2 bullets.",
)
print(response.text)
asyncio.run(generate_async())
```
## Token Counting & Usage Metadata
```python
from google import genai
client = genai.Client()
count = client.models.count_tokens(
model="gemini-4-hydrogen",
contents="Explain quantum computing",
)
print("Input tokens:", count.total_tokens)
# In async handlers, use: count = await client.aio.models.count_tokens(...)
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Explain quantum computing in one sentence.",
)
# prompt_token_count, candidates_token_count, cached_content_token_count, thoughts_token_count
print(response.usage_metadata)
```
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE