mcpField
G
google-gemini-api

google-gemini-api

github.com/ovachiever开发5664 次安装49 周前更新
代码仓库

关于 google-gemini-api

google-gemini-api 是使用当前 @google/genai SDK 或直接 REST 请求调用 Google Gemini 模型的指南。内容涵盖文本生成、多模态输入、函数调用、流式输出、缓存、代码执行和 Google Search grounding。

主要功能

  1. 01Node.js SDK 与 REST 调用方式
  2. 02文本生成与流式输出
  3. 03图像、视频、音频和 PDF 输入
  4. 04函数调用与并行调用
  5. 05上下文缓存与代码执行
  6. 06基于 Google Search 的信息检索

适用场景

  1. 01构建由 Gemini 驱动的应用
  2. 02分析混合媒体输入
  3. 03将模型响应连接到函数
  4. 04利用网络信息为回答提供依据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ovachiever/droid-tings --skill google-gemini-api

安装后在 Claude Code 中输入/google-gemini-api确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
.claude-plugin/
plugin.json
references/
code-execution-patterns.md
context-caching-guide.md
function-calling-patterns.md
generation-config.md
grounding-guide.md
models-guide.md
multimodal-guide.md
sdk-migration-guide.md
streaming-patterns.md
thinking-mode-guide.md
top-errors.md
scripts/
check-versions.sh
templates/
cloudflare-worker.ts
code-execution.ts
combined-advanced.ts
context-caching.ts
function-calling-basic.ts
function-calling-parallel.ts
grounding-search.ts
multimodal-image.ts
multimodal-video-audio.ts
package.json
streaming-chat.ts
streaming-fetch.ts
text-generation-basic.ts
text-generation-fetch.ts
thinking-mode.ts

详细介绍

Google Gemini API - 完整指南

版本:第 2 阶段已完成 + Gemini 3 ✅ 软件包:@google/[email protected](⚠️ 不是 @google/generative-ai) 最近更新:2025-11-19(Gemini 3 预览版发布)


⚠️ SDK 迁移重要警告

已弃用的 SDK:@google/generative-ai(将于 2025 年 11 月 30 日停止服务) 当前 SDK:@google/genai v1.27+

如果你看到使用 @google/generative-ai 的代码,那就是过时代码!

本技能使用当前正确的 SDK,并提供完整的迁移指南。


状态

✅ 第 1 阶段已完成:

  • ✅ 文本生成(基础功能 + 流式传输)
  • ✅ 多模态输入(图像、视频、音频、PDF)
  • ✅ 函数调用(基础功能 + 并行执行)
  • ✅ 系统指令和多轮对话
  • ✅ 思考模式配置
  • ✅ 生成参数(temperature、top-p、top-k、停止序列)
  • ✅ 同时支持 Node.js SDK(@google/genai)和 fetch 方式

✅ 第 2 阶段已完成:

  • ✅ 上下文缓存(通过基于 TTL 的缓存优化成本)
  • ✅ 代码执行(内置 Python 解释器和沙盒)
  • ✅ Google 搜索 grounding(实时网页信息 + 引用)

📦 独立技能:

  • 嵌入:text-embedding-004 请参阅 google-gemini-embeddings 技能

目录

第 1 阶段 - 核心功能:

  1. 快速开始
  2. 当前模型(2025)
  3. SDK 与 fetch 方式对比
  4. 文本生成
  5. 流式传输
  6. 多模态输入
  7. 函数调用
  8. 系统指令
  9. 多轮对话
  10. 思考模式
  11. 生成配置

第 2 阶段 - 高级功能: 12. 上下文缓存 13. 代码执行 14. Google 搜索 grounding

常用参考: 15. 错误处理 16. 速率限制 17. SDK 迁移指南 18. 生产环境最佳实践


快速开始

安装

正确的 SDK:

npm install @google/[email protected]

❌ 错误(已弃用):

npm install @google/generative-ai  # DO NOT USE!
环境设置
export GEMINI_API_KEY="..."

或者创建 .env 文件:

GEMINI_API_KEY=...
首次生成文本(Node.js SDK)
import { GoogleGenAI } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Explain quantum computing in simple terms'
});

console.log(response.text);
首次生成文本(fetch - Cloudflare Workers)
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [{ parts: [{ text: 'Explain quantum computing in simple terms' }] }]
    }),
  }
);

const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);

当前模型(2025)

Gemini 3 系列(预览版 - 2025 年 11 月)
gemini-3-pro-preview
  • 上下文:待定(文档待发布)
  • 状态:🆕 预览版发布(2025 年 11 月 18 日)
  • 说明:Google 最新、最智能的 AI 模型,具备业界领先的推理能力
  • 最适合:最复杂的推理任务、高级多模态理解、对基准测试表现要求严格的应用
  • 功能:增强的多模态能力(文本、图像、视频、音频、PDF)、函数调用、流式传输
  • 基准测试表现:在所有主要 AI 基准测试中均优于 Gemini 2.5 Pro
  • ⚠️ 预览版:用于评估。稳定版发布前,生产环境可考虑使用 gemini-2.5-pro
Gemini 2.5 系列(正式发布 - 稳定版)
gemini-2.5-pro
  • 上下文:1,048,576 个输入 token / 65,536 个输出 token
  • 说明:用于复杂推理的业界领先思考模型
  • 最适合:代码、数学、STEM、复杂问题求解
  • 功能:思考模式(默认开启)、函数调用、多模态、流式传输
  • 知识截止时间:2025 年 1 月
gemini-2.5-flash
  • 上下文:1,048,576 个输入 token / 65,536 个输出 token
  • 说明:性价比出色的主力模型
  • 最适合:大规模处理、低延迟、高吞吐量、Agent 场景
  • 功能:思考模式(默认开启)、函数调用、多模态、流式传输
  • 知识截止时间:2025 年 1 月
