Install
$ agentstack add skill-kgeminic-claude-skills-1-google-gemini-api ✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ● Network access Used
- ● Filesystem access Used
- ✓ Shell / process execution No
- ● Environment & secrets Used
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
About
Google Gemini API - Complete Guide
Version: 3.0.0 (14 Known Issues Added) Package: @google/genai@1.35.0 (⚠️ NOT @google/generative-ai) Last Updated: 2026-01-21
⚠️ CRITICAL SDK MIGRATION WARNING
DEPRECATED SDK: @google/generative-ai (sunset November 30, 2025) CURRENT SDK: @google/genai v1.27+
If you see code using @google/generative-ai, it's outdated!
This skill uses the correct current SDK and provides a complete migration guide.
Status
✅ Phase 1 Complete:
- ✅ Text Generation (basic + streaming)
- ✅ Multimodal Inputs (images, video, audio, PDFs)
- ✅ Function Calling (basic + parallel execution)
- ✅ System Instructions & Multi-turn Chat
- ✅ Thinking Mode Configuration
- ✅ Generation Parameters (temperature, top-p, top-k, stop sequences)
- ✅ Both Node.js SDK (@google/genai) and fetch approaches
✅ Phase 2 Complete:
- ✅ Context Caching (cost optimization with TTL-based caching)
- ✅ Code Execution (built-in Python interpreter and sandbox)
- ✅ Grounding with Google Search (real-time web information + citations)
📦 Separate Skills:
- Embeddings: See
google-gemini-embeddingsskill for text-embedding-004
Table of Contents
Phase 1 - Core Features:
- [Quick Start](#quick-start)
- [Current Models (2025)](#current-models-2025)
- [SDK vs Fetch Approaches](#sdk-vs-fetch-approaches)
- [Text Generation](#text-generation)
- [Streaming](#streaming)
- [Multimodal Inputs](#multimodal-inputs)
- [Function Calling](#function-calling)
- [System Instructions](#system-instructions)
- [Multi-turn Chat](#multi-turn-chat)
- [Thinking Mode](#thinking-mode)
- [Generation Configuration](#generation-configuration)
Phase 2 - Advanced Features:
- [Context Caching](#context-caching)
- [Code Execution](#code-execution)
- [Grounding with Google Search](#grounding-with-google-search)
Common Reference:
- [Known Issues Prevention](#known-issues-prevention)
- [Error Handling](#error-handling)
- [Rate Limits](#rate-limits)
- [SDK Migration Guide](#sdk-migration-guide)
- [Production Best Practices](#production-best-practices)
Quick Start
Installation
CORRECT SDK:
npm install @google/genai@1.34.0
❌ WRONG (DEPRECATED):
npm install @google/generative-ai # DO NOT USE!
Environment Setup
export GEMINI_API_KEY="..."
Or create .env file:
GEMINI_API_KEY=...
First Text Generation (Node.js SDK)
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Explain quantum computing in simple terms'
});
console.log(response.text);
First Text Generation (Fetch - Cloudflare Workers)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [{ parts: [{ text: 'Explain quantum computing in simple terms' }] }]
}),
}
);
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
Current Models (2025)
Gemini 3 Series (December 2025)
gemini-3-flash
- Context: 1,048,576 input tokens / 65,536 output tokens
- Status: 🆕 Generally Available (December 2025)
- Description: Google's fastest and most efficient Gemini 3 model for production workloads
- Best for: High-throughput applications, low-latency responses, cost-sensitive production
- Features: Enhanced multimodal, function calling, streaming, thinking mode
- Benchmark Performance: Matches gemini-2.5-pro quality at gemini-2.5-flash speed/cost
- Recommended for: Production use cases requiring speed + quality balance
gemini-3-pro-preview
- Context: TBD (documentation pending)
- Status: Preview release (November 18, 2025)
- Description: Google's newest and most intelligent AI model with state-of-the-art reasoning
- Best for: Most complex reasoning tasks, advanced multimodal understanding, benchmark-critical applications
- Features: Enhanced multimodal (text, image, video, audio, PDF), function calling, streaming
- Benchmark Performance: Outperforms Gemini 2.5 Pro on every major AI benchmark
- ⚠️ Preview Models Warning: Preview models have NO SLAs and can change or be deprecated with little notice. Use GA (generally available) models for production. See [Issue #13](#issue-13-preview-models-have-no-slas-and-can-change-without-warning)
Gemini 2.5 Series (General Availability - Stable)
gemini-2.5-pro
- Context: 1,048,576 input tokens / 65,536 output tokens
- Description: State-of-the-art thinking model for complex reasoning
- Best for: Code, math, STEM, complex problem-solving
- Features: Thinking mode (default on), function calling, multimodal, streaming
- Knowledge cutoff: January 2025
gemini-2.5-flash
- Context: 1,048,576 input tokens / 65,536 output tokens
- Description: Best price-performance workhorse model
- Best for: Large-scale processing, low-latency, high-volume, agentic use cases
- Features: Thinking mode (default on), function calling, multimodal, streaming
- Knowledge cutoff: January 2025
gemini-2.5-flash-lite
- Context: 1,048,576 input tokens / 65,536 output tokens
- Description: Cost-optimized, fastest 2.5 model
- Best for: High throughput, cost-sensitive applications
- Features: Thinking mode (default on), function calling, multimodal, streaming
- Knowledge cutoff: January 2025
Model Feature Matrix
| Feature | 3-Flash | 3-Pro (Preview) | 2.5-Pro | 2.5-Flash | 2.5-Flash-Lite | |---------|---------|-----------------|---------|-----------|----------------| | Thinking Mode | ✅ Default ON | TBD | ✅ Default ON | ✅ Default ON | ✅ Default ON | | Function Calling | ✅ | ✅ | ✅ | ✅ | ✅ | | Multimodal | ✅ Enhanced | ✅ Enhanced | ✅ | ✅ | ✅ | | Streaming | ✅ | ✅ | ✅ | ✅ | ✅ | | System Instructions | ✅ | ✅ | ✅ | ✅ | ✅ | | Context Window | 1,048,576 in | TBD | 1,048,576 in | 1,048,576 in | 1,048,576 in | | Output Tokens | 65,536 max | TBD | 65,536 max | 65,536 max | 65,536 max | | Status | GA | Preview | Stable | Stable | Stable |
⚠️ Context Window Correction
ACCURATE (Gemini 2.5): Gemini 2.5 models support 1,048,576 input tokens (NOT 2M!) OUTDATED: Only Gemini 1.5 Pro (previous generation) had 2M token context window GEMINI 3: Context window specifications pending official documentation
Common mistake: Claiming Gemini 2.5 has 2M tokens. It doesn't. This skill prevents this error.
SDK vs Fetch Approaches
Node.js SDK (@google/genai)
Pros:
- Type-safe with TypeScript
- Easier API (simpler syntax)
- Built-in chat helpers
- Automatic SSE parsing for streaming
- Better error handling
Cons:
- Requires Node.js or compatible runtime
- Larger bundle size
- May not work in all edge runtimes
Use when: Building Node.js apps, Next.js Server Actions/Components, or any environment with Node.js compatibility
Fetch-based (Direct REST API)
Pros:
- Works in any JavaScript environment (Cloudflare Workers, Deno, Bun, browsers)
- Minimal dependencies
- Smaller bundle size
- Full control over requests
Cons:
- More verbose syntax
- Manual SSE parsing for streaming
- No built-in chat helpers
- Manual error handling
Use when: Deploying to Cloudflare Workers, browser clients, or lightweight edge runtimes
Text Generation
Basic Text Generation (SDK)
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Write a haiku about artificial intelligence'
});
console.log(response.text);
Basic Text Generation (Fetch)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
{
parts: [
{ text: 'Write a haiku about artificial intelligence' }
]
}
]
}),
}
);
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
Response Structure
{
text: string, // Convenience accessor for text content
candidates: [
{
content: {
parts: [
{ text: string } // Generated text
],
role: string // "model"
},
finishReason: string, // "STOP" | "MAX_TOKENS" | "SAFETY" | "OTHER"
index: number
}
],
usageMetadata: {
promptTokenCount: number,
candidatesTokenCount: number,
totalTokenCount: number
}
}
Streaming
Streaming with SDK (Async Iteration)
const response = await ai.models.generateContentStream({
model: 'gemini-2.5-flash',
contents: 'Write a 200-word story about time travel'
});
for await (const chunk of response) {
process.stdout.write(chunk.text);
}
Streaming with Fetch (SSE Parsing)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [{ parts: [{ text: 'Write a 200-word story about time travel' }] }]
}),
}
);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.trim() === '' || line.startsWith('data: [DONE]')) continue;
if (!line.startsWith('data: ')) continue;
try {
const data = JSON.parse(line.slice(6));
const text = data.candidates[0]?.content?.parts[0]?.text;
if (text) {
process.stdout.write(text);
}
} catch (e) {
// Skip invalid JSON
}
}
}
Key Points:
- Use
streamGenerateContentendpoint (notgenerateContent) - Parse Server-Sent Events (SSE) format:
data: {json}\n\n - Handle incomplete chunks in buffer
- Skip empty lines and
[DONE]markers
Multimodal Inputs
Gemini 2.5 models support text + images + video + audio + PDFs in the same request.
Images (Vision)
SDK Approach
import { GoogleGenAI } from '@google/genai';
import fs from 'fs';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// From file
const imageData = fs.readFileSync('/path/to/image.jpg');
const base64Image = imageData.toString('base64');
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
{
parts: [
{ text: 'What is in this image?' },
{
inlineData: {
data: base64Image,
mimeType: 'image/jpeg'
}
}
]
}
]
});
console.log(response.text);
Fetch Approach
const imageData = fs.readFileSync('/path/to/image.jpg');
const base64Image = imageData.toString('base64');
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
{
parts: [
{ text: 'What is in this image?' },
{
inlineData: {
data: base64Image,
mimeType: 'image/jpeg'
}
}
]
}
]
}),
}
);
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
Supported Image Formats:
- JPEG (
.jpg,.jpeg) - PNG (
.png) - WebP (
.webp) - HEIC (
.heic) - HEIF (
.heif)
Max Image Size: 20MB per image
Video
// Video must be part.functionCall
);
console.log(`Model wants to call ${functionCalls.length} functions in parallel`);
Function Calling Modes
import { FunctionCallingConfigMode } from '@google/genai';
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What\'s the weather?',
config: {
tools: [{ functionDeclarations: [getCurrentWeather] }],
toolConfig: {
functionCallingConfig: {
mode: FunctionCallingConfigMode.ANY, // Force function call
// mode: FunctionCallingConfigMode.AUTO, // Model decides (default)
// mode: FunctionCallingConfigMode.NONE, // Never call functions
allowedFunctionNames: ['get_current_weather'] // Optional: restrict to specific functions
}
}
}
});
Modes:
AUTO(default): Model decides whether to call functionsANY: Force model to call at least one functionNONE: Disable function calling for this request
System Instructions
System instructions guide the model's behavior and set context. They are separate from the conversation messages.
SDK Approach
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
systemInstruction: 'You are a helpful AI assistant that always responds in the style of a pirate. Use nautical terminology and end sentences with "arrr".',
contents: 'Explain what a database is'
});
console.log(response.text);
// Output: "Ahoy there! A database be like a treasure chest..."
Fetch Approach
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
systemInstruction: {
parts: [
{ text: 'You are a helpful AI assistant that always responds in the style of a pirate.' }
]
},
contents: [
{ parts: [{ text: 'Explain what a database is' }] }
]
}),
}
);
Key Points:
- System instructions are NOT part of
contentsarray - They are set once at the top level of the request
- They persist for the entire conversation (when using multi-turn chat)
- They don't count as user or model messages
Multi-turn Chat
For conversations with history, use the SDK's chat helpers or manually manage conversation state.
SDK Chat Helpers (Recommended)
const chat = await ai.models.createChat({
model: 'gemini-2.5-flash',
systemInstruction: 'You are a helpful coding assistant.',
history: [] // Start empty or with previous messages
});
// Send first message
const response1 = await chat.sendMessage('What is TypeScript?');
console.log('Assistant:', response1.text);
// Send follow-up (context is automatically maintained)
const response2 = await chat.sendMessage('How do I install it?');
console.log('Assistant:', response2.text);
// Get full chat history
const history = chat.getHistory();
console.log('Full conversation:', history);
Manual Chat Management (Fetch)
const conversationHistory = [];
// First turn
const response1 = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
…
## Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- **Author:** [Kgeminic](https://github.com/Kgeminic)
- **Source:** [Kgeminic/claude-skills-1](https://github.com/Kgeminic/claude-skills-1)
- **License:** MIT
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet — be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.