[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AMA73MSC415514629SP1MG":3,"skill-same:01M7AMA73MSC415514629SP1MG":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":5,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M7AMA73MSC415514629SP1MG","google-gemini-api",null,"Complete guide for Google Gemini API using the CORRECT current SDK (@google\u002Fgenai v1.27+, NOT the\ndeprecated @google\u002Fgenerative-ai). Covers text generation, multimodal inputs (text + images + video +\naudio + PDFs), function calling, thinking mode, streaming, and system instructions with accurate 2025\nmodel information (Gemini 2.5 Pro\u002FFlash\u002FFlash-Lite with 1M input tokens, NOT 2M).\n\nUse when: integrating Gemini API, implementing multimodal AI applications, using thinking mode for\ncomplex reasoning, function calling with parallel execution, streaming responses, deploying to\nCloudflare Workers, building chat applications, or encountering SDK deprecation warnings, context window\nerrors, model not found errors, function calling failures, or multimodal format errors.\n\nKeywords: gemini api, @google\u002Fgenai, gemini-2.5-pro, gemini-2.5-flash, gemini-2.5-flash-lite,\nmultimodal gemini, thinking mode, google ai, genai sdk, function calling gemini, streaming gemini,\ngemini vision, gemini video, gemini audio, gemini pdf, system instructions, multi-turn chat,\nDEPRECATED @google\u002Fgenerative-ai, gemini context window, gemini models 2025, gemini 1m tokens,\ngemini tool use, parallel function calling, compositional function calling","davidanthonyn\u002Fagent-skills","davidanthonyn","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F55152980?v=4","01M7AJ4MY8S5C2RJCGX6626J0G","01M7AJ4MZB7EC7CAP27ANCSE7N",1,"MIT","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fgoogle-gemini-api\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: google-gemini-api\ndescription: |\n  Complete guide for Google Gemini API using the CORRECT current SDK (@google\u002Fgenai v1.27+, NOT the\n  deprecated @google\u002Fgenerative-ai). Covers text generation, multimodal inputs (text + images + video +\n  audio + PDFs), function calling, thinking mode, streaming, and system instructions with accurate 2025\n  model information (Gemini 2.5 Pro\u002FFlash\u002FFlash-Lite with 1M input tokens, NOT 2M).\n\n  Use when: integrating Gemini API, implementing multimodal AI applications, using thinking mode for\n  complex reasoning, function calling with parallel execution, streaming responses, deploying to\n  Cloudflare Workers, building chat applications, or encountering SDK deprecation warnings, context window\n  errors, model not found errors, function calling failures, or multimodal format errors.\n\n  Keywords: gemini api, @google\u002Fgenai, gemini-2.5-pro, gemini-2.5-flash, gemini-2.5-flash-lite,\n  multimodal gemini, thinking mode, google ai, genai sdk, function calling gemini, streaming gemini,\n  gemini vision, gemini video, gemini audio, gemini pdf, system instructions, multi-turn chat,\n  DEPRECATED @google\u002Fgenerative-ai, gemini context window, gemini models 2025, gemini 1m tokens,\n  gemini tool use, parallel function calling, compositional function calling\nlicense: MIT\n---\n\n# Google Gemini API - Complete Guide\n\n**Version**: Phase 2 Complete ✅\n**Package**: @google\u002Fgenai@1.27.0 (⚠️ NOT @google\u002Fgenerative-ai)\n**Last Updated**: 2025-10-25\n\n---\n\n## ⚠️ CRITICAL SDK MIGRATION WARNING\n\n**DEPRECATED SDK**: `@google\u002Fgenerative-ai` (sunset November 30, 2025)\n**CURRENT SDK**: `@google\u002Fgenai` v1.27+\n\n**If you see code using `@google\u002Fgenerative-ai`, it's outdated!**\n\nThis skill uses the **correct current SDK** and provides a complete migration guide.\n\n---\n\n## Status\n\n**✅ Phase 1 Complete**:\n- ✅ Text Generation (basic + streaming)\n- ✅ Multimodal Inputs (images, video, audio, PDFs)\n- ✅ Function Calling (basic + parallel execution)\n- ✅ System Instructions & Multi-turn Chat\n- ✅ Thinking Mode Configuration\n- ✅ Generation Parameters (temperature, top-p, top-k, stop sequences)\n- ✅ Both Node.js SDK (@google\u002Fgenai) and fetch approaches\n\n**✅ Phase 2 Complete**:\n- ✅ Context Caching (cost optimization with TTL-based caching)\n- ✅ Code Execution (built-in Python interpreter and sandbox)\n- ✅ Grounding with Google Search (real-time web information + citations)\n\n**📦 Separate Skills**:\n- **Embeddings**: See `google-gemini-embeddings` skill for text-embedding-004\n\n---\n\n## Table of Contents\n\n**Phase 1 - Core Features**:\n1. [Quick Start](#quick-start)\n2. [Current Models (2025)](#current-models-2025)\n3. [SDK vs Fetch Approaches](#sdk-vs-fetch-approaches)\n4. [Text Generation](#text-generation)\n5. [Streaming](#streaming)\n6. [Multimodal Inputs](#multimodal-inputs)\n7. [Function Calling](#function-calling)\n8. [System Instructions](#system-instructions)\n9. [Multi-turn Chat](#multi-turn-chat)\n10. [Thinking Mode](#thinking-mode)\n11. [Generation Configuration](#generation-configuration)\n\n**Phase 2 - Advanced Features**:\n12. [Context Caching](#context-caching)\n13. [Code Execution](#code-execution)\n14. [Grounding with Google Search](#grounding-with-google-search)\n\n**Common Reference**:\n15. [Error Handling](#error-handling)\n16. [Rate Limits](#rate-limits)\n17. [SDK Migration Guide](#sdk-migration-guide)\n18. [Production Best Practices](#production-best-practices)\n\n---\n\n## Quick Start\n\n### Installation\n\n**CORRECT SDK:**\n```bash\nnpm install @google\u002Fgenai@1.27.0\n```\n\n**❌ WRONG (DEPRECATED):**\n```bash\nnpm install @google\u002Fgenerative-ai  # DO NOT USE!\n```\n\n### Environment Setup\n\n```bash\nexport GEMINI_API_KEY=\"...\"\n```\n\nOr create `.env` file:\n```\nGEMINI_API_KEY=...\n```\n\n### First Text Generation (Node.js SDK)\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Explain quantum computing in simple terms'\n});\n\nconsole.log(response.text);\n```\n\n### First Text Generation (Fetch - Cloudflare Workers)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [{ parts: [{ text: 'Explain quantum computing in simple terms' }] }]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n```\n\n---\n\n## Current Models (2025)\n\n### Gemini 2.5 Series (General Availability)\n\n#### gemini-2.5-pro\n- **Context**: 1,048,576 input tokens \u002F 65,536 output tokens\n- **Description**: State-of-the-art thinking model for complex reasoning\n- **Best for**: Code, math, STEM, complex problem-solving\n- **Features**: Thinking mode (default on), function calling, multimodal, streaming\n- **Knowledge cutoff**: January 2025\n\n#### gemini-2.5-flash\n- **Context**: 1,048,576 input tokens \u002F 65,536 output tokens\n- **Description**: Best price-performance workhorse model\n- **Best for**: Large-scale processing, low-latency, high-volume, agentic use cases\n- **Features**: Thinking mode (default on), function calling, multimodal, streaming\n- **Knowledge cutoff**: January 2025\n\n#### gemini-2.5-flash-lite\n- **Context**: 1,048,576 input tokens \u002F 65,536 output tokens\n- **Description**: Cost-optimized, fastest 2.5 model\n- **Best for**: High throughput, cost-sensitive applications\n- **Features**: Thinking mode (default on), function calling, multimodal, streaming\n- **Knowledge cutoff**: January 2025\n\n### Model Feature Matrix\n\n| Feature | Pro | Flash | Flash-Lite |\n|---------|-----|-------|------------|\n| Thinking Mode | ✅ Default ON | ✅ Default ON | ✅ Default ON |\n| Function Calling | ✅ | ✅ | ✅ |\n| Multimodal | ✅ | ✅ | ✅ |\n| Streaming | ✅ | ✅ | ✅ |\n| System Instructions | ✅ | ✅ | ✅ |\n| Context Window | 1,048,576 in | 1,048,576 in | 1,048,576 in |\n| Output Tokens | 65,536 max | 65,536 max | 65,536 max |\n\n### ⚠️ Context Window Correction\n\n**ACCURATE**: Gemini 2.5 models support **1,048,576 input tokens** (NOT 2M!)\n**OUTDATED**: Only Gemini 1.5 Pro (previous generation) had 2M token context window\n\n**Common mistake**: Claiming Gemini 2.5 has 2M tokens. It doesn't. This skill prevents this error.\n\n---\n\n## SDK vs Fetch Approaches\n\n### Node.js SDK (@google\u002Fgenai)\n\n**Pros:**\n- Type-safe with TypeScript\n- Easier API (simpler syntax)\n- Built-in chat helpers\n- Automatic SSE parsing for streaming\n- Better error handling\n\n**Cons:**\n- Requires Node.js or compatible runtime\n- Larger bundle size\n- May not work in all edge runtimes\n\n**Use when:** Building Node.js apps, Next.js Server Actions\u002FComponents, or any environment with Node.js compatibility\n\n### Fetch-based (Direct REST API)\n\n**Pros:**\n- Works in **any** JavaScript environment (Cloudflare Workers, Deno, Bun, browsers)\n- Minimal dependencies\n- Smaller bundle size\n- Full control over requests\n\n**Cons:**\n- More verbose syntax\n- Manual SSE parsing for streaming\n- No built-in chat helpers\n- Manual error handling\n\n**Use when:** Deploying to Cloudflare Workers, browser clients, or lightweight edge runtimes\n\n---\n\n## Text Generation\n\n### Basic Text Generation (SDK)\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Write a haiku about artificial intelligence'\n});\n\nconsole.log(response.text);\n```\n\n### Basic Text Generation (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        {\n          parts: [\n            { text: 'Write a haiku about artificial intelligence' }\n          ]\n        }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n```\n\n### Response Structure\n\n```typescript\n{\n  text: string,                  \u002F\u002F Convenience accessor for text content\n  candidates: [\n    {\n      content: {\n        parts: [\n          { text: string }       \u002F\u002F Generated text\n        ],\n        role: string             \u002F\u002F \"model\"\n      },\n      finishReason: string,      \u002F\u002F \"STOP\" | \"MAX_TOKENS\" | \"SAFETY\" | \"OTHER\"\n      index: number\n    }\n  ],\n  usageMetadata: {\n    promptTokenCount: number,\n    candidatesTokenCount: number,\n    totalTokenCount: number\n  }\n}\n```\n\n---\n\n## Streaming\n\n### Streaming with SDK (Async Iteration)\n\n```typescript\nconst response = await ai.models.generateContentStream({\n  model: 'gemini-2.5-flash',\n  contents: 'Write a 200-word story about time travel'\n});\n\nfor await (const chunk of response) {\n  process.stdout.write(chunk.text);\n}\n```\n\n### Streaming with Fetch (SSE Parsing)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:streamGenerateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [{ parts: [{ text: 'Write a 200-word story about time travel' }] }]\n    }),\n  }\n);\n\nconst reader = response.body.getReader();\nconst decoder = new TextDecoder();\nlet buffer = '';\n\nwhile (true) {\n  const { done, value } = await reader.read();\n  if (done) break;\n\n  buffer += decoder.decode(value, { stream: true });\n  const lines = buffer.split('\\n');\n  buffer = lines.pop() || '';\n\n  for (const line of lines) {\n    if (line.trim() === '' || line.startsWith('data: [DONE]')) continue;\n    if (!line.startsWith('data: ')) continue;\n\n    try {\n      const data = JSON.parse(line.slice(6));\n      const text = data.candidates[0]?.content?.parts[0]?.text;\n      if (text) {\n        process.stdout.write(text);\n      }\n    } catch (e) {\n      \u002F\u002F Skip invalid JSON\n    }\n  }\n}\n```\n\n**Key Points:**\n- Use `streamGenerateContent` endpoint (not `generateContent`)\n- Parse Server-Sent Events (SSE) format: `data: {json}\\n\\n`\n- Handle incomplete chunks in buffer\n- Skip empty lines and `[DONE]` markers\n\n---\n\n## Multimodal Inputs\n\nGemini 2.5 models support text + images + video + audio + PDFs in the same request.\n\n### Images (Vision)\n\n#### SDK Approach\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\nimport fs from 'fs';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\n\u002F\u002F From file\nconst imageData = fs.readFileSync('\u002Fpath\u002Fto\u002Fimage.jpg');\nconst base64Image = imageData.toString('base64');\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'What is in this image?' },\n        {\n          inlineData: {\n            data: base64Image,\n            mimeType: 'image\u002Fjpeg'\n          }\n        }\n      ]\n    }\n  ]\n});\n\nconsole.log(response.text);\n```\n\n#### Fetch Approach\n\n```typescript\nconst imageData = fs.readFileSync('\u002Fpath\u002Fto\u002Fimage.jpg');\nconst base64Image = imageData.toString('base64');\n\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        {\n          parts: [\n            { text: 'What is in this image?' },\n            {\n              inlineData: {\n                data: base64Image,\n                mimeType: 'image\u002Fjpeg'\n              }\n            }\n          ]\n        }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n```\n\n**Supported Image Formats:**\n- JPEG (`.jpg`, `.jpeg`)\n- PNG (`.png`)\n- WebP (`.webp`)\n- HEIC (`.heic`)\n- HEIF (`.heif`)\n\n**Max Image Size**: 20MB per image\n\n### Video\n\n```typescript\n\u002F\u002F Video must be \u003C 2 minutes for inline data\nconst videoData = fs.readFileSync('\u002Fpath\u002Fto\u002Fvideo.mp4');\nconst base64Video = videoData.toString('base64');\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'Describe what happens in this video' },\n        {\n          inlineData: {\n            data: base64Video,\n            mimeType: 'video\u002Fmp4'\n          }\n        }\n      ]\n    }\n  ]\n});\n\nconsole.log(response.text);\n```\n\n**Supported Video Formats:**\n- MP4 (`.mp4`)\n- MPEG (`.mpeg`)\n- MOV (`.mov`)\n- AVI (`.avi`)\n- FLV (`.flv`)\n- MPG (`.mpg`)\n- WebM (`.webm`)\n- WMV (`.wmv`)\n\n**Max Video Length (inline)**: 2 minutes\n**Max Video Size**: 2GB (use File API for larger files - Phase 2)\n\n### Audio\n\n```typescript\nconst audioData = fs.readFileSync('\u002Fpath\u002Fto\u002Faudio.mp3');\nconst base64Audio = audioData.toString('base64');\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'Transcribe and summarize this audio' },\n        {\n          inlineData: {\n            data: base64Audio,\n            mimeType: 'audio\u002Fmp3'\n          }\n        }\n      ]\n    }\n  ]\n});\n\nconsole.log(response.text);\n```\n\n**Supported Audio Formats:**\n- MP3 (`.mp3`)\n- WAV (`.wav`)\n- FLAC (`.flac`)\n- AAC (`.aac`)\n- OGG (`.ogg`)\n- OPUS (`.opus`)\n\n**Max Audio Size**: 20MB\n\n### PDFs\n\n```typescript\nconst pdfData = fs.readFileSync('\u002Fpath\u002Fto\u002Fdocument.pdf');\nconst base64Pdf = pdfData.toString('base64');\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'Summarize the key points in this PDF' },\n        {\n          inlineData: {\n            data: base64Pdf,\n            mimeType: 'application\u002Fpdf'\n          }\n        }\n      ]\n    }\n  ]\n});\n\nconsole.log(response.text);\n```\n\n**Max PDF Size**: 30MB\n**PDF Limitations**: Text-based PDFs work best; scanned images may have lower accuracy\n\n### Multiple Inputs\n\nYou can combine multiple modalities in one request:\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'Compare these two images and describe the differences:' },\n        { inlineData: { data: base64Image1, mimeType: 'image\u002Fjpeg' } },\n        { inlineData: { data: base64Image2, mimeType: 'image\u002Fjpeg' } }\n      ]\n    }\n  ]\n});\n```\n\n---\n\n## Function Calling\n\nGemini supports function calling (tool use) to connect models with external APIs and systems.\n\n### Basic Function Calling (SDK)\n\n```typescript\nimport { GoogleGenAI, FunctionCallingConfigMode } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\n\u002F\u002F Define function declarations\nconst getCurrentWeather = {\n  name: 'get_current_weather',\n  description: 'Get the current weather for a location',\n  parametersJsonSchema: {\n    type: 'object',\n    properties: {\n      location: {\n        type: 'string',\n        description: 'City name, e.g. San Francisco'\n      },\n      unit: {\n        type: 'string',\n        enum: ['celsius', 'fahrenheit']\n      }\n    },\n    required: ['location']\n  }\n};\n\n\u002F\u002F Make request with tools\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What\\'s the weather in Tokyo?',\n  config: {\n    tools: [\n      { functionDeclarations: [getCurrentWeather] }\n    ]\n  }\n});\n\n\u002F\u002F Check if model wants to call a function\nconst functionCall = response.candidates[0].content.parts[0].functionCall;\n\nif (functionCall) {\n  console.log('Function to call:', functionCall.name);\n  console.log('Arguments:', functionCall.args);\n\n  \u002F\u002F Execute the function (your implementation)\n  const weatherData = await fetchWeather(functionCall.args.location);\n\n  \u002F\u002F Send function result back to model\n  const finalResponse = await ai.models.generateContent({\n    model: 'gemini-2.5-flash',\n    contents: [\n      'What\\'s the weather in Tokyo?',\n      response.candidates[0].content, \u002F\u002F Original assistant response with function call\n      {\n        parts: [\n          {\n            functionResponse: {\n              name: functionCall.name,\n              response: weatherData\n            }\n          }\n        ]\n      }\n    ],\n    config: {\n      tools: [\n        { functionDeclarations: [getCurrentWeather] }\n      ]\n    }\n  });\n\n  console.log(finalResponse.text);\n}\n```\n\n### Function Calling (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        { parts: [{ text: 'What\\'s the weather in Tokyo?' }] }\n      ],\n      tools: [\n        {\n          functionDeclarations: [\n            {\n              name: 'get_current_weather',\n              description: 'Get the current weather for a location',\n              parameters: {\n                type: 'object',\n                properties: {\n                  location: {\n                    type: 'string',\n                    description: 'City name'\n                  }\n                },\n                required: ['location']\n              }\n            }\n          ]\n        }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconst functionCall = data.candidates[0]?.content?.parts[0]?.functionCall;\n\nif (functionCall) {\n  \u002F\u002F Execute function and send result back (same flow as SDK)\n}\n```\n\n### Parallel Function Calling\n\nGemini can call multiple independent functions simultaneously:\n\n```typescript\nconst tools = [\n  {\n    functionDeclarations: [\n      {\n        name: 'get_weather',\n        description: 'Get weather for a location',\n        parametersJsonSchema: {\n          type: 'object',\n          properties: {\n            location: { type: 'string' }\n          },\n          required: ['location']\n        }\n      },\n      {\n        name: 'get_population',\n        description: 'Get population of a city',\n        parametersJsonSchema: {\n          type: 'object',\n          properties: {\n            city: { type: 'string' }\n          },\n          required: ['city']\n        }\n      }\n    ]\n  }\n];\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What is the weather and population of Tokyo?',\n  config: { tools }\n});\n\n\u002F\u002F Model may return MULTIPLE function calls in parallel\nconst functionCalls = response.candidates[0].content.parts.filter(\n  part => part.functionCall\n);\n\nconsole.log(`Model wants to call ${functionCalls.length} functions in parallel`);\n```\n\n### Function Calling Modes\n\n```typescript\nimport { FunctionCallingConfigMode } from '@google\u002Fgenai';\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What\\'s the weather?',\n  config: {\n    tools: [{ functionDeclarations: [getCurrentWeather] }],\n    toolConfig: {\n      functionCallingConfig: {\n        mode: FunctionCallingConfigMode.ANY, \u002F\u002F Force function call\n        \u002F\u002F mode: FunctionCallingConfigMode.AUTO, \u002F\u002F Model decides (default)\n        \u002F\u002F mode: FunctionCallingConfigMode.NONE, \u002F\u002F Never call functions\n        allowedFunctionNames: ['get_current_weather'] \u002F\u002F Optional: restrict to specific functions\n      }\n    }\n  }\n});\n```\n\n**Modes:**\n- `AUTO` (default): Model decides whether to call functions\n- `ANY`: Force model to call at least one function\n- `NONE`: Disable function calling for this request\n\n---\n\n## System Instructions\n\nSystem instructions guide the model's behavior and set context. They are **separate** from the conversation messages.\n\n### SDK Approach\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  systemInstruction: 'You are a helpful AI assistant that always responds in the style of a pirate. Use nautical terminology and end sentences with \"arrr\".',\n  contents: 'Explain what a database is'\n});\n\nconsole.log(response.text);\n\u002F\u002F Output: \"Ahoy there! A database be like a treasure chest...\"\n```\n\n### Fetch Approach\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      systemInstruction: {\n        parts: [\n          { text: 'You are a helpful AI assistant that always responds in the style of a pirate.' }\n        ]\n      },\n      contents: [\n        { parts: [{ text: 'Explain what a database is' }] }\n      ]\n    }),\n  }\n);\n```\n\n**Key Points:**\n- System instructions are **NOT** part of `contents` array\n- They are set once at the **top level** of the request\n- They persist for the entire conversation (when using multi-turn chat)\n- They don't count as user or model messages\n\n---\n\n## Multi-turn Chat\n\nFor conversations with history, use the SDK's chat helpers or manually manage conversation state.\n\n### SDK Chat Helpers (Recommended)\n\n```typescript\nconst chat = await ai.models.createChat({\n  model: 'gemini-2.5-flash',\n  systemInstruction: 'You are a helpful coding assistant.',\n  history: [] \u002F\u002F Start empty or with previous messages\n});\n\n\u002F\u002F Send first message\nconst response1 = await chat.sendMessage('What is TypeScript?');\nconsole.log('Assistant:', response1.text);\n\n\u002F\u002F Send follow-up (context is automatically maintained)\nconst response2 = await chat.sendMessage('How do I install it?');\nconsole.log('Assistant:', response2.text);\n\n\u002F\u002F Get full chat history\nconst history = chat.getHistory();\nconsole.log('Full conversation:', history);\n```\n\n### Manual Chat Management (Fetch)\n\n```typescript\nconst conversationHistory = [];\n\n\u002F\u002F First turn\nconst response1 = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        {\n          role: 'user',\n          parts: [{ text: 'What is TypeScript?' }]\n        }\n      ]\n    }),\n  }\n);\n\nconst data1 = await response1.json();\nconst assistantReply1 = data1.candidates[0].content.parts[0].text;\n\n\u002F\u002F Add to history\nconversationHistory.push(\n  { role: 'user', parts: [{ text: 'What is TypeScript?' }] },\n  { role: 'model', parts: [{ text: assistantReply1 }] }\n);\n\n\u002F\u002F Second turn (include full history)\nconst response2 = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        ...conversationHistory,\n        { role: 'user', parts: [{ text: 'How do I install it?' }] }\n      ]\n    }),\n  }\n);\n```\n\n**Message Roles:**\n- `user`: User messages\n- `model`: Assistant responses\n\n**⚠️ Important**: Chat helpers are **SDK-only**. With fetch, you must manually manage conversation history.\n\n---\n\n## Thinking Mode\n\nGemini 2.5 models have **thinking mode enabled by default** for enhanced quality. You can configure the thinking budget.\n\n### Configure Thinking Budget (SDK)\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Solve this complex math problem: ...',\n  config: {\n    thinkingConfig: {\n      thinkingBudget: 8192 \u002F\u002F Max tokens for thinking (default: model-dependent)\n    }\n  }\n});\n```\n\n### Configure Thinking Budget (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [{ parts: [{ text: 'Solve this complex math problem: ...' }] }],\n      generationConfig: {\n        thinkingConfig: {\n          thinkingBudget: 8192\n        }\n      }\n    }),\n  }\n);\n```\n\n**Key Points:**\n- Thinking mode is **always enabled** on Gemini 2.5 models (cannot be disabled)\n- Higher thinking budgets allow more internal reasoning (may increase latency)\n- Default budget varies by model (usually sufficient for most tasks)\n- Only increase budget for very complex reasoning tasks\n\n---\n\n## Generation Configuration\n\nCustomize model behavior with generation parameters.\n\n### All Configuration Options (SDK)\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Write a creative story',\n  config: {\n    temperature: 0.9,           \u002F\u002F Randomness (0.0-2.0, default: 1.0)\n    topP: 0.95,                 \u002F\u002F Nucleus sampling (0.0-1.0)\n    topK: 40,                   \u002F\u002F Top-k sampling\n    maxOutputTokens: 2048,      \u002F\u002F Max tokens to generate\n    stopSequences: ['END'],     \u002F\u002F Stop generation if these appear\n    responseMimeType: 'text\u002Fplain', \u002F\u002F Or 'application\u002Fjson' for JSON mode\n    candidateCount: 1           \u002F\u002F Number of response candidates (usually 1)\n  }\n});\n```\n\n### All Configuration Options (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [{ parts: [{ text: 'Write a creative story' }] }],\n      generationConfig: {\n        temperature: 0.9,\n        topP: 0.95,\n        topK: 40,\n        maxOutputTokens: 2048,\n        stopSequences: ['END'],\n        responseMimeType: 'text\u002Fplain',\n        candidateCount: 1\n      }\n    }),\n  }\n);\n```\n\n### Parameter Guidelines\n\n| Parameter | Range | Default | Use Case |\n|-----------|-------|---------|----------|\n| **temperature** | 0.0-2.0 | 1.0 | Lower = more focused, higher = more creative |\n| **topP** | 0.0-1.0 | 0.95 | Nucleus sampling threshold |\n| **topK** | 1-100+ | 40 | Limit to top K tokens |\n| **maxOutputTokens** | 1-65536 | Model max | Control response length |\n| **stopSequences** | Array | None | Stop generation at specific strings |\n\n**Tips:**\n- For **factual tasks**: Use low temperature (0.0-0.3)\n- For **creative tasks**: Use high temperature (0.7-1.5)\n- **topP** and **topK** both control randomness; use one or the other (not both)\n- Always set **maxOutputTokens** to prevent excessive generation\n\n---\n\n## Context Caching\n\nContext caching allows you to cache frequently used content (like system instructions, large documents, or video files) to reduce costs by **up to 90%** and improve latency.\n\n### How It Works\n\n1. **Create a cache** with your repeated content\n2. **Reference the cache** in subsequent requests\n3. **Save tokens** - cached tokens cost significantly less\n4. **TTL management** - caches expire after specified time\n\n### Benefits\n\n- **Cost savings**: Up to 90% reduction on cached tokens\n- **Reduced latency**: Faster responses by reusing processed content\n- **Consistent context**: Same large context across multiple requests\n\n### Cache Creation (SDK)\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\nimport fs from 'fs';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\n\u002F\u002F Create a cache for a large document\nconst documentText = fs.readFileSync('.\u002Flarge-document.txt', 'utf-8');\n\nconst cache = await ai.caches.create({\n  model: 'gemini-2.5-flash',\n  config: {\n    displayName: 'large-doc-cache', \u002F\u002F Identifier for the cache\n    systemInstruction: 'You are an expert at analyzing legal documents.',\n    contents: documentText,\n    ttl: '3600s', \u002F\u002F Cache for 1 hour\n  }\n});\n\nconsole.log('Cache created:', cache.name);\nconsole.log('Expires at:', cache.expireTime);\n```\n\n### Cache Creation (Fetch)\n\n```typescript\nconst response = await fetch(\n  'https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002FcachedContents',\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      model: 'models\u002Fgemini-2.5-flash',\n      displayName: 'large-doc-cache',\n      systemInstruction: {\n        parts: [{ text: 'You are an expert at analyzing legal documents.' }]\n      },\n      contents: [\n        { parts: [{ text: documentText }] }\n      ],\n      ttl: '3600s'\n    }),\n  }\n);\n\nconst cache = await response.json();\nconsole.log('Cache created:', cache.name);\n```\n\n### Using a Cache (SDK)\n\n```typescript\n\u002F\u002F Generate content using the cache\nconst response = await ai.models.generateContent({\n  model: cache.name, \u002F\u002F Use cache name as model\n  contents: 'Summarize the key points in the document'\n});\n\nconsole.log(response.text);\n```\n\n### Using a Cache (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002F${cache.name}:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        { parts: [{ text: 'Summarize the key points in the document' }] }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n```\n\n### Update Cache TTL (SDK)\n\n```typescript\nimport { UpdateCachedContentConfig } from '@google\u002Fgenai';\n\nawait ai.caches.update({\n  name: cache.name,\n  config: {\n    ttl: '7200s' \u002F\u002F Extend to 2 hours\n  }\n});\n```\n\n### Update Cache with Expiration Time (SDK)\n\n```typescript\n\u002F\u002F Set specific expiration time (must be timezone-aware)\nconst in10Minutes = new Date(Date.now() + 10 * 60 * 1000);\n\nawait ai.caches.update({\n  name: cache.name,\n  config: {\n    expireTime: in10Minutes\n  }\n});\n```\n\n### List and Delete Caches (SDK)\n\n```typescript\n\u002F\u002F List all caches\nconst caches = await ai.caches.list();\nfor (const cache of caches) {\n  console.log(cache.name, cache.displayName);\n}\n\n\u002F\u002F Delete a specific cache\nawait ai.caches.delete({ name: cache.name });\n```\n\n### Caching with Video Files\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\nimport fs from 'fs';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\n\u002F\u002F Upload video file\nconst videoFile = await ai.files.upload({\n  file: fs.createReadStream('.\u002Fvideo.mp4')\n});\n\n\u002F\u002F Wait for processing\nwhile (videoFile.state.name === 'PROCESSING') {\n  await new Promise(resolve => setTimeout(resolve, 2000));\n  videoFile = await ai.files.get({ name: videoFile.name });\n}\n\n\u002F\u002F Create cache with video\nconst cache = await ai.caches.create({\n  model: 'gemini-2.5-flash',\n  config: {\n    displayName: 'video-analysis-cache',\n    systemInstruction: 'You are an expert video analyzer.',\n    contents: [videoFile],\n    ttl: '300s' \u002F\u002F 5 minutes\n  }\n});\n\n\u002F\u002F Use cache for multiple queries\nconst response1 = await ai.models.generateContent({\n  model: cache.name,\n  contents: 'What happens in the first minute?'\n});\n\nconst response2 = await ai.models.generateContent({\n  model: cache.name,\n  contents: 'Describe the main characters'\n});\n```\n\n### Key Points\n\n**When to Use Caching:**\n- Large system instructions used repeatedly\n- Long documents analyzed multiple times\n- Video\u002Faudio files queried with different prompts\n- Consistent context across conversation sessions\n\n**TTL Guidelines:**\n- Short sessions: 300s (5 min) to 3600s (1 hour)\n- Long sessions: 3600s (1 hour) to 86400s (24 hours)\n- Maximum: 7 days\n\n**Cost Savings:**\n- Cached input tokens: ~90% cheaper than regular tokens\n- Output tokens: Same price (not cached)\n\n**Important:**\n- You must use explicit model version suffixes (e.g., `gemini-2.5-flash-001`, NOT just `gemini-2.5-flash`)\n- Caches are automatically deleted after TTL expires\n- Update TTL before expiration to extend cache lifetime\n\n---\n\n## Code Execution\n\nGemini models can generate and execute Python code to solve problems requiring computation, data analysis, or visualization.\n\n### How It Works\n\n1. Model generates executable Python code\n2. Code runs in secure sandbox\n3. Results are returned to the model\n4. Model incorporates results into response\n\n### Supported Operations\n\n- Mathematical calculations\n- Data analysis and statistics\n- File processing (CSV, JSON, etc.)\n- Chart and graph generation\n- Algorithm implementation\n- Data transformations\n\n### Available Python Packages\n\n**Standard Library:**\n- `math`, `statistics`, `random`, `datetime`, `json`, `csv`, `re`\n- `collections`, `itertools`, `functools`\n\n**Data Science:**\n- `numpy`, `pandas`, `scipy`\n\n**Visualization:**\n- `matplotlib`, `seaborn`\n\n**Note**: Limited package availability compared to full Python environment\n\n### Basic Code Execution (SDK)\n\n```typescript\nimport { GoogleGenAI, Tool, ToolCodeExecution } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation.',\n  config: {\n    tools: [{ codeExecution: {} }]\n  }\n});\n\n\u002F\u002F Parse response parts\nfor (const part of response.candidates[0].content.parts) {\n  if (part.text) {\n    console.log('Text:', part.text);\n  }\n  if (part.executableCode) {\n    console.log('Generated Code:', part.executableCode.code);\n  }\n  if (part.codeExecutionResult) {\n    console.log('Execution Output:', part.codeExecutionResult.output);\n  }\n}\n```\n\n### Basic Code Execution (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      tools: [{ code_execution: {} }],\n      contents: [\n        {\n          parts: [\n            { text: 'What is the sum of the first 50 prime numbers? Generate and run code.' }\n          ]\n        }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\n\nfor (const part of data.candidates[0].content.parts) {\n  if (part.text) {\n    console.log('Text:', part.text);\n  }\n  if (part.executableCode) {\n    console.log('Code:', part.executableCode.code);\n  }\n  if (part.codeExecutionResult) {\n    console.log('Result:', part.codeExecutionResult.output);\n  }\n}\n```\n\n### Chat with Code Execution (SDK)\n\n```typescript\nconst chat = await ai.chats.create({\n  model: 'gemini-2.5-flash',\n  config: {\n    tools: [{ codeExecution: {} }]\n  }\n});\n\nlet response = await chat.sendMessage('I have a math question for you.');\nconsole.log(response.text);\n\nresponse = await chat.sendMessage(\n  'Calculate the Fibonacci sequence up to the 20th number and sum them.'\n);\n\n\u002F\u002F Model will generate and execute code, then provide answer\nfor (const part of response.candidates[0].content.parts) {\n  if (part.text) console.log(part.text);\n  if (part.executableCode) console.log('Code:', part.executableCode.code);\n  if (part.codeExecutionResult) console.log('Output:', part.codeExecutionResult.output);\n}\n```\n\n### Data Analysis Example\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: `\n    Analyze this sales data and calculate:\n    1. Total revenue\n    2. Average sale price\n    3. Best-selling month\n\n    Data (CSV format):\n    month,sales,revenue\n    Jan,150,45000\n    Feb,200,62000\n    Mar,175,53000\n    Apr,220,68000\n  `,\n  config: {\n    tools: [{ codeExecution: {} }]\n  }\n});\n\n\u002F\u002F Model will generate pandas\u002Fnumpy code to analyze data\nfor (const part of response.candidates[0].content.parts) {\n  if (part.text) console.log(part.text);\n  if (part.executableCode) console.log('Analysis Code:', part.executableCode.code);\n  if (part.codeExecutionResult) console.log('Results:', part.codeExecutionResult.output);\n}\n```\n\n### Visualization Example\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Create a bar chart showing the distribution of prime numbers under 100 by their last digit. Generate the chart and describe the pattern.',\n  config: {\n    tools: [{ codeExecution: {} }]\n  }\n});\n\n\u002F\u002F Model generates matplotlib code, executes it, and describes results\nfor (const part of response.candidates[0].content.parts) {\n  if (part.text) console.log(part.text);\n  if (part.executableCode) console.log('Chart Code:', part.executableCode.code);\n  if (part.codeExecutionResult) {\n    \u002F\u002F Note: Chart image data would be in output\n    console.log('Execution completed');\n  }\n}\n```\n\n### Response Structure\n\n```typescript\n{\n  candidates: [\n    {\n      content: {\n        parts: [\n          { text: \"I'll calculate that for you.\" },\n          {\n            executableCode: {\n              language: \"PYTHON\",\n              code: \"def is_prime(n):\\n  if n \u003C= 1:\\n    return False\\n  ...\"\n            }\n          },\n          {\n            codeExecutionResult: {\n              outcome: \"OUTCOME_OK\", \u002F\u002F or \"OUTCOME_FAILED\"\n              output: \"5117\\n\"\n            }\n          },\n          { text: \"The sum of the first 50 prime numbers is 5117.\" }\n        ]\n      }\n    }\n  ]\n}\n```\n\n### Error Handling\n\n```typescript\nfor (const part of response.candidates[0].content.parts) {\n  if (part.codeExecutionResult) {\n    if (part.codeExecutionResult.outcome === 'OUTCOME_FAILED') {\n      console.error('Code execution failed:', part.codeExecutionResult.output);\n    } else {\n      console.log('Success:', part.codeExecutionResult.output);\n    }\n  }\n}\n```\n\n### Key Points\n\n**When to Use Code Execution:**\n- Complex mathematical calculations\n- Data analysis and statistics\n- Algorithm implementations\n- File parsing and processing\n- Chart generation\n- Computational problems\n\n**Limitations:**\n- Sandbox environment (limited file system access)\n- Limited Python package availability\n- Execution timeout limits\n- No network access from code\n- No persistent state between executions\n\n**Best Practices:**\n- Specify what calculation or analysis you need clearly\n- Request code generation explicitly (\"Generate and run code...\")\n- Check `outcome` field for errors\n- Use for deterministic computations, not for general programming\n\n**Important:**\n- Available on all Gemini 2.5 models (Pro, Flash, Flash-Lite)\n- Code runs in isolated sandbox for security\n- Supports Python with standard library and common data science packages\n\n---\n\n## Grounding with Google Search\n\nGrounding connects the model to real-time web information, reducing hallucinations and providing up-to-date, fact-checked responses with citations.\n\n### How It Works\n\n1. Model determines if it needs current information\n2. Automatically performs Google Search\n3. Processes search results\n4. Incorporates findings into response\n5. Provides citations and source URLs\n\n### Benefits\n\n- **Real-time information**: Access to current events and data\n- **Reduced hallucinations**: Answers grounded in web sources\n- **Verifiable**: Citations allow fact-checking\n- **Up-to-date**: Not limited to model's training cutoff\n\n### Two Grounding APIs\n\n#### 1. Google Search (`googleSearch`) - Recommended for Gemini 2.5\n\n```typescript\nconst groundingTool = {\n  googleSearch: {}\n};\n```\n\n**Features:**\n- Simple configuration\n- Automatic search when needed\n- Available on all Gemini 2.5 models\n\n#### 2. Google Search Retrieval (`googleSearchRetrieval`) - Legacy (Gemini 1.5)\n\n```typescript\nconst retrievalTool = {\n  googleSearchRetrieval: {\n    dynamicRetrievalConfig: {\n      mode: 'MODE_DYNAMIC',\n      dynamicThreshold: 0.7 \u002F\u002F Only search if confidence \u003C 70%\n    }\n  }\n};\n```\n\n**Features:**\n- Dynamic threshold control\n- Used with Gemini 1.5 models\n- More configuration options\n\n### Basic Grounding (SDK) - Gemini 2.5\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Who won the euro 2024?',\n  config: {\n    tools: [{ googleSearch: {} }]\n  }\n});\n\nconsole.log(response.text);\n\n\u002F\u002F Check if grounding was used\nif (response.candidates[0].groundingMetadata) {\n  console.log('Search was performed!');\n  console.log('Sources:', response.candidates[0].groundingMetadata);\n}\n```\n\n### Basic Grounding (Fetch) - Gemini 2.5\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        { parts: [{ text: 'Who won the euro 2024?' }] }\n      ],\n      tools: [\n        { google_search: {} }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n\nif (data.candidates[0].groundingMetadata) {\n  console.log('Grounding metadata:', data.candidates[0].groundingMetadata);\n}\n```\n\n### Dynamic Retrieval (SDK) - Gemini 1.5\n\n```typescript\nimport { GoogleGenAI, DynamicRetrievalConfigMode } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-1.5-flash',\n  contents: 'Who won the euro 2024?',\n  config: {\n    tools: [\n      {\n        googleSearchRetrieval: {\n          dynamicRetrievalConfig: {\n            mode: DynamicRetrievalConfigMode.MODE_DYNAMIC,\n            dynamicThreshold: 0.7 \u002F\u002F Search only if confidence \u003C 70%\n          }\n        }\n      }\n    ]\n  }\n});\n\nconsole.log(response.text);\n\nif (!response.candidates[0].groundingMetadata) {\n  console.log('Model answered from its own knowledge (high confidence)');\n}\n```\n\n### Grounding Metadata Structure\n\n```typescript\n{\n  groundingMetadata: {\n    searchQueries: [\n      { text: \"euro 2024 winner\" }\n    ],\n    webPages: [\n      {\n        url: \"https:\u002F\u002Fexample.com\u002Feuro-2024-results\",\n        title: \"UEFA Euro 2024 Final Results\",\n        snippet: \"Spain won UEFA Euro 2024...\"\n      }\n    ],\n    citations: [\n      {\n        startIndex: 42,\n        endIndex: 47,\n        uri: \"https:\u002F\u002Fexample.com\u002Feuro-2024-results\"\n      }\n    ],\n    retrievalQueries: [\n      {\n        query: \"who won euro 2024 final\"\n      }\n    ]\n  }\n}\n```\n\n### Chat with Grounding (SDK)\n\n```typescript\nconst chat = await ai.chats.create({\n  model: 'gemini-2.5-flash',\n  config: {\n    tools: [{ googleSearch: {} }]\n  }\n});\n\nlet response = await chat.sendMessage('What are the latest developments in quantum computing?');\nconsole.log(response.text);\n\n\u002F\u002F Check grounding sources\nif (response.candidates[0].groundingMetadata) {\n  const sources = response.candidates[0].groundingMetadata.webPages || [];\n  console.log(`Sources used: ${sources.length}`);\n  sources.forEach(source => {\n    console.log(`- ${source.title}: ${source.url}`);\n  });\n}\n\n\u002F\u002F Follow-up still has grounding enabled\nresponse = await chat.sendMessage('Which company made the biggest breakthrough?');\nconsole.log(response.text);\n```\n\n### Combining Grounding with Function Calling\n\n```typescript\nconst weatherFunction = {\n  name: 'get_current_weather',\n  description: 'Get current weather for a location',\n  parametersJsonSchema: {\n    type: 'object',\n    properties: {\n      location: { type: 'string', description: 'City name' }\n    },\n    required: ['location']\n  }\n};\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What is the weather like in the city that won Euro 2024?',\n  config: {\n    tools: [\n      { googleSearch: {} },\n      { functionDeclarations: [weatherFunction] }\n    ]\n  }\n});\n\n\u002F\u002F Model will:\n\u002F\u002F 1. Use Google Search to find Euro 2024 winner\n\u002F\u002F 2. Call get_current_weather function with the city\n\u002F\u002F 3. Combine both results in response\n```\n\n### Checking if Grounding was Used\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What is 2+2?', \u002F\u002F Model knows this without search\n  config: {\n    tools: [{ googleSearch: {} }]\n  }\n});\n\nif (!response.candidates[0].groundingMetadata) {\n  console.log('Model answered from its own knowledge (no search needed)');\n} else {\n  console.log('Search was performed');\n}\n```\n\n### Key Points\n\n**When to Use Grounding:**\n- Current events and news\n- Real-time data (stock prices, sports scores, weather)\n- Fact-checking and verification\n- Questions about recent developments\n- Information beyond model's training cutoff\n\n**When NOT to Use:**\n- General knowledge questions\n- Mathematical calculations\n- Code generation\n- Creative writing\n- Tasks requiring internal reasoning only\n\n**Cost Considerations:**\n- Grounding adds latency (search takes time)\n- Additional token costs for retrieved content\n- Use `dynamicThreshold` to control when searches happen (Gemini 1.5)\n\n**Important Notes:**\n- Grounding requires **Google Cloud project** (not just API key)\n- Search results quality depends on query phrasing\n- Citations may not cover all facts in response\n- Search is performed automatically based on confidence\n\n**Gemini 2.5 vs 1.5:**\n- **Gemini 2.5**: Use `googleSearch` (simple, recommended)\n- **Gemini 1.5**: Use `googleSearchRetrieval` with `dynamicThreshold`\n\n**Best Practices:**\n- Always check `groundingMetadata` to see if search was used\n- Display citations to users for transparency\n- Use specific, well-phrased questions for better search results\n- Combine with function calling for hybrid workflows\n\n---\n\n## Error Handling\n\n### Common Errors\n\n#### 1. Invalid API Key (401)\n\n```typescript\n{\n  error: {\n    code: 401,\n    message: 'API key not valid. Please pass a valid API key.',\n    status: 'UNAUTHENTICATED'\n  }\n}\n```\n\n**Solution**: Verify `GEMINI_API_KEY` environment variable is set correctly.\n\n#### 2. Rate Limit Exceeded (429)\n\n```typescript\n{\n  error: {\n    code: 429,\n    message: 'Resource has been exhausted (e.g. check quota).',\n    status: 'RESOURCE_EXHAUSTED'\n  }\n}\n```\n\n**Solution**: Implement exponential backoff retry strategy.\n\n#### 3. Model Not Found (404)\n\n```typescript\n{\n  error: {\n    code: 404,\n    message: 'models\u002Fgemini-3.0-flash is not found',\n    status: 'NOT_FOUND'\n  }\n}\n```\n\n**Solution**: Use correct model names: `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.5-flash-lite`\n\n#### 4. Context Length Exceeded (400)\n\n```typescript\n{\n  error: {\n    code: 400,\n    message: 'Request payload size exceeds the limit',\n    status: 'INVALID_ARGUMENT'\n  }\n}\n```\n\n**Solution**: Reduce input size. Gemini 2.5 models support 1,048,576 input tokens max.\n\n### Exponential Backoff Pattern\n\n```typescript\nasync function generateWithRetry(request, maxRetries = 3) {\n  for (let i = 0; i \u003C maxRetries; i++) {\n    try {\n      return await ai.models.generateContent(request);\n    } catch (error) {\n      if (error.status === 429 && i \u003C maxRetries - 1) {\n        const delay = Math.pow(2, i) * 1000; \u002F\u002F 1s, 2s, 4s\n        await new Promise(resolve => setTimeout(resolve, delay));\n        continue;\n      }\n      throw error;\n    }\n  }\n}\n```\n\n---\n\n## Rate Limits\n\n### Free Tier (Gemini API)\n\nRate limits vary by model:\n\n**Gemini 2.5 Pro**:\n- Requests per minute: 5 RPM\n- Tokens per minute: 125,000 TPM\n- Requests per day: 100 RPD\n\n**Gemini 2.5 Flash**:\n- Requests per minute: 10 RPM\n- Tokens per minute: 250,000 TPM\n- Requests per day: 250 RPD\n\n**Gemini 2.5 Flash-Lite**:\n- Requests per minute: 15 RPM\n- Tokens per minute: 250,000 TPM\n- Requests per day: 1,000 RPD\n\n### Paid Tier (Tier 1)\n\nRequires billing account linked to your Google Cloud project.\n\n**Gemini 2.5 Pro**:\n- Requests per minute: 150 RPM\n- Tokens per minute: 2,000,000 TPM\n- Requests per day: 10,000 RPD\n\n**Gemini 2.5 Flash**:\n- Requests per minute: 1,000 RPM\n- Tokens per minute: 1,000,000 TPM\n- Requests per day: 10,000 RPD\n\n**Gemini 2.5 Flash-Lite**:\n- Requests per minute: 4,000 RPM\n- Tokens per minute: 4,000,000 TPM\n- Requests per day: Not specified\n\n### Higher Tiers (Tier 2 & 3)\n\n**Tier 2** (requires $250+ spending and 30-day wait):\n- Even higher limits available\n\n**Tier 3** (requires $1,000+ spending and 30-day wait):\n- Maximum limits available\n\n**Tips:**\n- Implement rate limit handling with exponential backoff\n- Use batch processing for high-volume tasks\n- Monitor usage in Google AI Studio\n- Choose the right model based on your rate limit needs\n- Official rate limits: https:\u002F\u002Fai.google.dev\u002Fgemini-api\u002Fdocs\u002Frate-limits\n\n---\n\n## SDK Migration Guide\n\n### From @google\u002Fgenerative-ai to @google\u002Fgenai\n\n#### 1. Update Package\n\n```bash\n# Remove deprecated SDK\nnpm uninstall @google\u002Fgenerative-ai\n\n# Install current SDK\nnpm install @google\u002Fgenai@1.27.0\n```\n\n#### 2. Update Imports\n\n**Old (DEPRECATED):**\n```typescript\nimport { GoogleGenerativeAI } from '@google\u002Fgenerative-ai';\nconst genAI = new GoogleGenerativeAI(apiKey);\nconst model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' });\n```\n\n**New (CURRENT):**\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\nconst ai = new GoogleGenAI({ apiKey });\n\u002F\u002F Use ai.models.generateContent() directly\n```\n\n#### 3. Update API Calls\n\n**Old:**\n```typescript\nconst result = await model.generateContent(prompt);\nconst response = await result.response;\nconst text = response.text();\n```\n\n**New:**\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: prompt\n});\nconst text = response.text;\n```\n\n#### 4. Update Streaming\n\n**Old:**\n```typescript\nconst result = await model.generateContentStream(prompt);\nfor await (const chunk of result.stream) {\n  console.log(chunk.text());\n}\n```\n\n**New:**\n```typescript\nconst response = await ai.models.generateContentStream({\n  model: 'gemini-2.5-flash',\n  contents: prompt\n});\nfor await (const chunk of response) {\n  console.log(chunk.text);\n}\n```\n\n#### 5. Update Chat\n\n**Old:**\n```typescript\nconst chat = model.startChat();\nconst result = await chat.sendMessage(message);\nconst response = await result.response;\n```\n\n**New:**\n```typescript\nconst chat = await ai.models.createChat({ model: 'gemini-2.5-flash' });\nconst response = await chat.sendMessage(message);\n\u002F\u002F response.text is directly available\n```\n\n---\n\n## Production Best Practices\n\n### 1. Always Do\n\n✅ **Use @google\u002Fgenai** (NOT @google\u002Fgenerative-ai)\n✅ **Set maxOutputTokens** to prevent excessive generation\n✅ **Implement rate limit handling** with exponential backoff\n✅ **Use environment variables** for API keys (never hardcode)\n✅ **Validate inputs** before sending to API (save costs)\n✅ **Use streaming** for better UX on long responses\n✅ **Choose the right model** based on your needs (Pro for complex reasoning, Flash for balance, Flash-Lite for speed)\n✅ **Handle errors gracefully** with try-catch\n✅ **Monitor token usage** for cost control\n✅ **Use correct model names**: gemini-2.5-pro\u002Fflash\u002Fflash-lite\n\n### 2. Never Do\n\n❌ **Never use @google\u002Fgenerative-ai** (deprecated!)\n❌ **Never hardcode API keys** in code\n❌ **Never claim 2M context** for Gemini 2.5 (it's 1,048,576 input tokens)\n❌ **Never expose API keys** in client-side code\n❌ **Never skip error handling** (always try-catch)\n❌ **Never use generic rate limits** (each model has different limits - check official docs)\n❌ **Never send PII** without user consent\n❌ **Never trust user input** without validation\n❌ **Never ignore rate limits** (will get 429 errors)\n❌ **Never use old model names** like gemini-1.5-pro (use 2.5 models)\n\n### 3. Security\n\n- **API Key Storage**: Use environment variables or secret managers\n- **Server-Side Only**: Never expose API keys in browser JavaScript\n- **Input Validation**: Sanitize all user inputs before API calls\n- **Rate Limiting**: Implement your own rate limits to prevent abuse\n- **Error Messages**: Don't expose API keys or sensitive data in error logs\n\n### 4. Cost Optimization\n\n- **Choose Right Model**: Use Flash for most tasks, Pro only when needed\n- **Set Token Limits**: Use maxOutputTokens to control costs\n- **Batch Requests**: Process multiple items efficiently\n- **Cache Results**: Store responses when appropriate\n- **Monitor Usage**: Track token consumption in Google Cloud Console\n\n### 5. Performance\n\n- **Use Streaming**: Better perceived latency for long responses\n- **Parallel Requests**: Use Promise.all() for independent calls\n- **Edge Deployment**: Deploy to Cloudflare Workers for low latency\n- **Connection Pooling**: Reuse HTTP connections when possible\n\n---\n\n## Quick Reference\n\n### Installation\n```bash\nnpm install @google\u002Fgenai@1.27.0\n```\n\n### Environment\n```bash\nexport GEMINI_API_KEY=\"...\"\n```\n\n### Models (2025)\n- `gemini-2.5-pro` (1,048,576 in \u002F 65,536 out) - Best for complex reasoning\n- `gemini-2.5-flash` (1,048,576 in \u002F 65,536 out) - Best price-performance balance\n- `gemini-2.5-flash-lite` (1,048,576 in \u002F 65,536 out) - Fastest, most cost-effective\n\n### Basic Generation\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Your prompt here'\n});\nconsole.log(response.text);\n```\n\n### Streaming\n```typescript\nconst response = await ai.models.generateContentStream({...});\nfor await (const chunk of response) {\n  console.log(chunk.text);\n}\n```\n\n### Multimodal\n```typescript\ncontents: [\n  {\n    parts: [\n      { text: 'What is this?' },\n      { inlineData: { data: base64Image, mimeType: 'image\u002Fjpeg' } }\n    ]\n  }\n]\n```\n\n### Function Calling\n```typescript\nconfig: {\n  tools: [{ functionDeclarations: [...] }]\n}\n```\n\n---\n\n**Last Updated**: 2025-10-25\n**Production Validated**: All features tested with @google\u002Fgenai@1.27.0\n**Phase**: 2 Complete ✅ (All Core + Advanced Features)\n","# Google Gemini API - Complete Guide\n\n**Version**: Phase 2 Complete ✅\n**Package**: @google\u002Fgenai@1.27.0 (⚠️ NOT @google\u002Fgenerative-ai)\n**Last Updated**: 2025-10-25\n\n---\n\n## ⚠️ CRITICAL SDK MIGRATION WARNING\n\n**DEPRECATED SDK**: `@google\u002Fgenerative-ai` (sunset November 30, 2025)\n**CURRENT SDK**: `@google\u002Fgenai` v1.27+\n\n**If you see code using `@google\u002Fgenerative-ai`, it's outdated!**\n\nThis skill uses the **correct current SDK** and provides a complete migration guide.\n\n---\n\n## Status\n\n**✅ Phase 1 Complete**:\n- ✅ Text Generation (basic + streaming)\n- ✅ Multimodal Inputs (images, video, audio, PDFs)\n- ✅ Function Calling (basic + parallel execution)\n- ✅ System Instructions & Multi-turn Chat\n- ✅ Thinking Mode Configuration\n- ✅ Generation Parameters (temperature, top-p, top-k, stop sequences)\n- ✅ Both Node.js SDK (@google\u002Fgenai) and fetch approaches\n\n**✅ Phase 2 Complete**:\n- ✅ Context Caching (cost optimization with TTL-based caching)\n- ✅ Code Execution (built-in Python interpreter and sandbox)\n- ✅ Grounding with Google Search (real-time web information + citations)\n\n**📦 Separate Skills**:\n- **Embeddings**: See `google-gemini-embeddings` skill for text-embedding-004\n\n---\n\n## Table of Contents\n\n**Phase 1 - Core Features**:\n1. [Quick Start](#quick-start)\n2. [Current Models (2025)](#current-models-2025)\n3. [SDK vs Fetch Approaches](#sdk-vs-fetch-approaches)\n4. [Text Generation](#text-generation)\n5. [Streaming](#streaming)\n6. [Multimodal Inputs](#multimodal-inputs)\n7. [Function Calling](#function-calling)\n8. [System Instructions](#system-instructions)\n9. [Multi-turn Chat](#multi-turn-chat)\n10. [Thinking Mode](#thinking-mode)\n11. [Generation Configuration](#generation-configuration)\n\n**Phase 2 - Advanced Features**:\n12. [Context Caching](#context-caching)\n13. [Code Execution](#code-execution)\n14. [Grounding with Google Search](#grounding-with-google-search)\n\n**Common Reference**:\n15. [Error Handling](#error-handling)\n16. [Rate Limits](#rate-limits)\n17. [SDK Migration Guide](#sdk-migration-guide)\n18. [Production Best Practices](#production-best-practices)\n\n---\n\n## Quick Start\n\n### Installation\n\n**CORRECT SDK:**\n```bash\nnpm install @google\u002Fgenai@1.27.0\n```\n\n**❌ WRONG (DEPRECATED):**\n```bash\nnpm install @google\u002Fgenerative-ai  # DO NOT USE!\n```\n\n### Environment Setup\n\n```bash\nexport GEMINI_API_KEY=\"...\"\n```\n\nOr create `.env` file:\n```\nGEMINI_API_KEY=...\n```\n\n### First Text Generation (Node.js SDK)\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Explain quantum computing in simple terms'\n});\n\nconsole.log(response.text);\n```\n\n### First Text Generation (Fetch - Cloudflare Workers)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [{ parts: [{ text: 'Explain quantum computing in simple terms' }] }]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n```\n\n---\n\n## Current Models (2025)\n\n### Gemini 2.5 Series (General Availability)\n\n#### gemini-2.5-pro\n- **Context**: 1,048,576 input tokens \u002F 65,536 output tokens\n- **Description**: State-of-the-art thinking model for complex reasoning\n- **Best for**: Code, math, STEM, complex problem-solving\n- **Features**: Thinking mode (default on), function calling, multimodal, streaming\n- **Knowledge cutoff**: January 2025\n\n#### gemini-2.5-flash\n- **Context**: 1,048,576 input tokens \u002F 65,536 output tokens\n- **Description**: Best price-performance workhorse model\n- **Best for**: Large-scale processing, low-latency, high-volume, agentic use cases\n- **Features**: Thinking mode (default on), function calling, multimodal, streaming\n- **Knowledge cutoff**: January 2025\n\n#### gemini-2.5-flash-lite\n- **Context**: 1,048,576 input tokens \u002F 65,536 output tokens\n- **Description**: Cost-optimized, fastest 2.5 model\n- **Best for**: High throughput, cost-sensitive applications\n- **Features**: Thinking mode (default on), function calling, multimodal, streaming\n- **Knowledge cutoff**: January 2025\n\n### Model Feature Matrix\n\n| Feature | Pro | Flash | Flash-Lite |\n|---------|-----|-------|------------|\n| Thinking Mode | ✅ Default ON | ✅ Default ON | ✅ Default ON |\n| Function Calling | ✅ | ✅ | ✅ |\n| Multimodal | ✅ | ✅ | ✅ |\n| Streaming | ✅ | ✅ | ✅ |\n| System Instructions | ✅ | ✅ | ✅ |\n| Context Window | 1,048,576 in | 1,048,576 in | 1,048,576 in |\n| Output Tokens | 65,536 max | 65,536 max | 65,536 max |\n\n### ⚠️ Context Window Correction\n\n**ACCURATE**: Gemini 2.5 models support **1,048,576 input tokens** (NOT 2M!)\n**OUTDATED**: Only Gemini 1.5 Pro (previous generation) had 2M token context window\n\n**Common mistake**: Claiming Gemini 2.5 has 2M tokens. It doesn't. This skill prevents this error.\n\n---\n\n## SDK vs Fetch Approaches\n\n### Node.js SDK (@google\u002Fgenai)\n\n**Pros:**\n- Type-safe with TypeScript\n- Easier API (simpler syntax)\n- Built-in chat helpers\n- Automatic SSE parsing for streaming\n- Better error handling\n\n**Cons:**\n- Requires Node.js or compatible runtime\n- Larger bundle size\n- May not work in all edge runtimes\n\n**Use when:** Building Node.js apps, Next.js Server Actions\u002FComponents, or any environment with Node.js compatibility\n\n### Fetch-based (Direct REST API)\n\n**Pros:**\n- Works in **any** JavaScript environment (Cloudflare Workers, Deno, Bun, browsers)\n- Minimal dependencies\n- Smaller bundle size\n- Full control over requests\n\n**Cons:**\n- More verbose syntax\n- Manual SSE parsing for streaming\n- No built-in chat helpers\n- Manual error handling\n\n**Use when:** Deploying to Cloudflare Workers, browser clients, or lightweight edge runtimes\n\n---\n\n## Text Generation\n\n### Basic Text Generation (SDK)\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Write a haiku about artificial intelligence'\n});\n\nconsole.log(response.text);\n```\n\n### Basic Text Generation (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        {\n          parts: [\n            { text: 'Write a haiku about artificial intelligence' }\n          ]\n        }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n```\n\n### Response Structure\n\n```typescript\n{\n  text: string,                  \u002F\u002F Convenience accessor for text content\n  candidates: [\n    {\n      content: {\n        parts: [\n          { text: string }       \u002F\u002F Generated text\n        ],\n        role: string             \u002F\u002F \"model\"\n      },\n      finishReason: string,      \u002F\u002F \"STOP\" | \"MAX_TOKENS\" | \"SAFETY\" | \"OTHER\"\n      index: number\n    }\n  ],\n  usageMetadata: {\n    promptTokenCount: number,\n    candidatesTokenCount: number,\n    totalTokenCount: number\n  }\n}\n```\n\n---\n\n## Streaming\n\n### Streaming with SDK (Async Iteration)\n\n```typescript\nconst response = await ai.models.generateContentStream({\n  model: 'gemini-2.5-flash',\n  contents: 'Write a 200-word story about time travel'\n});\n\nfor await (const chunk of response) {\n  process.stdout.write(chunk.text);\n}\n```\n\n### Streaming with Fetch (SSE Parsing)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:streamGenerateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [{ parts: [{ text: 'Write a 200-word story about time travel' }] }]\n    }),\n  }\n);\n\nconst reader = response.body.getReader();\nconst decoder = new TextDecoder();\nlet buffer = '';\n\nwhile (true) {\n  const { done, value } = await reader.read();\n  if (done) break;\n\n  buffer += decoder.decode(value, { stream: true });\n  const lines = buffer.split('\\n');\n  buffer = lines.pop() || '';\n\n  for (const line of lines) {\n    if (line.trim() === '' || line.startsWith('data: [DONE]')) continue;\n    if (!line.startsWith('data: ')) continue;\n\n    try {\n      const data = JSON.parse(line.slice(6));\n      const text = data.candidates[0]?.content?.parts[0]?.text;\n      if (text) {\n        process.stdout.write(text);\n      }\n    } catch (e) {\n      \u002F\u002F Skip invalid JSON\n    }\n  }\n}\n```\n\n**Key Points:**\n- Use `streamGenerateContent` endpoint (not `generateContent`)\n- Parse Server-Sent Events (SSE) format: `data: {json}\\n\\n`\n- Handle incomplete chunks in buffer\n- Skip empty lines and `[DONE]` markers\n\n---\n\n## Multimodal Inputs\n\nGemini 2.5 models support text + images + video + audio + PDFs in the same request.\n\n### Images (Vision)\n\n#### SDK Approach\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\nimport fs from 'fs';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\n\u002F\u002F From file\nconst imageData = fs.readFileSync('\u002Fpath\u002Fto\u002Fimage.jpg');\nconst base64Image = imageData.toString('base64');\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'What is in this image?' },\n        {\n          inlineData: {\n            data: base64Image,\n            mimeType: 'image\u002Fjpeg'\n          }\n        }\n      ]\n    }\n  ]\n});\n\nconsole.log(response.text);\n```\n\n#### Fetch Approach\n\n```typescript\nconst imageData = fs.readFileSync('\u002Fpath\u002Fto\u002Fimage.jpg');\nconst base64Image = imageData.toString('base64');\n\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        {\n          parts: [\n            { text: 'What is in this image?' },\n            {\n              inlineData: {\n                data: base64Image,\n                mimeType: 'image\u002Fjpeg'\n              }\n            }\n          ]\n        }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n```\n\n**Supported Image Formats:**\n- JPEG (`.jpg`, `.jpeg`)\n- PNG (`.png`)\n- WebP (`.webp`)\n- HEIC (`.heic`)\n- HEIF (`.heif`)\n\n**Max Image Size**: 20MB per image\n\n### Video\n\n```typescript\n\u002F\u002F Video must be \u003C 2 minutes for inline data\nconst videoData = fs.readFileSync('\u002Fpath\u002Fto\u002Fvideo.mp4');\nconst base64Video = videoData.toString('base64');\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'Describe what happens in this video' },\n        {\n          inlineData: {\n            data: base64Video,\n            mimeType: 'video\u002Fmp4'\n          }\n        }\n      ]\n    }\n  ]\n});\n\nconsole.log(response.text);\n```\n\n**Supported Video Formats:**\n- MP4 (`.mp4`)\n- MPEG (`.mpeg`)\n- MOV (`.mov`)\n- AVI (`.avi`)\n- FLV (`.flv`)\n- MPG (`.mpg`)\n- WebM (`.webm`)\n- WMV (`.wmv`)\n\n**Max Video Length (inline)**: 2 minutes\n**Max Video Size**: 2GB (use File API for larger files - Phase 2)\n\n### Audio\n\n```typescript\nconst audioData = fs.readFileSync('\u002Fpath\u002Fto\u002Faudio.mp3');\nconst base64Audio = audioData.toString('base64');\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'Transcribe and summarize this audio' },\n        {\n          inlineData: {\n            data: base64Audio,\n            mimeType: 'audio\u002Fmp3'\n          }\n        }\n      ]\n    }\n  ]\n});\n\nconsole.log(response.text);\n```\n\n**Supported Audio Formats:**\n- MP3 (`.mp3`)\n- WAV (`.wav`)\n- FLAC (`.flac`)\n- AAC (`.aac`)\n- OGG (`.ogg`)\n- OPUS (`.opus`)\n\n**Max Audio Size**: 20MB\n\n### PDFs\n\n```typescript\nconst pdfData = fs.readFileSync('\u002Fpath\u002Fto\u002Fdocument.pdf');\nconst base64Pdf = pdfData.toString('base64');\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'Summarize the key points in this PDF' },\n        {\n          inlineData: {\n            data: base64Pdf,\n            mimeType: 'application\u002Fpdf'\n          }\n        }\n      ]\n    }\n  ]\n});\n\nconsole.log(response.text);\n```\n\n**Max PDF Size**: 30MB\n**PDF Limitations**: Text-based PDFs work best; scanned images may have lower accuracy\n\n### Multiple Inputs\n\nYou can combine multiple modalities in one request:\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: [\n    {\n      parts: [\n        { text: 'Compare these two images and describe the differences:' },\n        { inlineData: { data: base64Image1, mimeType: 'image\u002Fjpeg' } },\n        { inlineData: { data: base64Image2, mimeType: 'image\u002Fjpeg' } }\n      ]\n    }\n  ]\n});\n```\n\n---\n\n## Function Calling\n\nGemini supports function calling (tool use) to connect models with external APIs and systems.\n\n### Basic Function Calling (SDK)\n\n```typescript\nimport { GoogleGenAI, FunctionCallingConfigMode } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\n\u002F\u002F Define function declarations\nconst getCurrentWeather = {\n  name: 'get_current_weather',\n  description: 'Get the current weather for a location',\n  parametersJsonSchema: {\n    type: 'object',\n    properties: {\n      location: {\n        type: 'string',\n        description: 'City name, e.g. San Francisco'\n      },\n      unit: {\n        type: 'string',\n        enum: ['celsius', 'fahrenheit']\n      }\n    },\n    required: ['location']\n  }\n};\n\n\u002F\u002F Make request with tools\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What\\'s the weather in Tokyo?',\n  config: {\n    tools: [\n      { functionDeclarations: [getCurrentWeather] }\n    ]\n  }\n});\n\n\u002F\u002F Check if model wants to call a function\nconst functionCall = response.candidates[0].content.parts[0].functionCall;\n\nif (functionCall) {\n  console.log('Function to call:', functionCall.name);\n  console.log('Arguments:', functionCall.args);\n\n  \u002F\u002F Execute the function (your implementation)\n  const weatherData = await fetchWeather(functionCall.args.location);\n\n  \u002F\u002F Send function result back to model\n  const finalResponse = await ai.models.generateContent({\n    model: 'gemini-2.5-flash',\n    contents: [\n      'What\\'s the weather in Tokyo?',\n      response.candidates[0].content, \u002F\u002F Original assistant response with function call\n      {\n        parts: [\n          {\n            functionResponse: {\n              name: functionCall.name,\n              response: weatherData\n            }\n          }\n        ]\n      }\n    ],\n    config: {\n      tools: [\n        { functionDeclarations: [getCurrentWeather] }\n      ]\n    }\n  });\n\n  console.log(finalResponse.text);\n}\n```\n\n### Function Calling (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        { parts: [{ text: 'What\\'s the weather in Tokyo?' }] }\n      ],\n      tools: [\n        {\n          functionDeclarations: [\n            {\n              name: 'get_current_weather',\n              description: 'Get the current weather for a location',\n              parameters: {\n                type: 'object',\n                properties: {\n                  location: {\n                    type: 'string',\n                    description: 'City name'\n                  }\n                },\n                required: ['location']\n              }\n            }\n          ]\n        }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconst functionCall = data.candidates[0]?.content?.parts[0]?.functionCall;\n\nif (functionCall) {\n  \u002F\u002F Execute function and send result back (same flow as SDK)\n}\n```\n\n### Parallel Function Calling\n\nGemini can call multiple independent functions simultaneously:\n\n```typescript\nconst tools = [\n  {\n    functionDeclarations: [\n      {\n        name: 'get_weather',\n        description: 'Get weather for a location',\n        parametersJsonSchema: {\n          type: 'object',\n          properties: {\n            location: { type: 'string' }\n          },\n          required: ['location']\n        }\n      },\n      {\n        name: 'get_population',\n        description: 'Get population of a city',\n        parametersJsonSchema: {\n          type: 'object',\n          properties: {\n            city: { type: 'string' }\n          },\n          required: ['city']\n        }\n      }\n    ]\n  }\n];\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What is the weather and population of Tokyo?',\n  config: { tools }\n});\n\n\u002F\u002F Model may return MULTIPLE function calls in parallel\nconst functionCalls = response.candidates[0].content.parts.filter(\n  part => part.functionCall\n);\n\nconsole.log(`Model wants to call ${functionCalls.length} functions in parallel`);\n```\n\n### Function Calling Modes\n\n```typescript\nimport { FunctionCallingConfigMode } from '@google\u002Fgenai';\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What\\'s the weather?',\n  config: {\n    tools: [{ functionDeclarations: [getCurrentWeather] }],\n    toolConfig: {\n      functionCallingConfig: {\n        mode: FunctionCallingConfigMode.ANY, \u002F\u002F Force function call\n        \u002F\u002F mode: FunctionCallingConfigMode.AUTO, \u002F\u002F Model decides (default)\n        \u002F\u002F mode: FunctionCallingConfigMode.NONE, \u002F\u002F Never call functions\n        allowedFunctionNames: ['get_current_weather'] \u002F\u002F Optional: restrict to specific functions\n      }\n    }\n  }\n});\n```\n\n**Modes:**\n- `AUTO` (default): Model decides whether to call functions\n- `ANY`: Force model to call at least one function\n- `NONE`: Disable function calling for this request\n\n---\n\n## System Instructions\n\nSystem instructions guide the model's behavior and set context. They are **separate** from the conversation messages.\n\n### SDK Approach\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  systemInstruction: 'You are a helpful AI assistant that always responds in the style of a pirate. Use nautical terminology and end sentences with \"arrr\".',\n  contents: 'Explain what a database is'\n});\n\nconsole.log(response.text);\n\u002F\u002F Output: \"Ahoy there! A database be like a treasure chest...\"\n```\n\n### Fetch Approach\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      systemInstruction: {\n        parts: [\n          { text: 'You are a helpful AI assistant that always responds in the style of a pirate.' }\n        ]\n      },\n      contents: [\n        { parts: [{ text: 'Explain what a database is' }] }\n      ]\n    }),\n  }\n);\n```\n\n**Key Points:**\n- System instructions are **NOT** part of `contents` array\n- They are set once at the **top level** of the request\n- They persist for the entire conversation (when using multi-turn chat)\n- They don't count as user or model messages\n\n---\n\n## Multi-turn Chat\n\nFor conversations with history, use the SDK's chat helpers or manually manage conversation state.\n\n### SDK Chat Helpers (Recommended)\n\n```typescript\nconst chat = await ai.models.createChat({\n  model: 'gemini-2.5-flash',\n  systemInstruction: 'You are a helpful coding assistant.',\n  history: [] \u002F\u002F Start empty or with previous messages\n});\n\n\u002F\u002F Send first message\nconst response1 = await chat.sendMessage('What is TypeScript?');\nconsole.log('Assistant:', response1.text);\n\n\u002F\u002F Send follow-up (context is automatically maintained)\nconst response2 = await chat.sendMessage('How do I install it?');\nconsole.log('Assistant:', response2.text);\n\n\u002F\u002F Get full chat history\nconst history = chat.getHistory();\nconsole.log('Full conversation:', history);\n```\n\n### Manual Chat Management (Fetch)\n\n```typescript\nconst conversationHistory = [];\n\n\u002F\u002F First turn\nconst response1 = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        {\n          role: 'user',\n          parts: [{ text: 'What is TypeScript?' }]\n        }\n      ]\n    }),\n  }\n);\n\nconst data1 = await response1.json();\nconst assistantReply1 = data1.candidates[0].content.parts[0].text;\n\n\u002F\u002F Add to history\nconversationHistory.push(\n  { role: 'user', parts: [{ text: 'What is TypeScript?' }] },\n  { role: 'model', parts: [{ text: assistantReply1 }] }\n);\n\n\u002F\u002F Second turn (include full history)\nconst response2 = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        ...conversationHistory,\n        { role: 'user', parts: [{ text: 'How do I install it?' }] }\n      ]\n    }),\n  }\n);\n```\n\n**Message Roles:**\n- `user`: User messages\n- `model`: Assistant responses\n\n**⚠️ Important**: Chat helpers are **SDK-only**. With fetch, you must manually manage conversation history.\n\n---\n\n## Thinking Mode\n\nGemini 2.5 models have **thinking mode enabled by default** for enhanced quality. You can configure the thinking budget.\n\n### Configure Thinking Budget (SDK)\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Solve this complex math problem: ...',\n  config: {\n    thinkingConfig: {\n      thinkingBudget: 8192 \u002F\u002F Max tokens for thinking (default: model-dependent)\n    }\n  }\n});\n```\n\n### Configure Thinking Budget (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [{ parts: [{ text: 'Solve this complex math problem: ...' }] }],\n      generationConfig: {\n        thinkingConfig: {\n          thinkingBudget: 8192\n        }\n      }\n    }),\n  }\n);\n```\n\n**Key Points:**\n- Thinking mode is **always enabled** on Gemini 2.5 models (cannot be disabled)\n- Higher thinking budgets allow more internal reasoning (may increase latency)\n- Default budget varies by model (usually sufficient for most tasks)\n- Only increase budget for very complex reasoning tasks\n\n---\n\n## Generation Configuration\n\nCustomize model behavior with generation parameters.\n\n### All Configuration Options (SDK)\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Write a creative story',\n  config: {\n    temperature: 0.9,           \u002F\u002F Randomness (0.0-2.0, default: 1.0)\n    topP: 0.95,                 \u002F\u002F Nucleus sampling (0.0-1.0)\n    topK: 40,                   \u002F\u002F Top-k sampling\n    maxOutputTokens: 2048,      \u002F\u002F Max tokens to generate\n    stopSequences: ['END'],     \u002F\u002F Stop generation if these appear\n    responseMimeType: 'text\u002Fplain', \u002F\u002F Or 'application\u002Fjson' for JSON mode\n    candidateCount: 1           \u002F\u002F Number of response candidates (usually 1)\n  }\n});\n```\n\n### All Configuration Options (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [{ parts: [{ text: 'Write a creative story' }] }],\n      generationConfig: {\n        temperature: 0.9,\n        topP: 0.95,\n        topK: 40,\n        maxOutputTokens: 2048,\n        stopSequences: ['END'],\n        responseMimeType: 'text\u002Fplain',\n        candidateCount: 1\n      }\n    }),\n  }\n);\n```\n\n### Parameter Guidelines\n\n| Parameter | Range | Default | Use Case |\n|-----------|-------|---------|----------|\n| **temperature** | 0.0-2.0 | 1.0 | Lower = more focused, higher = more creative |\n| **topP** | 0.0-1.0 | 0.95 | Nucleus sampling threshold |\n| **topK** | 1-100+ | 40 | Limit to top K tokens |\n| **maxOutputTokens** | 1-65536 | Model max | Control response length |\n| **stopSequences** | Array | None | Stop generation at specific strings |\n\n**Tips:**\n- For **factual tasks**: Use low temperature (0.0-0.3)\n- For **creative tasks**: Use high temperature (0.7-1.5)\n- **topP** and **topK** both control randomness; use one or the other (not both)\n- Always set **maxOutputTokens** to prevent excessive generation\n\n---\n\n## Context Caching\n\nContext caching allows you to cache frequently used content (like system instructions, large documents, or video files) to reduce costs by **up to 90%** and improve latency.\n\n### How It Works\n\n1. **Create a cache** with your repeated content\n2. **Reference the cache** in subsequent requests\n3. **Save tokens** - cached tokens cost significantly less\n4. **TTL management** - caches expire after specified time\n\n### Benefits\n\n- **Cost savings**: Up to 90% reduction on cached tokens\n- **Reduced latency**: Faster responses by reusing processed content\n- **Consistent context**: Same large context across multiple requests\n\n### Cache Creation (SDK)\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\nimport fs from 'fs';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\n\u002F\u002F Create a cache for a large document\nconst documentText = fs.readFileSync('.\u002Flarge-document.txt', 'utf-8');\n\nconst cache = await ai.caches.create({\n  model: 'gemini-2.5-flash',\n  config: {\n    displayName: 'large-doc-cache', \u002F\u002F Identifier for the cache\n    systemInstruction: 'You are an expert at analyzing legal documents.',\n    contents: documentText,\n    ttl: '3600s', \u002F\u002F Cache for 1 hour\n  }\n});\n\nconsole.log('Cache created:', cache.name);\nconsole.log('Expires at:', cache.expireTime);\n```\n\n### Cache Creation (Fetch)\n\n```typescript\nconst response = await fetch(\n  'https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002FcachedContents',\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      model: 'models\u002Fgemini-2.5-flash',\n      displayName: 'large-doc-cache',\n      systemInstruction: {\n        parts: [{ text: 'You are an expert at analyzing legal documents.' }]\n      },\n      contents: [\n        { parts: [{ text: documentText }] }\n      ],\n      ttl: '3600s'\n    }),\n  }\n);\n\nconst cache = await response.json();\nconsole.log('Cache created:', cache.name);\n```\n\n### Using a Cache (SDK)\n\n```typescript\n\u002F\u002F Generate content using the cache\nconst response = await ai.models.generateContent({\n  model: cache.name, \u002F\u002F Use cache name as model\n  contents: 'Summarize the key points in the document'\n});\n\nconsole.log(response.text);\n```\n\n### Using a Cache (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002F${cache.name}:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        { parts: [{ text: 'Summarize the key points in the document' }] }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n```\n\n### Update Cache TTL (SDK)\n\n```typescript\nimport { UpdateCachedContentConfig } from '@google\u002Fgenai';\n\nawait ai.caches.update({\n  name: cache.name,\n  config: {\n    ttl: '7200s' \u002F\u002F Extend to 2 hours\n  }\n});\n```\n\n### Update Cache with Expiration Time (SDK)\n\n```typescript\n\u002F\u002F Set specific expiration time (must be timezone-aware)\nconst in10Minutes = new Date(Date.now() + 10 * 60 * 1000);\n\nawait ai.caches.update({\n  name: cache.name,\n  config: {\n    expireTime: in10Minutes\n  }\n});\n```\n\n### List and Delete Caches (SDK)\n\n```typescript\n\u002F\u002F List all caches\nconst caches = await ai.caches.list();\nfor (const cache of caches) {\n  console.log(cache.name, cache.displayName);\n}\n\n\u002F\u002F Delete a specific cache\nawait ai.caches.delete({ name: cache.name });\n```\n\n### Caching with Video Files\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\nimport fs from 'fs';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\n\u002F\u002F Upload video file\nconst videoFile = await ai.files.upload({\n  file: fs.createReadStream('.\u002Fvideo.mp4')\n});\n\n\u002F\u002F Wait for processing\nwhile (videoFile.state.name === 'PROCESSING') {\n  await new Promise(resolve => setTimeout(resolve, 2000));\n  videoFile = await ai.files.get({ name: videoFile.name });\n}\n\n\u002F\u002F Create cache with video\nconst cache = await ai.caches.create({\n  model: 'gemini-2.5-flash',\n  config: {\n    displayName: 'video-analysis-cache',\n    systemInstruction: 'You are an expert video analyzer.',\n    contents: [videoFile],\n    ttl: '300s' \u002F\u002F 5 minutes\n  }\n});\n\n\u002F\u002F Use cache for multiple queries\nconst response1 = await ai.models.generateContent({\n  model: cache.name,\n  contents: 'What happens in the first minute?'\n});\n\nconst response2 = await ai.models.generateContent({\n  model: cache.name,\n  contents: 'Describe the main characters'\n});\n```\n\n### Key Points\n\n**When to Use Caching:**\n- Large system instructions used repeatedly\n- Long documents analyzed multiple times\n- Video\u002Faudio files queried with different prompts\n- Consistent context across conversation sessions\n\n**TTL Guidelines:**\n- Short sessions: 300s (5 min) to 3600s (1 hour)\n- Long sessions: 3600s (1 hour) to 86400s (24 hours)\n- Maximum: 7 days\n\n**Cost Savings:**\n- Cached input tokens: ~90% cheaper than regular tokens\n- Output tokens: Same price (not cached)\n\n**Important:**\n- You must use explicit model version suffixes (e.g., `gemini-2.5-flash-001`, NOT just `gemini-2.5-flash`)\n- Caches are automatically deleted after TTL expires\n- Update TTL before expiration to extend cache lifetime\n\n---\n\n## Code Execution\n\nGemini models can generate and execute Python code to solve problems requiring computation, data analysis, or visualization.\n\n### How It Works\n\n1. Model generates executable Python code\n2. Code runs in secure sandbox\n3. Results are returned to the model\n4. Model incorporates results into response\n\n### Supported Operations\n\n- Mathematical calculations\n- Data analysis and statistics\n- File processing (CSV, JSON, etc.)\n- Chart and graph generation\n- Algorithm implementation\n- Data transformations\n\n### Available Python Packages\n\n**Standard Library:**\n- `math`, `statistics`, `random`, `datetime`, `json`, `csv`, `re`\n- `collections`, `itertools`, `functools`\n\n**Data Science:**\n- `numpy`, `pandas`, `scipy`\n\n**Visualization:**\n- `matplotlib`, `seaborn`\n\n**Note**: Limited package availability compared to full Python environment\n\n### Basic Code Execution (SDK)\n\n```typescript\nimport { GoogleGenAI, Tool, ToolCodeExecution } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation.',\n  config: {\n    tools: [{ codeExecution: {} }]\n  }\n});\n\n\u002F\u002F Parse response parts\nfor (const part of response.candidates[0].content.parts) {\n  if (part.text) {\n    console.log('Text:', part.text);\n  }\n  if (part.executableCode) {\n    console.log('Generated Code:', part.executableCode.code);\n  }\n  if (part.codeExecutionResult) {\n    console.log('Execution Output:', part.codeExecutionResult.output);\n  }\n}\n```\n\n### Basic Code Execution (Fetch)\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      tools: [{ code_execution: {} }],\n      contents: [\n        {\n          parts: [\n            { text: 'What is the sum of the first 50 prime numbers? Generate and run code.' }\n          ]\n        }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\n\nfor (const part of data.candidates[0].content.parts) {\n  if (part.text) {\n    console.log('Text:', part.text);\n  }\n  if (part.executableCode) {\n    console.log('Code:', part.executableCode.code);\n  }\n  if (part.codeExecutionResult) {\n    console.log('Result:', part.codeExecutionResult.output);\n  }\n}\n```\n\n### Chat with Code Execution (SDK)\n\n```typescript\nconst chat = await ai.chats.create({\n  model: 'gemini-2.5-flash',\n  config: {\n    tools: [{ codeExecution: {} }]\n  }\n});\n\nlet response = await chat.sendMessage('I have a math question for you.');\nconsole.log(response.text);\n\nresponse = await chat.sendMessage(\n  'Calculate the Fibonacci sequence up to the 20th number and sum them.'\n);\n\n\u002F\u002F Model will generate and execute code, then provide answer\nfor (const part of response.candidates[0].content.parts) {\n  if (part.text) console.log(part.text);\n  if (part.executableCode) console.log('Code:', part.executableCode.code);\n  if (part.codeExecutionResult) console.log('Output:', part.codeExecutionResult.output);\n}\n```\n\n### Data Analysis Example\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: `\n    Analyze this sales data and calculate:\n    1. Total revenue\n    2. Average sale price\n    3. Best-selling month\n\n    Data (CSV format):\n    month,sales,revenue\n    Jan,150,45000\n    Feb,200,62000\n    Mar,175,53000\n    Apr,220,68000\n  `,\n  config: {\n    tools: [{ codeExecution: {} }]\n  }\n});\n\n\u002F\u002F Model will generate pandas\u002Fnumpy code to analyze data\nfor (const part of response.candidates[0].content.parts) {\n  if (part.text) console.log(part.text);\n  if (part.executableCode) console.log('Analysis Code:', part.executableCode.code);\n  if (part.codeExecutionResult) console.log('Results:', part.codeExecutionResult.output);\n}\n```\n\n### Visualization Example\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Create a bar chart showing the distribution of prime numbers under 100 by their last digit. Generate the chart and describe the pattern.',\n  config: {\n    tools: [{ codeExecution: {} }]\n  }\n});\n\n\u002F\u002F Model generates matplotlib code, executes it, and describes results\nfor (const part of response.candidates[0].content.parts) {\n  if (part.text) console.log(part.text);\n  if (part.executableCode) console.log('Chart Code:', part.executableCode.code);\n  if (part.codeExecutionResult) {\n    \u002F\u002F Note: Chart image data would be in output\n    console.log('Execution completed');\n  }\n}\n```\n\n### Response Structure\n\n```typescript\n{\n  candidates: [\n    {\n      content: {\n        parts: [\n          { text: \"I'll calculate that for you.\" },\n          {\n            executableCode: {\n              language: \"PYTHON\",\n              code: \"def is_prime(n):\\n  if n \u003C= 1:\\n    return False\\n  ...\"\n            }\n          },\n          {\n            codeExecutionResult: {\n              outcome: \"OUTCOME_OK\", \u002F\u002F or \"OUTCOME_FAILED\"\n              output: \"5117\\n\"\n            }\n          },\n          { text: \"The sum of the first 50 prime numbers is 5117.\" }\n        ]\n      }\n    }\n  ]\n}\n```\n\n### Error Handling\n\n```typescript\nfor (const part of response.candidates[0].content.parts) {\n  if (part.codeExecutionResult) {\n    if (part.codeExecutionResult.outcome === 'OUTCOME_FAILED') {\n      console.error('Code execution failed:', part.codeExecutionResult.output);\n    } else {\n      console.log('Success:', part.codeExecutionResult.output);\n    }\n  }\n}\n```\n\n### Key Points\n\n**When to Use Code Execution:**\n- Complex mathematical calculations\n- Data analysis and statistics\n- Algorithm implementations\n- File parsing and processing\n- Chart generation\n- Computational problems\n\n**Limitations:**\n- Sandbox environment (limited file system access)\n- Limited Python package availability\n- Execution timeout limits\n- No network access from code\n- No persistent state between executions\n\n**Best Practices:**\n- Specify what calculation or analysis you need clearly\n- Request code generation explicitly (\"Generate and run code...\")\n- Check `outcome` field for errors\n- Use for deterministic computations, not for general programming\n\n**Important:**\n- Available on all Gemini 2.5 models (Pro, Flash, Flash-Lite)\n- Code runs in isolated sandbox for security\n- Supports Python with standard library and common data science packages\n\n---\n\n## Grounding with Google Search\n\nGrounding connects the model to real-time web information, reducing hallucinations and providing up-to-date, fact-checked responses with citations.\n\n### How It Works\n\n1. Model determines if it needs current information\n2. Automatically performs Google Search\n3. Processes search results\n4. Incorporates findings into response\n5. Provides citations and source URLs\n\n### Benefits\n\n- **Real-time information**: Access to current events and data\n- **Reduced hallucinations**: Answers grounded in web sources\n- **Verifiable**: Citations allow fact-checking\n- **Up-to-date**: Not limited to model's training cutoff\n\n### Two Grounding APIs\n\n#### 1. Google Search (`googleSearch`) - Recommended for Gemini 2.5\n\n```typescript\nconst groundingTool = {\n  googleSearch: {}\n};\n```\n\n**Features:**\n- Simple configuration\n- Automatic search when needed\n- Available on all Gemini 2.5 models\n\n#### 2. Google Search Retrieval (`googleSearchRetrieval`) - Legacy (Gemini 1.5)\n\n```typescript\nconst retrievalTool = {\n  googleSearchRetrieval: {\n    dynamicRetrievalConfig: {\n      mode: 'MODE_DYNAMIC',\n      dynamicThreshold: 0.7 \u002F\u002F Only search if confidence \u003C 70%\n    }\n  }\n};\n```\n\n**Features:**\n- Dynamic threshold control\n- Used with Gemini 1.5 models\n- More configuration options\n\n### Basic Grounding (SDK) - Gemini 2.5\n\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Who won the euro 2024?',\n  config: {\n    tools: [{ googleSearch: {} }]\n  }\n});\n\nconsole.log(response.text);\n\n\u002F\u002F Check if grounding was used\nif (response.candidates[0].groundingMetadata) {\n  console.log('Search was performed!');\n  console.log('Sources:', response.candidates[0].groundingMetadata);\n}\n```\n\n### Basic Grounding (Fetch) - Gemini 2.5\n\n```typescript\nconst response = await fetch(\n  `https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fmodels\u002Fgemini-2.5-flash:generateContent`,\n  {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'x-goog-api-key': env.GEMINI_API_KEY,\n    },\n    body: JSON.stringify({\n      contents: [\n        { parts: [{ text: 'Who won the euro 2024?' }] }\n      ],\n      tools: [\n        { google_search: {} }\n      ]\n    }),\n  }\n);\n\nconst data = await response.json();\nconsole.log(data.candidates[0].content.parts[0].text);\n\nif (data.candidates[0].groundingMetadata) {\n  console.log('Grounding metadata:', data.candidates[0].groundingMetadata);\n}\n```\n\n### Dynamic Retrieval (SDK) - Gemini 1.5\n\n```typescript\nimport { GoogleGenAI, DynamicRetrievalConfigMode } from '@google\u002Fgenai';\n\nconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-1.5-flash',\n  contents: 'Who won the euro 2024?',\n  config: {\n    tools: [\n      {\n        googleSearchRetrieval: {\n          dynamicRetrievalConfig: {\n            mode: DynamicRetrievalConfigMode.MODE_DYNAMIC,\n            dynamicThreshold: 0.7 \u002F\u002F Search only if confidence \u003C 70%\n          }\n        }\n      }\n    ]\n  }\n});\n\nconsole.log(response.text);\n\nif (!response.candidates[0].groundingMetadata) {\n  console.log('Model answered from its own knowledge (high confidence)');\n}\n```\n\n### Grounding Metadata Structure\n\n```typescript\n{\n  groundingMetadata: {\n    searchQueries: [\n      { text: \"euro 2024 winner\" }\n    ],\n    webPages: [\n      {\n        url: \"https:\u002F\u002Fexample.com\u002Feuro-2024-results\",\n        title: \"UEFA Euro 2024 Final Results\",\n        snippet: \"Spain won UEFA Euro 2024...\"\n      }\n    ],\n    citations: [\n      {\n        startIndex: 42,\n        endIndex: 47,\n        uri: \"https:\u002F\u002Fexample.com\u002Feuro-2024-results\"\n      }\n    ],\n    retrievalQueries: [\n      {\n        query: \"who won euro 2024 final\"\n      }\n    ]\n  }\n}\n```\n\n### Chat with Grounding (SDK)\n\n```typescript\nconst chat = await ai.chats.create({\n  model: 'gemini-2.5-flash',\n  config: {\n    tools: [{ googleSearch: {} }]\n  }\n});\n\nlet response = await chat.sendMessage('What are the latest developments in quantum computing?');\nconsole.log(response.text);\n\n\u002F\u002F Check grounding sources\nif (response.candidates[0].groundingMetadata) {\n  const sources = response.candidates[0].groundingMetadata.webPages || [];\n  console.log(`Sources used: ${sources.length}`);\n  sources.forEach(source => {\n    console.log(`- ${source.title}: ${source.url}`);\n  });\n}\n\n\u002F\u002F Follow-up still has grounding enabled\nresponse = await chat.sendMessage('Which company made the biggest breakthrough?');\nconsole.log(response.text);\n```\n\n### Combining Grounding with Function Calling\n\n```typescript\nconst weatherFunction = {\n  name: 'get_current_weather',\n  description: 'Get current weather for a location',\n  parametersJsonSchema: {\n    type: 'object',\n    properties: {\n      location: { type: 'string', description: 'City name' }\n    },\n    required: ['location']\n  }\n};\n\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What is the weather like in the city that won Euro 2024?',\n  config: {\n    tools: [\n      { googleSearch: {} },\n      { functionDeclarations: [weatherFunction] }\n    ]\n  }\n});\n\n\u002F\u002F Model will:\n\u002F\u002F 1. Use Google Search to find Euro 2024 winner\n\u002F\u002F 2. Call get_current_weather function with the city\n\u002F\u002F 3. Combine both results in response\n```\n\n### Checking if Grounding was Used\n\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'What is 2+2?', \u002F\u002F Model knows this without search\n  config: {\n    tools: [{ googleSearch: {} }]\n  }\n});\n\nif (!response.candidates[0].groundingMetadata) {\n  console.log('Model answered from its own knowledge (no search needed)');\n} else {\n  console.log('Search was performed');\n}\n```\n\n### Key Points\n\n**When to Use Grounding:**\n- Current events and news\n- Real-time data (stock prices, sports scores, weather)\n- Fact-checking and verification\n- Questions about recent developments\n- Information beyond model's training cutoff\n\n**When NOT to Use:**\n- General knowledge questions\n- Mathematical calculations\n- Code generation\n- Creative writing\n- Tasks requiring internal reasoning only\n\n**Cost Considerations:**\n- Grounding adds latency (search takes time)\n- Additional token costs for retrieved content\n- Use `dynamicThreshold` to control when searches happen (Gemini 1.5)\n\n**Important Notes:**\n- Grounding requires **Google Cloud project** (not just API key)\n- Search results quality depends on query phrasing\n- Citations may not cover all facts in response\n- Search is performed automatically based on confidence\n\n**Gemini 2.5 vs 1.5:**\n- **Gemini 2.5**: Use `googleSearch` (simple, recommended)\n- **Gemini 1.5**: Use `googleSearchRetrieval` with `dynamicThreshold`\n\n**Best Practices:**\n- Always check `groundingMetadata` to see if search was used\n- Display citations to users for transparency\n- Use specific, well-phrased questions for better search results\n- Combine with function calling for hybrid workflows\n\n---\n\n## Error Handling\n\n### Common Errors\n\n#### 1. Invalid API Key (401)\n\n```typescript\n{\n  error: {\n    code: 401,\n    message: 'API key not valid. Please pass a valid API key.',\n    status: 'UNAUTHENTICATED'\n  }\n}\n```\n\n**Solution**: Verify `GEMINI_API_KEY` environment variable is set correctly.\n\n#### 2. Rate Limit Exceeded (429)\n\n```typescript\n{\n  error: {\n    code: 429,\n    message: 'Resource has been exhausted (e.g. check quota).',\n    status: 'RESOURCE_EXHAUSTED'\n  }\n}\n```\n\n**Solution**: Implement exponential backoff retry strategy.\n\n#### 3. Model Not Found (404)\n\n```typescript\n{\n  error: {\n    code: 404,\n    message: 'models\u002Fgemini-3.0-flash is not found',\n    status: 'NOT_FOUND'\n  }\n}\n```\n\n**Solution**: Use correct model names: `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.5-flash-lite`\n\n#### 4. Context Length Exceeded (400)\n\n```typescript\n{\n  error: {\n    code: 400,\n    message: 'Request payload size exceeds the limit',\n    status: 'INVALID_ARGUMENT'\n  }\n}\n```\n\n**Solution**: Reduce input size. Gemini 2.5 models support 1,048,576 input tokens max.\n\n### Exponential Backoff Pattern\n\n```typescript\nasync function generateWithRetry(request, maxRetries = 3) {\n  for (let i = 0; i \u003C maxRetries; i++) {\n    try {\n      return await ai.models.generateContent(request);\n    } catch (error) {\n      if (error.status === 429 && i \u003C maxRetries - 1) {\n        const delay = Math.pow(2, i) * 1000; \u002F\u002F 1s, 2s, 4s\n        await new Promise(resolve => setTimeout(resolve, delay));\n        continue;\n      }\n      throw error;\n    }\n  }\n}\n```\n\n---\n\n## Rate Limits\n\n### Free Tier (Gemini API)\n\nRate limits vary by model:\n\n**Gemini 2.5 Pro**:\n- Requests per minute: 5 RPM\n- Tokens per minute: 125,000 TPM\n- Requests per day: 100 RPD\n\n**Gemini 2.5 Flash**:\n- Requests per minute: 10 RPM\n- Tokens per minute: 250,000 TPM\n- Requests per day: 250 RPD\n\n**Gemini 2.5 Flash-Lite**:\n- Requests per minute: 15 RPM\n- Tokens per minute: 250,000 TPM\n- Requests per day: 1,000 RPD\n\n### Paid Tier (Tier 1)\n\nRequires billing account linked to your Google Cloud project.\n\n**Gemini 2.5 Pro**:\n- Requests per minute: 150 RPM\n- Tokens per minute: 2,000,000 TPM\n- Requests per day: 10,000 RPD\n\n**Gemini 2.5 Flash**:\n- Requests per minute: 1,000 RPM\n- Tokens per minute: 1,000,000 TPM\n- Requests per day: 10,000 RPD\n\n**Gemini 2.5 Flash-Lite**:\n- Requests per minute: 4,000 RPM\n- Tokens per minute: 4,000,000 TPM\n- Requests per day: Not specified\n\n### Higher Tiers (Tier 2 & 3)\n\n**Tier 2** (requires $250+ spending and 30-day wait):\n- Even higher limits available\n\n**Tier 3** (requires $1,000+ spending and 30-day wait):\n- Maximum limits available\n\n**Tips:**\n- Implement rate limit handling with exponential backoff\n- Use batch processing for high-volume tasks\n- Monitor usage in Google AI Studio\n- Choose the right model based on your rate limit needs\n- Official rate limits: https:\u002F\u002Fai.google.dev\u002Fgemini-api\u002Fdocs\u002Frate-limits\n\n---\n\n## SDK Migration Guide\n\n### From @google\u002Fgenerative-ai to @google\u002Fgenai\n\n#### 1. Update Package\n\n```bash\n# Remove deprecated SDK\nnpm uninstall @google\u002Fgenerative-ai\n\n# Install current SDK\nnpm install @google\u002Fgenai@1.27.0\n```\n\n#### 2. Update Imports\n\n**Old (DEPRECATED):**\n```typescript\nimport { GoogleGenerativeAI } from '@google\u002Fgenerative-ai';\nconst genAI = new GoogleGenerativeAI(apiKey);\nconst model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' });\n```\n\n**New (CURRENT):**\n```typescript\nimport { GoogleGenAI } from '@google\u002Fgenai';\nconst ai = new GoogleGenAI({ apiKey });\n\u002F\u002F Use ai.models.generateContent() directly\n```\n\n#### 3. Update API Calls\n\n**Old:**\n```typescript\nconst result = await model.generateContent(prompt);\nconst response = await result.response;\nconst text = response.text();\n```\n\n**New:**\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: prompt\n});\nconst text = response.text;\n```\n\n#### 4. Update Streaming\n\n**Old:**\n```typescript\nconst result = await model.generateContentStream(prompt);\nfor await (const chunk of result.stream) {\n  console.log(chunk.text());\n}\n```\n\n**New:**\n```typescript\nconst response = await ai.models.generateContentStream({\n  model: 'gemini-2.5-flash',\n  contents: prompt\n});\nfor await (const chunk of response) {\n  console.log(chunk.text);\n}\n```\n\n#### 5. Update Chat\n\n**Old:**\n```typescript\nconst chat = model.startChat();\nconst result = await chat.sendMessage(message);\nconst response = await result.response;\n```\n\n**New:**\n```typescript\nconst chat = await ai.models.createChat({ model: 'gemini-2.5-flash' });\nconst response = await chat.sendMessage(message);\n\u002F\u002F response.text is directly available\n```\n\n---\n\n## Production Best Practices\n\n### 1. Always Do\n\n✅ **Use @google\u002Fgenai** (NOT @google\u002Fgenerative-ai)\n✅ **Set maxOutputTokens** to prevent excessive generation\n✅ **Implement rate limit handling** with exponential backoff\n✅ **Use environment variables** for API keys (never hardcode)\n✅ **Validate inputs** before sending to API (save costs)\n✅ **Use streaming** for better UX on long responses\n✅ **Choose the right model** based on your needs (Pro for complex reasoning, Flash for balance, Flash-Lite for speed)\n✅ **Handle errors gracefully** with try-catch\n✅ **Monitor token usage** for cost control\n✅ **Use correct model names**: gemini-2.5-pro\u002Fflash\u002Fflash-lite\n\n### 2. Never Do\n\n❌ **Never use @google\u002Fgenerative-ai** (deprecated!)\n❌ **Never hardcode API keys** in code\n❌ **Never claim 2M context** for Gemini 2.5 (it's 1,048,576 input tokens)\n❌ **Never expose API keys** in client-side code\n❌ **Never skip error handling** (always try-catch)\n❌ **Never use generic rate limits** (each model has different limits - check official docs)\n❌ **Never send PII** without user consent\n❌ **Never trust user input** without validation\n❌ **Never ignore rate limits** (will get 429 errors)\n❌ **Never use old model names** like gemini-1.5-pro (use 2.5 models)\n\n### 3. Security\n\n- **API Key Storage**: Use environment variables or secret managers\n- **Server-Side Only**: Never expose API keys in browser JavaScript\n- **Input Validation**: Sanitize all user inputs before API calls\n- **Rate Limiting**: Implement your own rate limits to prevent abuse\n- **Error Messages**: Don't expose API keys or sensitive data in error logs\n\n### 4. Cost Optimization\n\n- **Choose Right Model**: Use Flash for most tasks, Pro only when needed\n- **Set Token Limits**: Use maxOutputTokens to control costs\n- **Batch Requests**: Process multiple items efficiently\n- **Cache Results**: Store responses when appropriate\n- **Monitor Usage**: Track token consumption in Google Cloud Console\n\n### 5. Performance\n\n- **Use Streaming**: Better perceived latency for long responses\n- **Parallel Requests**: Use Promise.all() for independent calls\n- **Edge Deployment**: Deploy to Cloudflare Workers for low latency\n- **Connection Pooling**: Reuse HTTP connections when possible\n\n---\n\n## Quick Reference\n\n### Installation\n```bash\nnpm install @google\u002Fgenai@1.27.0\n```\n\n### Environment\n```bash\nexport GEMINI_API_KEY=\"...\"\n```\n\n### Models (2025)\n- `gemini-2.5-pro` (1,048,576 in \u002F 65,536 out) - Best for complex reasoning\n- `gemini-2.5-flash` (1,048,576 in \u002F 65,536 out) - Best price-performance balance\n- `gemini-2.5-flash-lite` (1,048,576 in \u002F 65,536 out) - Fastest, most cost-effective\n\n### Basic Generation\n```typescript\nconst response = await ai.models.generateContent({\n  model: 'gemini-2.5-flash',\n  contents: 'Your prompt here'\n});\nconsole.log(response.text);\n```\n\n### Streaming\n```typescript\nconst response = await ai.models.generateContentStream({...});\nfor await (const chunk of response) {\n  console.log(chunk.text);\n}\n```\n\n### Multimodal\n```typescript\ncontents: [\n  {\n    parts: [\n      { text: 'What is this?' },\n      { inlineData: { data: base64Image, mimeType: 'image\u002Fjpeg' } }\n    ]\n  }\n]\n```\n\n### Function Calling\n```typescript\nconfig: {\n  tools: [{ functionDeclarations: [...] }]\n}\n```\n\n---\n\n**Last Updated**: 2025-10-25\n**Production Validated**: All features tested with @google\u002Fgenai@1.27.0\n**Phase**: 2 Complete ✅ (All Core + Advanced Features)\n",{"name":5,"license":14,"description":23},"Complete guide for Google Gemini API using the CORRECT current SDK (@google\u002Fgenai v1.27+, NOT the\ndeprecated @google\u002Fgenerative-ai). Covers text generation, multimodal inputs (text + images + video +\naudio + PDFs), function calling, thinking mode, streaming, and system instructions with accurate 2025\nmodel information (Gemini 2.5 Pro\u002FFlash\u002FFlash-Lite with 1M input tokens, NOT 2M).\n\nUse when: integrating Gemini API, implementing multimodal AI applications, using thinking mode for\ncomplex reasoning, function calling with parallel execution, streaming responses, deploying to\nCloudflare Workers, building chat applications, or encountering SDK deprecation warnings, context window\nerrors, model not found errors, function calling failures, or multimodal format errors.\n\nKeywords: gemini api, @google\u002Fgenai, gemini-2.5-pro, gemini-2.5-flash, gemini-2.5-flash-lite,\nmultimodal gemini, thinking mode, google ai, genai sdk, function calling gemini, streaming gemini,\ngemini vision, gemini video, gemini audio, gemini pdf, system instructions, multi-turn chat,\nDEPRECATED @google\u002Fgenerative-ai, gemini context window, gemini models 2025, gemini 1m tokens,\ngemini tool use, parallel function calling, compositional function calling\n","main","6b73b29e4866f997b1eb47fe8d9631396265fc24",0,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn","2026-09-09 16:06:07",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add davidanthonyn\u002Fagent-skills --skill google-gemini-api",{"tool":36,"command":37},"bunx","bunx skills add davidanthonyn\u002Fagent-skills --skill google-gemini-api",{"tool":39,"command":40},"pnpm","pnpm dlx skills add davidanthonyn\u002Fagent-skills --skill google-gemini-api","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fgoogle-gemini-api\u002FSKILL.md",true,[44,50,54],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"README.md","REFERENCE","参考文档",13129,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fgoogle-gemini-api\u002FREADME.md",{"path":51,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":52,"sourceHtmlUrl":53},"SKILL.json",59266,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fgoogle-gemini-api\u002FSKILL.json",{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"SKILL.md.backup","OTHER","其他",53798,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fgoogle-gemini-api\u002FSKILL.md.backup",[61,68,76,83,90,99],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7AQNJDXVNVMN08N5BHBGZBF","zustand-state-management","Production-tested setup for Zustand state management in React applications with TypeScript.\nThis skill provides comprehensive patterns for building scalable, type-safe global state.\n\nUse when: setting up global state in React, migrating from Redux or Context API, implementing\nstate persistence with localStorage, configuring TypeScript with Zustand, using slices pattern\nfor modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration,\nor encountering hydration errors, TypeScript inference issues, or persist middleware problems.\n\nPrevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses\nsyntax errors, persist middleware export errors, infinite render loops, and slices pattern\ntype inference failures.\n\nKeywords: zustand, state management, React state, TypeScript state, persist middleware,\ndevtools, slices pattern, global state, React hooks, create store, useBoundStore,\nStateCreator, hydration error, text content mismatch, infinite render, localStorage,\nsessionStorage, immer middleware, shallow equality, selector pattern, zustand v5","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzustand-state-management\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":72,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M7AQN2DW9DTPM8BYNZSHQANC","zetic-mlange","Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin\u002FJava) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android\u002FiOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch\u002FONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M7AQMEK370FBPC75N2W8WA4W","youtube-downloader","Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3\u002FM4A\u002FFLAC, downloading entire playlists\u002Fchannels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M7AQHKQ4VQB04NH6BG4SV9Q7","wordpress-plugin-core","This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks\u002Ffilters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types\u002Ftaxonomies, building admin interfaces, or working with the WordPress database.\n\nUse when: Creating new WordPress plugins, implementing nonces\u002Fsanitization\u002Fescaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation\u002Fdeactivation issues, preventing SQL injection\u002FXSS\u002FCSRF vulnerabilities.\n\nKeywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwordpress-plugin-core\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":18},"01M7AQH4JW8F2MJFS1C43TZ2TY","webapp-testing","Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":18},"01M7AQH0PWD6Z1NN66V15DT25M","web-performance-audit","Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fweb-performance-audit\u002FSKILL.md",[],[]]