gemini-2.5-flash-lite
  • 上下文:1,048,576 个输入令牌 / 65,536 个输出令牌
  • 描述:成本优化、速度最快的 2.5 模型
  • 最适合:高吞吐量、对成本敏感的应用
  • 功能:思考模式(默认开启)、函数调用、多模态、流式传输
  • 知识截止日期:2025 年 1 月
模型功能矩阵
功能3-Pro(预览版)2.5-Pro2.5-Flash2.5-Flash-Lite
思考模式TBD✅ 默认开启✅ 默认开启✅ 默认开启
函数调用✅✅✅✅
多模态✅ 增强✅✅✅
流式传输✅✅✅✅
系统指令✅✅✅✅
上下文窗口TBD1,048,576 个输入令牌1,048,576 个输入令牌1,048,576 个输入令牌
输出令牌TBD最多 65,536 个最多 65,536 个最多 65,536 个
状态预览版稳定版稳定版稳定版
⚠️ 上下文窗口更正

准确数据(Gemini 2.5):Gemini 2.5 模型支持 1,048,576 个输入令牌(不是 2M!) 已过时:只有上一代 Gemini 1.5 Pro 的上下文窗口为 2M 个令牌 GEMINI 3:上下文窗口规格有待官方文档公布

常见错误:声称 Gemini 2.5 有 2M 个令牌。事实并非如此。此技能可避免此类错误。


SDK 与 Fetch 方式

Node.js SDK(@google/genai)

优点:

  • 使用 TypeScript 时具备类型安全
  • API 更简单(语法更简洁)
  • 内置聊天辅助工具
  • 自动解析流式传输的 SSE
  • 错误处理更完善

缺点:

  • 需要 Node.js 或兼容的运行时
  • 打包体积更大
  • 可能无法在所有边缘运行时中使用

**适用场景:**构建 Node.js 应用、Next.js Server Actions/Components,或任何兼容 Node.js 的环境

基于 Fetch(直接 REST API)

优点:

  • 可在任何 JavaScript 环境中运行(Cloudflare Workers、Deno、Bun、浏览器)
  • 依赖项极少
  • 打包体积更小
  • 可完全控制请求

缺点:

  • 语法更冗长
  • 流式传输需要手动解析 SSE
  • 没有内置聊天辅助工具
  • 需要手动处理错误

**适用场景:**部署到 Cloudflare Workers、浏览器客户端或轻量级边缘运行时


文本生成

基本文本生成(SDK)
import { GoogleGenAI } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Write a haiku about artificial intelligence'
});

console.log(response.text);
基本文本生成(Fetch)
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [
        {
          parts: [
            { text: 'Write a haiku about artificial intelligence' }
          ]
        }
      ]
    }),
  }
);

const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
响应结构
{
  text: string,                  // Convenience accessor for text content
  candidates: [
    {
      content: {
        parts: [
          { text: string }       // Generated text
        ],
        role: string             // "model"
      },
      finishReason: string,      // "STOP" | "MAX_TOKENS" | "SAFETY" | "OTHER"
      index: number
    }
  ],
  usageMetadata: {
    promptTokenCount: number,
    candidatesTokenCount: number,
    totalTokenCount: number
  }
}

流式传输

使用 SDK 进行流式传输(异步迭代)
const response = await ai.models.generateContentStream({
  model: 'gemini-2.5-flash',
  contents: 'Write a 200-word story about time travel'
});

for await (const chunk of response) {
  process.stdout.write(chunk.text);
}
使用 Fetch 进行流式传输(SSE 解析)
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [{ parts: [{ text: 'Write a 200-word story about time travel' }] }]
    }),
  }
);

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split('\n');
  buffer = lines.pop() || '';

  for (const line of lines) {
    if (line.trim() === '' || line.startsWith('data: [DONE]')) continue;
    if (!line.startsWith('data: ')) continue;

    try {
      const data = JSON.parse(line.slice(6));
      const text = data.candidates[0]?.content?.parts[0]?.text;
      if (text) {
        process.stdout.write(text);
      }
    } catch (e) {
      // Skip invalid JSON
    }
  }
}

要点:

  • 使用 streamGenerateContent 端点(而不是 generateContent)
  • 解析 Server-Sent Events(SSE)格式:data: {json}\n\n
  • 在缓冲区中处理不完整的数据块
  • 跳过空行和 [DONE] 标记

多模态输入

Gemini 2.5 模型支持在同一个请求中使用文本、图像、视频、音频和 PDF。

图像(视觉)
SDK 方式
import { GoogleGenAI } from '@google/genai';
import fs from 'fs';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// From file
const imageData = fs.readFileSync('/path/to/image.jpg');
const base64Image = imageData.toString('base64');

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    {
      parts: [
        { text: 'What is in this image?' },
        {
          inlineData: {
            data: base64Image,
            mimeType: 'image/jpeg'
          }
        }
      ]
    }
  ]
});

console.log(response.text);
Fetch 方式
const imageData = fs.readFileSync('/path/to/image.jpg');
const base64Image = imageData.toString('base64');

const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [
        {
          parts: [
            { text: 'What is in this image?' },
            {
              inlineData: {
                data: base64Image,
                mimeType: 'image/jpeg'
              }
            }
          ]
        }
      ]
    }),
  }
);

const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);

支持的图像格式:

  • JPEG(.jpg、.jpeg)
  • PNG(.png)
  • WebP(.webp)
  • HEIC(.heic)
  • HEIF(.heif)

图像大小上限:每张图像 20MB

