Receber por email
← Voltar para o catálogo

google-gemini-api

Complete guide for Google Gemini API using the CORRECT current SDK (@google/genai v1.27+, NOT the deprecated @google/generative-ai). Covers text generation, multimodal inputs (text + images + video + audio + PDFs), function calling, thinking mode, streaming, and system instructions with accurate 2025 model information (Gemini 2.5 Pro/Flash/Flash-Lite with 1M input tokens, NOT 2M). Use when: integr

15estrelas
Atualizado há 11 meses

Ver no GitHub ↗ Licença: MIT

Como adicionar

/plugin marketplace add jackspace/ClaudeSkillz

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/google-gemini-api/svg)](https://www.skillteca.com.br/skills/google-gemini-api)

Skills relacionadas

Ver todas de Documentos →

Alerta por categoria

Receba novas skills de Documentos toda segunda

1 email curto, só com as skills novas de Documentos. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

Google Gemini API - Complete Guide

Version: Phase 2 Complete ✅ Package: @google/genai@1.27.0 (⚠️ NOT @google/generative-ai) Last Updated: 2025-10-25

⚠️ 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:

  1. [Context Caching](#context-caching)
  2. [Code Execution](#code-execution)
  3. [Grounding with Google Search](#grounding-with-google-search)

Common Reference:

  1. [Error Handling](#error-handling)
  2. [Rate Limits](#rate-limits)
  3. [SDK Migration Guide](#sdk-migration-guide)
  4. [Production Best Practices](#production-best-practices)

Quick Start

Installation

CORRECT SDK:

npm install @google/genai@1.27.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 2.5 Series (General Availability)

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 | Pro | Flash | Flash-Lite | |---------|-----|-------|------------| | Thinking Mode | ✅ Default ON | ✅ Default ON | ✅ Default ON | | Function Calling | ✅ | ✅ | ✅ | | Multimodal | ✅ | ✅ | ✅ | | Streaming | ✅ | ✅ | ✅ | | System Instructions | ✅ | ✅ | ✅ | | Context Window | 1,048,576 in | 1,048,576 in | 1,048,576 in | | Output Tokens | 65,536 max | 65,536 max | 65,536 max |

⚠️ Context Window Correction

ACCURATE: 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

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
Compartilhar X LinkedIn