# Google Gemini Api

> |

- **Type:** Skill
- **Install:** `agentstack add skill-kgeminic-claude-skills-1-google-gemini-api`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [Kgeminic](https://agentstack.voostack.com/s/kgeminic)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [Kgeminic](https://github.com/Kgeminic)
- **Source:** https://github.com/Kgeminic/claude-skills-1/tree/main/skills/google-gemini-api

## Install

```sh
agentstack add skill-kgeminic-claude-skills-1-google-gemini-api
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## 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-embeddings` skill for text-embedding-004

---

## Table of Contents

**Phase 1 - Core Features**:
1. [Quick Start](#quick-start)
2. [Current Models (2025)](#current-models-2025)
3. [SDK vs Fetch Approaches](#sdk-vs-fetch-approaches)
4. [Text Generation](#text-generation)
5. [Streaming](#streaming)
6. [Multimodal Inputs](#multimodal-inputs)
7. [Function Calling](#function-calling)
8. [System Instructions](#system-instructions)
9. [Multi-turn Chat](#multi-turn-chat)
10. [Thinking Mode](#thinking-mode)
11. [Generation Configuration](#generation-configuration)

**Phase 2 - Advanced Features**:
12. [Context Caching](#context-caching)
13. [Code Execution](#code-execution)
14. [Grounding with Google Search](#grounding-with-google-search)

**Common Reference**:
15. [Known Issues Prevention](#known-issues-prevention)
16. [Error Handling](#error-handling)
17. [Rate Limits](#rate-limits)
18. [SDK Migration Guide](#sdk-migration-guide)
19. [Production Best Practices](#production-best-practices)

---

## Quick Start

### Installation

**CORRECT SDK:**
```bash
npm install @google/genai@1.34.0
```

**❌ WRONG (DEPRECATED):**
```bash
npm install @google/generative-ai  # DO NOT USE!
```

### Environment Setup

```bash
export GEMINI_API_KEY="..."
```

Or create `.env` file:
```
GEMINI_API_KEY=...
```

### First Text Generation (Node.js SDK)

```typescript
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)

```typescript
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)

```typescript
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)

```typescript
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

```typescript
{
  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)

```typescript
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)

```typescript
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 `streamGenerateContent` endpoint (not `generateContent`)
- 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

```typescript
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

```typescript
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

```typescript
// Video must be  part.functionCall
);

console.log(`Model wants to call ${functionCalls.length} functions in parallel`);
```

### Function Calling Modes

```typescript
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 functions
- `ANY`: Force model to call at least one function
- `NONE`: 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

```typescript
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

```typescript
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 `contents` array
- 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)

```typescript
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)

```typescript
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.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** yes
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-kgeminic-claude-skills-1-google-gemini-api
- Seller: https://agentstack.voostack.com/s/kgeminic
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