视频
// Video must be < 2 minutes for inline data
const videoData = fs.readFileSync('/path/to/video.mp4');
const base64Video = videoData.toString('base64');

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    {
      parts: [
        { text: 'Describe what happens in this video' },
        {
          inlineData: {
            data: base64Video,
            mimeType: 'video/mp4'
          }
        }
      ]
    }
  ]
});

console.log(response.text);

支持的视频格式:

  • MP4(.mp4)
  • MPEG(.mpeg)
  • MOV(.mov)
  • AVI(.avi)
  • FLV(.flv)
  • MPG(.mpg)
  • WebM(.webm)
  • WMV(.wmv)

视频时长上限(内联):2 分钟 视频大小上限:2GB(较大的文件请使用 File API - Phase 2)

音频
const audioData = fs.readFileSync('/path/to/audio.mp3');
const base64Audio = audioData.toString('base64');

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    {
      parts: [
        { text: 'Transcribe and summarize this audio' },
        {
          inlineData: {
            data: base64Audio,
            mimeType: 'audio/mp3'
          }
        }
      ]
    }
  ]
});

console.log(response.text);

支持的音频格式:

  • MP3(.mp3)
  • WAV(.wav)
  • FLAC(.flac)
  • AAC(.aac)
  • OGG(.ogg)
  • OPUS(.opus)

音频大小上限:20MB

PDF
const pdfData = fs.readFileSync('/path/to/document.pdf');
const base64Pdf = pdfData.toString('base64');

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    {
      parts: [
        { text: 'Summarize the key points in this PDF' },
        {
          inlineData: {
            data: base64Pdf,
            mimeType: 'application/pdf'
          }
        }
      ]
    }
  ]
});

console.log(response.text);

PDF 大小上限:30MB PDF 限制:基于文本的 PDF 效果最佳;扫描图像的准确度可能较低

多种输入

你可以在一个请求中组合多种模态:

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    {
      parts: [
        { text: 'Compare these two images and describe the differences:' },
        { inlineData: { data: base64Image1, mimeType: 'image/jpeg' } },
        { inlineData: { data: base64Image2, mimeType: 'image/jpeg' } }
      ]
    }
  ]
});

函数调用

Gemini 支持函数调用(工具使用),可将模型与外部 API 和系统连接起来。

基本函数调用(SDK)
import { GoogleGenAI, FunctionCallingConfigMode } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Define function declarations
const getCurrentWeather = {
  name: 'get_current_weather',
  description: 'Get the current weather for a location',
  parametersJsonSchema: {
    type: 'object',
    properties: {
      location: {
        type: 'string',
        description: 'City name, e.g. San Francisco'
      },
      unit: {
        type: 'string',
        enum: ['celsius', 'fahrenheit']
      }
    },
    required: ['location']
  }
};

// Make request with tools
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'What\'s the weather in Tokyo?',
  config: {
    tools: [
      { functionDeclarations: [getCurrentWeather] }
    ]
  }
});

// Check if model wants to call a function
const functionCall = response.candidates[0].content.parts[0].functionCall;

if (functionCall) {
  console.log('Function to call:', functionCall.name);
  console.log('Arguments:', functionCall.args);

  // Execute the function (your implementation)
  const weatherData = await fetchWeather(functionCall.args.location);

  // Send function result back to model
  const finalResponse = await ai.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: [
      'What\'s the weather in Tokyo?',
      response.candidates[0].content, // Original assistant response with function call
      {
        parts: [
          {
            functionResponse: {
              name: functionCall.name,
              response: weatherData
            }
          }
        ]
      }
    ],
    config: {
      tools: [
        { functionDeclarations: [getCurrentWeather] }
      ]
    }
  });

  console.log(finalResponse.text);
}
函数调用(Fetch)
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [
        { parts: [{ text: 'What\'s the weather in Tokyo?' }] }
      ],
      tools: [
        {
          functionDeclarations: [
            {
              name: 'get_current_weather',
              description: 'Get the current weather for a location',
              parameters: {
                type: 'object',
                properties: {
                  location: {
                    type: 'string',
                    description: 'City name'
                  }
                },
                required: ['location']
              }
            }
          ]
        }
      ]
    }),
  }
);

const data = await response.json();
const functionCall = data.candidates[0]?.content?.parts[0]?.functionCall;

if (functionCall) {
  // Execute function and send result back (same flow as SDK)
}
并行函数调用

Gemini 可以同时调用多个互不依赖的函数:

const tools = [
  {
    functionDeclarations: [
      {
        name: 'get_weather',
        description: 'Get weather for a location',
        parametersJsonSchema: {
          type: 'object',
          properties: {
            location: { type: 'string' }
          },
          required: ['location']
        }
      },
      {
        name: 'get_population',
        description: 'Get population of a city',
        parametersJsonSchema: {
          type: 'object',
          properties: {
            city: { type: 'string' }
          },
          required: ['city']
        }
      }
    ]
  }
];

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'What is the weather and population of Tokyo?',
  config: { tools }
});

// Model may return MULTIPLE function calls in parallel
const functionCalls = response.candidates[0].content.parts.filter(
  part => part.functionCall
);

console.log(`Model wants to call ${functionCalls.length} functions in parallel`);
函数调用模式
import { FunctionCallingConfigMode } from '@google/genai';

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'What\'s the weather?',
  config: {
    tools: [{ functionDeclarations: [getCurrentWeather] }],
    toolConfig: {
      functionCallingConfig: {
        mode: FunctionCallingConfigMode.ANY, // Force function call
        // mode: FunctionCallingConfigMode.AUTO, // Model decides (default)
        // mode: FunctionCallingConfigMode.NONE, // Never call functions
        allowedFunctionNames: ['get_current_weather'] // Optional: restrict to specific functions
      }
    }
  }
});

