关于 google-gemini-api
google-gemini-api 是面向开发者的技能,介绍当前的 @google/genai SDK 及对 Gemini 的 REST 请求,涵盖文本生成、多模态输入、函数调用和进阶请求功能。
主要功能
- 01文本生成与流式输出
- 02图像、视频、音频和 PDF 输入
- 03支持并行执行的函数调用
- 04系统指令与多轮对话
- 05上下文缓存、代码执行和 Google 搜索 grounding
适用场景
- 01在 Node.js 应用中生成文本
- 02在 Gemini 请求中处理媒体和文档
- 03将模型响应连接到外部函数
- 04在边缘运行时使用 REST 请求
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill google-gemini-api安装后在 Claude Code 中输入/google-gemini-api确认已加载。
附带文件README.mdSKILL.json
详细介绍
Google Gemini API - 完整指南
版本:Phase 2 已完成 ✅ 软件包:@google/[email protected] (⚠️ 不是 @google/generative-ai) 最后更新:2025-10-25
⚠️ SDK 迁移重要警告
已弃用的 SDK:@google/generative-ai(将于 2025 年 11 月 30 日停止服务)
当前 SDK:@google/genai v1.27+
如果你看到使用 @google/generative-ai 的代码,那就是过时的!
本技能使用当前正确的 SDK,并提供完整的迁移指南。
状态
✅ Phase 1 已完成:
- ✅ 文本生成(基础和流式)
- ✅ 多模态输入(图像、视频、音频、PDF)
- ✅ 函数调用(基础和并行执行)
- ✅ 系统指令和多轮对话
- ✅ 思考模式配置
- ✅ 生成参数(temperature、top-p、top-k、停止序列)
- ✅ 支持 Node.js SDK(@google/genai)和 fetch 两种方式
✅ Phase 2 已完成:
- ✅ 上下文缓存(基于 TTL 的缓存,可优化成本)
- ✅ 代码执行(内置 Python 解释器和沙箱)
- ✅ 使用 Google 搜索进行信息溯源(实时网络信息和引用)
📦 独立技能:
- 嵌入:text-embedding-004 请参阅
google-gemini-embeddings技能
目录
Phase 1 - 核心功能:
Phase 2 - 高级功能: 12. 上下文缓存 13. 代码执行 14. 使用 Google 搜索进行信息溯源
常用参考: 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 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 个输入 token / 65,536 个输出 token
- 描述:成本优化、速度最快的 2.5 模型
- 适用场景:高吞吐量、成本敏感型应用
- 功能:思考模式(默认开启)、函数调用、多模态、流式处理
- 知识截止时间:2025 年 1 月
模型功能对照表
| 功能 | Pro | Flash | Flash-Lite |
|---|---|---|---|
| 思考模式 | ✅ 默认开启 | ✅ 默认开启 | ✅ 默认开启 |
| 函数调用 | ✅ | ✅ | ✅ |
| 多模态 | ✅ | ✅ | ✅ |
| 流式处理 | ✅ | ✅ | ✅ |
| 系统指令 | ✅ | ✅ | ✅ |
| 上下文窗口 | 1,048,576 个输入 token | 1,048,576 个输入 token | 1,048,576 个输入 token |
| 输出 token | 最多 65,536 个 | 最多 65,536 个 | 最多 65,536 个 |
⚠️ 上下文窗口更正
准确:Gemini 2.5 模型支持 1,048,576 个输入令牌(不是 2M!) 已过时:只有上一代 Gemini 1.5 Pro 拥有 2M 令牌上下文窗口
常见错误:声称 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
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
}
}),
}
);
参数指南
| 参数 | 范围 | 默认值 | 使用场景 |
|---|---|---|---|
| temperature | 0.0-2.0 | 1.0 | 值越低,回答越专注;值越高,回答越有创意 |
| topP | 0.0-1.0 | 0.95 | 核采样阈值 |
| topK | 1-100+ | 40 | 限制为前 K 个词元 |
| maxOutputTokens | 1-65536 | 模型最大值 | 控制回复长度 |
| stopSequences | 数组 | 无 | 在指定字符串处停止生成 |
提示:
- 对于事实性任务:使用较低的 temperature(0.0-0.3)
- 对于创意任务:使用较高的 temperature(0.7-1.5)
- topP 和 topK 都可控制随机性;二选一使用(不要同时使用)
- 始终设置 maxOutputTokens,以避免生成内容过多
上下文缓存
上下文缓存可缓存常用内容(例如系统指令、大型文档或视频文件),从而最多降低 90% 的成本并缩短延迟。
工作原理
- 使用重复内容创建缓存
- 在后续请求中引用缓存
- 节省词元——缓存词元的成本大幅降低
- TTL 管理——缓存会在指定时间后过期
优势
- 节省成本:缓存词元的成本最多可降低 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 代码,以解决需要计算、数据分析或可视化的问题。
工作原理
- 模型生成可执行的 Python 代码
- 代码在安全沙箱中运行
- 运行结果返回给模型
- 模型将结果纳入回复
支持的操作
- 数学计算
- 数据分析和统计
- 文件处理(CSV、JSON 等)
- 图表生成
- 算法实现
- 数据转换
可用的 Python 包
标准库:
math、statistics、random、datetime、json、csv、recollections、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 搜索进行信息核实
信息核实功能将模型连接到实时网络信息,减少幻觉,并通过引用提供最新且经过事实核查的回答。
工作原理
- 模型判断是否需要当前信息
- 自动执行 Google 搜索
- 处理搜索结果
- 将搜索结果纳入回答
- 提供引用和来源 URL
优势
- 实时信息:获取当前事件和数据
- 减少幻觉:回答以网络来源为依据
- 可核查:引用可用于事实核查
- 保持最新:不受模型训练截止时间的限制
两种信息核实 API
1. Google 搜索(googleSearch)——推荐用于 Gemini 2.5
const groundingTool = {
googleSearch: {}
};
功能:
- 配置简单
- 需要时自动搜索
- 所有 Gemini 2.5 模型均可使用
2. Google 搜索检索(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"
}
]
}
}
使用信息核实进行聊天(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);
将信息核实与函数调用结合使用
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
检查是否使用了信息核实
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 会增加延迟(搜索需要时间)
- 检索内容会产生额外的令牌成本
- 使用
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 个输入令牌。
指数退避模式
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
- 每分钟令牌数:125,000 TPM
- 每日请求数:100 RPD
Gemini 2.5 Flash:
- 每分钟请求数:10 RPM
- 每分钟令牌数:250,000 TPM
- 每日请求数:250 RPD
Gemini 2.5 Flash-Lite:
- 每分钟请求数:15 RPM
- 每分钟令牌数:250,000 TPM
- 每日请求数:1,000 RPD
付费层级(第 1 层)
需要将结算账号关联到 Google Cloud 项目。
Gemini 2.5 Pro:
- 每分钟请求数:150 RPM
- 每分钟令牌数:2,000,000 TPM
- 每日请求数:10,000 RPD
Gemini 2.5 Flash:
- 每分钟请求数:1,000 RPM
- 每分钟令牌数:1,000,000 TPM
- 每日请求数:10,000 RPD
Gemini 2.5 Flash-Lite:
- 每分钟请求数:4,000 RPM
- 每分钟令牌数:4,000,000 TPM
- 每日请求数:未指定
更高层级(第 2 层和第 3 层)
第 2 层(要求累计支出 $250 以上并等待 30 天):
- 可用更高的限制
第 3 层(要求累计支出 $1,000 以上并等待 30 天):
- 可用最高限制
提示:
- 使用指数退避处理速率限制
- 对高吞吐量任务使用批处理
- 在 Google AI Studio 中监控用量
- 根据速率限制需求选择合适的模型
- 官方速率限制:https://ai.google.dev/gemini-api/docs/rate-limits
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 阶段已完成 ✅(所有核心功能和高级功能)