模式:

  • AUTO(默认):由模型决定是否调用函数
  • ANY:强制模型至少调用一个函数
  • NONE:对此请求禁用函数调用

系统指令

系统指令用于指导模型行为并设置上下文。它们与对话消息相互独立。

SDK 方式
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  systemInstruction: 'You are a helpful AI assistant that always responds in the style of a pirate. Use nautical terminology and end sentences with "arrr".',
  contents: 'Explain what a database is'
});

console.log(response.text);
// Output: "Ahoy there! A database be like a treasure chest..."
Fetch 方式
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      systemInstruction: {
        parts: [
          { text: 'You are a helpful AI assistant that always responds in the style of a pirate.' }
        ]
      },
      contents: [
        { parts: [{ text: 'Explain what a database is' }] }
      ]
    }),
  }
);

要点:

  • 系统指令不属于 contents 数组
  • 它们在请求的顶层设置一次
  • 它们会在整个对话期间持续生效(使用多轮聊天时)
  • 它们不计作用户消息或模型消息

多轮聊天

对于包含历史记录的对话,请使用 SDK 的聊天辅助工具,或手动管理对话状态。

SDK 聊天辅助工具(推荐)
const chat = await ai.models.createChat({
  model: 'gemini-2.5-flash',
  systemInstruction: 'You are a helpful coding assistant.',
  history: [] // Start empty or with previous messages
});

// Send first message
const response1 = await chat.sendMessage('What is TypeScript?');
console.log('Assistant:', response1.text);

// Send follow-up (context is automatically maintained)
const response2 = await chat.sendMessage('How do I install it?');
console.log('Assistant:', response2.text);

// Get full chat history
const history = chat.getHistory();
console.log('Full conversation:', history);
手动管理聊天(Fetch)
const conversationHistory = [];

// First turn
const response1 = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [
        {
          role: 'user',
          parts: [{ text: 'What is TypeScript?' }]
        }
      ]
    }),
  }
);

const data1 = await response1.json();
const assistantReply1 = data1.candidates[0].content.parts[0].text;

// Add to history
conversationHistory.push(
  { role: 'user', parts: [{ text: 'What is TypeScript?' }] },
  { role: 'model', parts: [{ text: assistantReply1 }] }
);

// Second turn (include full history)
const response2 = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [
        ...conversationHistory,
        { role: 'user', parts: [{ text: 'How do I install it?' }] }
      ]
    }),
  }
);

消息角色:

  • user:用户消息
  • model:助手回复

⚠️ 重要:聊天辅助工具仅限 SDK 使用。使用 fetch 时,必须手动管理对话历史记录。


思考模式

Gemini 2.5 模型默认启用思考模式,以提升质量。你可以配置思考预算。

配置思考预算(SDK)
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Solve this complex math problem: ...',
  config: {
    thinkingConfig: {
      thinkingBudget: 8192 // Max tokens for thinking (default: model-dependent)
    }
  }
});
配置思考预算(Fetch)
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [{ parts: [{ text: 'Solve this complex math problem: ...' }] }],
      generationConfig: {
        thinkingConfig: {
          thinkingBudget: 8192
        }
      }
    }),
  }
);

要点:

  • Gemini 2.5 模型始终启用思考模式(无法禁用)
  • 更高的思考预算允许进行更多内部推理(可能增加延迟)
  • 默认预算因模型而异(通常足以应对大多数任务)
  • 仅在非常复杂的推理任务中提高预算

生成配置

使用生成参数自定义模型行为。

所有配置选项(SDK)
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Write a creative story',
  config: {
    temperature: 0.9,           // Randomness (0.0-2.0, default: 1.0)
    topP: 0.95,                 // Nucleus sampling (0.0-1.0)
    topK: 40,                   // Top-k sampling
    maxOutputTokens: 2048,      // Max tokens to generate
    stopSequences: ['END'],     // Stop generation if these appear
    responseMimeType: 'text/plain', // Or 'application/json' for JSON mode
    candidateCount: 1           // Number of response candidates (usually 1)
  }
});
所有配置选项(Fetch)
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [{ parts: [{ text: 'Write a creative story' }] }],
      generationConfig: {
        temperature: 0.9,
        topP: 0.95,
        topK: 40,
        maxOutputTokens: 2048,
        stopSequences: ['END'],
        responseMimeType: 'text/plain',
        candidateCount: 1
      }
    }),
  }
);
参数指南
参数范围默认值使用场景
temperature0.0-2.01.0值越低越聚焦,值越高越有创意
topP0.0-1.00.95核采样阈值
topK1-100+40限制为前 K 个 token
maxOutputTokens1-65536模型最大值控制回复长度
stopSequences数组无在特定字符串处停止生成

提示:

  • 对于事实类任务:使用较低的温度(0.0-0.3)
  • 对于创意类任务:使用较高的温度(0.7-1.5)
  • topP 和 topK 都会控制随机性;使用其中一个即可(不要同时使用)
  • 始终设置 maxOutputTokens,以防止生成内容过多

上下文缓存

上下文缓存可以缓存常用内容(如系统指令、大型文档或视频文件),将成本降低最高达 90%,并改善延迟。

工作原理
  1. 使用重复内容创建缓存
  2. 在后续请求中引用缓存
  3. 节省 token——缓存 token 的费用低得多
  4. TTL 管理——缓存会在指定时间后过期
优势
  • 节省成本:缓存 token 的费用最高可降低 90%
  • 降低延迟:通过重用已处理的内容加快响应速度
  • 上下文一致:在多个请求中使用相同的大型上下文
创建缓存(SDK)
import { GoogleGenAI } from '@google/genai';
import fs from 'fs';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Create a cache for a large document
const documentText = fs.readFileSync('./large-document.txt', 'utf-8');

const cache = await ai.caches.create({
  model: 'gemini-2.5-flash',
  config: {
    displayName: 'large-doc-cache', // Identifier for the cache
    systemInstruction: 'You are an expert at analyzing legal documents.',
    contents: documentText,
    ttl: '3600s', // Cache for 1 hour
  }
});

console.log('Cache created:', cache.name);
console.log('Expires at:', cache.expireTime);
创建缓存(Fetch)
const response = await fetch(
  'https://generativelanguage.googleapis.com/v1beta/cachedContents',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      model: 'models/gemini-2.5-flash',
      displayName: 'large-doc-cache',
      systemInstruction: {
        parts: [{ text: 'You are an expert at analyzing legal documents.' }]
      },
      contents: [
        { parts: [{ text: documentText }] }
      ],
      ttl: '3600s'
    }),
  }
);

const cache = await response.json();
console.log('Cache created:', cache.name);
使用缓存(SDK)
// Generate content using the cache
const response = await ai.models.generateContent({
  model: cache.name, // Use cache name as model
  contents: 'Summarize the key points in the document'
});

console.log(response.text);
使用缓存(Fetch)
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/${cache.name}:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [
        { parts: [{ text: 'Summarize the key points in the document' }] }
      ]
    }),
  }
);

const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
更新缓存 TTL(SDK)
import { UpdateCachedContentConfig } from '@google/genai';

await ai.caches.update({
  name: cache.name,
  config: {
    ttl: '7200s' // Extend to 2 hours
  }
});
使用到期时间更新缓存(SDK)
// Set specific expiration time (must be timezone-aware)
const in10Minutes = new Date(Date.now() + 10 * 60 * 1000);

await ai.caches.update({
  name: cache.name,
  config: {
    expireTime: in10Minutes
  }
});
列出和删除缓存(SDK)
// List all caches
const caches = await ai.caches.list();
for (const cache of caches) {
  console.log(cache.name, cache.displayName);
}

// Delete a specific cache
await ai.caches.delete({ name: cache.name });
使用视频文件进行缓存
import { GoogleGenAI } from '@google/genai';
import fs from 'fs';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Upload video file
const videoFile = await ai.files.upload({
  file: fs.createReadStream('./video.mp4')
});

// Wait for processing
while (videoFile.state.name === 'PROCESSING') {
  await new Promise(resolve => setTimeout(resolve, 2000));
  videoFile = await ai.files.get({ name: videoFile.name });
}

// Create cache with video
const cache = await ai.caches.create({
  model: 'gemini-2.5-flash',
  config: {
    displayName: 'video-analysis-cache',
    systemInstruction: 'You are an expert video analyzer.',
    contents: [videoFile],
    ttl: '300s' // 5 minutes
  }
});

// Use cache for multiple queries
const response1 = await ai.models.generateContent({
  model: cache.name,
  contents: 'What happens in the first minute?'
});

const response2 = await ai.models.generateContent({
  model: cache.name,
  contents: 'Describe the main characters'
});
要点

适用缓存的场景:

  • 需要重复使用的大型系统指令
  • 需要多次分析的长文档
  • 使用不同提示词查询的视频/音频文件
  • 在多个对话会话中保持一致的上下文

TTL 指南:

  • 短会话:300s(5 min)至 3600s(1 hour)
  • 长会话:3600s(1 hour)至 86400s(24 hours)
  • 最长:7 days

节省费用:

  • 缓存的输入令牌:比普通令牌便宜约 90%
  • 输出令牌:价格相同(不缓存)

重要提示:

  • 必须使用明确的模型版本后缀(例如,gemini-2.5-flash-001,而不是仅使用 gemini-2.5-flash)
  • 缓存会在 TTL 到期后自动删除
  • 在到期前更新 TTL,以延长缓存生命周期

代码执行

Gemini 模型可以生成并执行 Python 代码,以解决需要计算、数据分析或可视化的问题。

工作原理
  1. 模型生成可执行的 Python 代码
  2. 代码在安全沙箱中运行
  3. 将结果返回给模型
  4. 模型将结果整合到回复中
支持的操作
  • 数学计算
  • 数据分析和统计
  • 文件处理(CSV、JSON 等)
  • 图表和绘图生成
  • 算法实现
  • 数据转换
可用的 Python 包

标准库:

  • math、statistics、random、datetime、json、csv、re
  • collections、itertools、functools

数据科学:

  • numpy、pandas、scipy

可视化:

  • matplotlib、seaborn

注意:与完整的 Python 环境相比,可用的软件包有限

基本代码执行(SDK)
import { GoogleGenAI, Tool, ToolCodeExecution } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation.',
  config: {
    tools: [{ codeExecution: {} }]
  }
});

// Parse response parts
for (const part of response.candidates[0].content.parts) {
  if (part.text) {
    console.log('Text:', part.text);
  }
  if (part.executableCode) {
    console.log('Generated Code:', part.executableCode.code);
  }
  if (part.codeExecutionResult) {
    console.log('Execution Output:', part.codeExecutionResult.output);
  }
}
基本代码执行(Fetch)
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      tools: [{ code_execution: {} }],
      contents: [
        {
          parts: [
            { text: 'What is the sum of the first 50 prime numbers? Generate and run code.' }
          ]
        }
      ]
    }),
  }
);

const data = await response.json();

for (const part of data.candidates[0].content.parts) {
  if (part.text) {
    console.log('Text:', part.text);
  }
  if (part.executableCode) {
    console.log('Code:', part.executableCode.code);
  }
  if (part.codeExecutionResult) {
    console.log('Result:', part.codeExecutionResult.output);
  }
}
使用代码执行进行对话(SDK)
const chat = await ai.chats.create({
  model: 'gemini-2.5-flash',
  config: {
    tools: [{ codeExecution: {} }]
  }
});

let response = await chat.sendMessage('I have a math question for you.');
console.log(response.text);

response = await chat.sendMessage(
  'Calculate the Fibonacci sequence up to the 20th number and sum them.'
);

// Model will generate and execute code, then provide answer
for (const part of response.candidates[0].content.parts) {
  if (part.text) console.log(part.text);
  if (part.executableCode) console.log('Code:', part.executableCode.code);
  if (part.codeExecutionResult) console.log('Output:', part.codeExecutionResult.output);
}
数据分析示例
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: `
    Analyze this sales data and calculate:
    1. Total revenue
    2. Average sale price
    3. Best-selling month

    Data (CSV format):
    month,sales,revenue
    Jan,150,45000
    Feb,200,62000
    Mar,175,53000
    Apr,220,68000
  `,
  config: {
    tools: [{ codeExecution: {} }]
  }
});

// Model will generate pandas/numpy code to analyze data
for (const part of response.candidates[0].content.parts) {
  if (part.text) console.log(part.text);
  if (part.executableCode) console.log('Analysis Code:', part.executableCode.code);
  if (part.codeExecutionResult) console.log('Results:', part.codeExecutionResult.output);
}
可视化示例
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Create a bar chart showing the distribution of prime numbers under 100 by their last digit. Generate the chart and describe the pattern.',
  config: {
    tools: [{ codeExecution: {} }]
  }
});

// Model generates matplotlib code, executes it, and describes results
for (const part of response.candidates[0].content.parts) {
  if (part.text) console.log(part.text);
  if (part.executableCode) console.log('Chart Code:', part.executableCode.code);
  if (part.codeExecutionResult) {
    // Note: Chart image data would be in output
    console.log('Execution completed');
  }
}
响应结构
{
  candidates: [
    {
      content: {
        parts: [
          { text: "I'll calculate that for you." },
          {
            executableCode: {
              language: "PYTHON",
              code: "def is_prime(n):\n  if n <= 1:\n    return False\n  ..."
            }
          },
          {
            codeExecutionResult: {
              outcome: "OUTCOME_OK", // or "OUTCOME_FAILED"
              output: "5117\n"
            }
          },
          { text: "The sum of the first 50 prime numbers is 5117." }
        ]
      }
    }
  ]
}
错误处理
for (const part of response.candidates[0].content.parts) {
  if (part.codeExecutionResult) {
    if (part.codeExecutionResult.outcome === 'OUTCOME_FAILED') {
      console.error('Code execution failed:', part.codeExecutionResult.output);
    } else {
      console.log('Success:', part.codeExecutionResult.output);
    }
  }
}
要点

适用代码执行的场景:

  • 复杂的数学计算
  • 数据分析和统计
  • 算法实现
  • 文件解析和处理
  • 图表生成
  • 计算问题

限制:

  • 沙箱环境(文件系统访问受限)
  • 可用的 Python 软件包有限
  • 执行超时限制
  • 代码无法访问网络
  • 执行之间不保留状态

最佳实践:

  • 清楚地说明所需的计算或分析
  • 明确要求生成代码(“Generate and run code...”)
  • 检查 outcome 字段以查看错误
  • 用于确定性计算,而非一般编程

重要提示:

  • 所有 Gemini 2.5 模型(Pro、Flash、Flash-Lite)均可使用
  • 为确保安全,代码在隔离沙箱中运行
  • 支持 Python 标准库和常见数据科学软件包

使用 Google 搜索进行信息溯源

信息溯源可将模型连接到实时网络信息,减少幻觉,并通过引用提供最新且经过事实核查的回复。

工作原理
  1. 模型判断是否需要最新信息
  2. 自动执行 Google 搜索
  3. 处理搜索结果
  4. 将搜索结果整合到回复中
  5. 提供引用和来源 URL
优势
  • 实时信息:获取最新事件和数据
  • 减少幻觉:答案以网络来源为依据
  • 可验证:引用便于核查事实
  • 保持最新:不受模型训练数据截止时间的限制
两种信息溯源 API
1. Google 搜索(googleSearch)——推荐用于 Gemini 2.5
const groundingTool = {
  googleSearch: {}
};

功能:

  • 配置简单
  • 需要时自动搜索
  • 所有 Gemini 2.5 模型均可使用
2. Google Search Retrieval(googleSearchRetrieval)——旧版(Gemini 1.5)
const retrievalTool = {
  googleSearchRetrieval: {
    dynamicRetrievalConfig: {
      mode: 'MODE_DYNAMIC',
      dynamicThreshold: 0.7 // Only search if confidence < 70%
    }
  }
};

功能:

  • 可动态控制阈值
  • 与 Gemini 1.5 模型配合使用
  • 配置选项更多
基本信息溯源(SDK)——Gemini 2.5
import { GoogleGenAI } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Who won the euro 2024?',
  config: {
    tools: [{ googleSearch: {} }]
  }
});

console.log(response.text);

// Check if grounding was used
if (response.candidates[0].groundingMetadata) {
  console.log('Search was performed!');
  console.log('Sources:', response.candidates[0].groundingMetadata);
}
基本信息溯源(Fetch)——Gemini 2.5
const response = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-goog-api-key': env.GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [
        { parts: [{ text: 'Who won the euro 2024?' }] }
      ],
      tools: [
        { google_search: {} }
      ]
    }),
  }
);

const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);

if (data.candidates[0].groundingMetadata) {
  console.log('Grounding metadata:', data.candidates[0].groundingMetadata);
}
动态检索(SDK)——Gemini 1.5
import { GoogleGenAI, DynamicRetrievalConfigMode } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

const response = await ai.models.generateContent({
  model: 'gemini-1.5-flash',
  contents: 'Who won the euro 2024?',
  config: {
    tools: [
      {
        googleSearchRetrieval: {
          dynamicRetrievalConfig: {
            mode: DynamicRetrievalConfigMode.MODE_DYNAMIC,
            dynamicThreshold: 0.7 // Search only if confidence < 70%
          }
        }
      }
    ]
  }
});

console.log(response.text);

if (!response.candidates[0].groundingMetadata) {
  console.log('Model answered from its own knowledge (high confidence)');
}
信息溯源元数据结构
{
  groundingMetadata: {
    searchQueries: [
      { text: "euro 2024 winner" }
    ],
    webPages: [
      {
        url: "https://example.com/euro-2024-results",
        title: "UEFA Euro 2024 Final Results",
        snippet: "Spain won UEFA Euro 2024..."
      }
    ],
    citations: [
      {
        startIndex: 42,
        endIndex: 47,
        uri: "https://example.com/euro-2024-results"
      }
    ],
    retrievalQueries: [
      {
        query: "who won euro 2024 final"
      }
    ]
  }
}
使用 Grounding 聊天(SDK)
const chat = await ai.chats.create({
  model: 'gemini-2.5-flash',
  config: {
    tools: [{ googleSearch: {} }]
  }
});

let response = await chat.sendMessage('What are the latest developments in quantum computing?');
console.log(response.text);

// Check grounding sources
if (response.candidates[0].groundingMetadata) {
  const sources = response.candidates[0].groundingMetadata.webPages || [];
  console.log(`Sources used: ${sources.length}`);
  sources.forEach(source => {
    console.log(`- ${source.title}: ${source.url}`);
  });
}

// Follow-up still has grounding enabled
response = await chat.sendMessage('Which company made the biggest breakthrough?');
console.log(response.text);
将 Grounding 与函数调用结合使用
const weatherFunction = {
  name: 'get_current_weather',
  description: 'Get current weather for a location',
  parametersJsonSchema: {
    type: 'object',
    properties: {
      location: { type: 'string', description: 'City name' }
    },
    required: ['location']
  }
};

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'What is the weather like in the city that won Euro 2024?',
  config: {
    tools: [
      { googleSearch: {} },
      { functionDeclarations: [weatherFunction] }
    ]
  }
});

// Model will:
// 1. Use Google Search to find Euro 2024 winner
// 2. Call get_current_weather function with the city
// 3. Combine both results in response
检查是否使用了 Grounding
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'What is 2+2?', // Model knows this without search
  config: {
    tools: [{ googleSearch: {} }]
  }
});

if (!response.candidates[0].groundingMetadata) {
  console.log('Model answered from its own knowledge (no search needed)');
} else {
  console.log('Search was performed');
}
要点

何时使用 Grounding:

  • 时事和新闻
  • 实时数据(股价、体育比分、天气)
  • 事实核查与验证
  • 有关近期进展的问题
  • 超出模型训练截止时间的信息

何时不使用:

  • 一般知识问题
  • 数学计算
  • 代码生成
  • 创意写作
  • 仅需内部推理的任务

成本注意事项:

  • Grounding 会增加延迟(搜索需要时间)
  • 检索内容会产生额外的 Token 成本
  • 使用 dynamicThreshold 控制何时执行搜索(Gemini 1.5)

重要说明:

  • Grounding 需要 Google Cloud 项目(不能只有 API 密钥)
  • 搜索结果质量取决于查询措辞
  • 引用可能无法涵盖回复中的所有事实
  • 系统会根据置信度自动执行搜索

Gemini 2.5 与 1.5:

  • Gemini 2.5:使用 googleSearch(简单,推荐)
  • Gemini 1.5:使用 googleSearchRetrieval 和 dynamicThreshold

最佳实践:

  • 始终检查 groundingMetadata,确认是否使用了搜索
  • 向用户显示引用,确保透明度
  • 使用具体、措辞清晰的问题,以获得更好的搜索结果
  • 与函数调用结合,构建混合工作流

错误处理

常见错误
1. API 密钥无效(401)
{
  error: {
    code: 401,
    message: 'API key not valid. Please pass a valid API key.',
    status: 'UNAUTHENTICATED'
  }
}

解决方案:确认已正确设置 GEMINI_API_KEY 环境变量。

2. 超出速率限制(429)
{
  error: {
    code: 429,
    message: 'Resource has been exhausted (e.g. check quota).',
    status: 'RESOURCE_EXHAUSTED'
  }
}

解决方案:实现指数退避重试策略。

3. 未找到模型(404)
{
  error: {
    code: 404,
    message: 'models/gemini-3.0-flash is not found',
    status: 'NOT_FOUND'
  }
}

解决方案:使用正确的模型名称:gemini-2.5-pro、gemini-2.5-flash、gemini-2.5-flash-lite

4. 超出上下文长度(400)
{
  error: {
    code: 400,
    message: 'Request payload size exceeds the limit',
    status: 'INVALID_ARGUMENT'
  }
}

解决方案:缩减输入内容。Gemini 2.5 模型最多支持 1,048,576 个输入 Token。

指数退避模式
async function generateWithRetry(request, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await ai.models.generateContent(request);
    } catch (error) {
      if (error.status === 429 && i < maxRetries - 1) {
        const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
}

速率限制

免费层级(Gemini API)

速率限制因模型而异:

Gemini 2.5 Pro:

  • 每分钟请求数:5 RPM
  • 每分钟 Token 数:125,000 TPM
  • 每日请求数:100 RPD

Gemini 2.5 Flash:

  • 每分钟请求数:10 RPM
  • 每分钟 Token 数:250,000 TPM
  • 每日请求数:250 RPD

Gemini 2.5 Flash-Lite:

  • 每分钟请求数:15 RPM
  • 每分钟 Token 数:250,000 TPM
  • 每日请求数:1,000 RPD
付费层级(Tier 1)

需要将结算账号关联到 Google Cloud 项目。

Gemini 2.5 Pro:

  • 每分钟请求数:150 RPM
  • 每分钟 Token 数:2,000,000 TPM
  • 每日请求数:10,000 RPD

Gemini 2.5 Flash:

  • 每分钟请求数:1,000 RPM
  • 每分钟 Token 数:1,000,000 TPM
  • 每日请求数:10,000 RPD

Gemini 2.5 Flash-Lite:

  • 每分钟请求数:4,000 RPM
  • 每分钟 Token 数:4,000,000 TPM
  • 每日请求数:未指定
更高级别(Tier 2 和 Tier 3)

Tier 2(需要消费 $250+ 并等待 30 天):

  • 可获得更高的限制

Tier 3(需要消费 $1,000+ 并等待 30 天):

  • 可获得最高限制

提示:


SDK 迁移指南

从 @google/generative-ai 迁移到 @google/genai
1. 更新软件包
# Remove deprecated SDK
npm uninstall @google/generative-ai

# Install current SDK
npm install @google/[email protected]
2. 更新导入语句

旧版(已弃用):

import { GoogleGenerativeAI } from '@google/generative-ai';
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' });

新版(当前):

import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey });
// Use ai.models.generateContent() directly
3. 更新 API 调用

旧版:

const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text();

新版:

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: prompt
});
const text = response.text;
4. 更新流式处理

旧版:

const result = await model.generateContentStream(prompt);
for await (const chunk of result.stream) {
  console.log(chunk.text());
}

新版:

const response = await ai.models.generateContentStream({
  model: 'gemini-2.5-flash',
  contents: prompt
});
for await (const chunk of response) {
  console.log(chunk.text);
}
5. 更新聊天

旧版:

const chat = model.startChat();
const result = await chat.sendMessage(message);
const response = await result.response;

新版:

const chat = await ai.models.createChat({ model: 'gemini-2.5-flash' });
const response = await chat.sendMessage(message);
// response.text is directly available

生产环境最佳实践

1. 务必做到

✅ 使用 @google/genai(不要使用 @google/generative-ai) ✅ 设置 maxOutputTokens,避免生成过多内容 ✅ 实现速率限制处理,并使用指数退避 ✅ 使用环境变量存储 API 密钥(切勿硬编码) ✅ 向 API 发送请求前验证输入(节省成本) ✅ 对较长的响应使用流式传输,提升用户体验 ✅ 根据需求选择合适的模型(复杂推理选 Pro,均衡选 Flash,追求速度选 Flash-Lite) ✅ 使用 try-catch 优雅地处理错误 ✅ 监控 token 用量,控制成本 ✅ 使用正确的模型名称:gemini-2.5-pro/flash/flash-lite

2. 切勿这样做

❌ 切勿使用 @google/generative-ai(已弃用!) ❌ 切勿在代码中硬编码 API 密钥 ❌ 切勿声称 Gemini 2.5 支持 2M 上下文(其输入 token 上限为 1,048,576) ❌ 切勿在客户端代码中暴露 API 密钥 ❌ 切勿跳过错误处理(始终使用 try-catch) ❌ 切勿使用通用的速率限制(每种模型的限制都不同,请查阅官方文档) ❌ 未经用户同意,切勿发送 PII ❌ 未经验证,切勿信任用户输入 ❌ 切勿忽略速率限制(否则会收到 429 错误) ❌ 切勿使用 gemini-1.5-pro 等旧模型名称(请使用 2.5 系列模型)

3. 安全
  • API 密钥存储:使用环境变量或密钥管理器
  • 仅限服务端使用:切勿在浏览器 JavaScript 中暴露 API 密钥
  • 输入验证:在调用 API 前清理所有用户输入
  • 速率限制:实施自有速率限制以防止滥用
  • 错误消息:不要在错误日志中暴露 API 密钥或敏感数据
4. 成本优化
  • 选择合适的模型:大多数任务使用 Flash,仅在需要时使用 Pro
  • 设置 token 限制:使用 maxOutputTokens 控制成本
  • 批量请求:高效处理多个项目
  • 缓存结果:在适当情况下存储响应
  • 监控用量:在 Google Cloud Console 中跟踪 token 消耗
5. 性能
  • 使用流式传输:降低较长响应的感知延迟
  • 并行请求:对相互独立的调用使用 Promise.all()
  • 边缘部署:部署到 Cloudflare Workers 以降低延迟
  • 连接池:尽可能复用 HTTP 连接

快速参考

安装
npm install @google/[email protected]
环境
export GEMINI_API_KEY="..."
模型(2025 年)
  • gemini-2.5-pro(输入 1,048,576 / 输出 65,536)- 最适合复杂推理
  • gemini-2.5-flash(输入 1,048,576 / 输出 65,536)- 性价比最均衡
  • gemini-2.5-flash-lite(输入 1,048,576 / 输出 65,536)- 速度最快、成本效益最高
基本生成
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Your prompt here'
});
console.log(response.text);
流式传输
const response = await ai.models.generateContentStream({...});
for await (const chunk of response) {
  console.log(chunk.text);
}
多模态
contents: [
  {
    parts: [
      { text: 'What is this?' },
      { inlineData: { data: base64Image, mimeType: 'image/jpeg' } }
    ]
  }
]
函数调用
config: {
  tools: [{ functionDeclarations: [...] }]
}

最后更新:2025-10-25 已通过生产环境验证:所有功能均已使用 @google/[email protected] 完成测试 阶段:第 2 阶段已完成 ✅(所有核心功能和高级功能)

评论

支持 Markdown