关于 google-gemini-api
面向开发者的 Google Gemini API 指南,使用 JavaScript SDK @google/genai,涵盖内容生成、流式输出、多模态输入、函数调用、模型选择、迁移与问题排查。
主要功能
- 01文本生成与流式输出
- 02图像、视频、音频和 PDF 输入
- 03函数调用与聊天模式
- 04模型选择与参数配置
- 05迁移指南与错误参考
适用场景
- 01从 @google/generative-ai 迁移
- 02使用 Gemini 模型生成内容
- 03分析多模态输入
- 04实现函数调用工作流
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill google-gemini-api安装后在 Claude Code 中输入/google-gemini-api确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/code-execution-patterns.mdcontext-caching-guide.mderror-catalog.mdfunction-calling-patterns.mdgeneration-config.mdgrounding-guide.mdmodels-guide.mdmultimodal-guide.mdsdk-migration-guide.mdstreaming-patterns.mdthinking-mode-guide.mdtop-errors.mdscripts/check-versions.shtemplates/basic-usage.tscloudflare-worker.tscode-execution.tscombined-advanced.tscontext-caching.tsfunction-calling-basic.tsfunction-calling-parallel.tsgrounding-search.tsmultimodal-image.tsmultimodal-video-audio.tspackage.jsonstreaming-chat.tsstreaming-fetch.tstext-generation-basic.tstext-generation-fetch.tsthinking-mode.ts详细介绍
Google Gemini API - 完整指南
软件包:@google/[email protected] (⚠️ 不是 @google/generative-ai) 最后更新:2025-11-21
⚠️ SDK 迁移重要警告
已弃用的 SDK:@google/generative-ai(将于 2025 年 11 月 30 日停止服务)
当前 SDK:@google/genai v1.27+
如果你看到使用 @google/generative-ai 的代码,那它已经过时了!
加载 references/sdk-migration-guide.md,查看完整迁移步骤。
快速入门
安装
✅ 正确的 SDK:
bun add @google/[email protected]
❌ 错误(已弃用):
bun add @google/generative-ai # DO NOT USE!
环境设置
export GEMINI_API_KEY="your-api-key"
首次文本生成
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);
查看完整模板:templates/basic-usage.ts
当前模型(2025 年)
gemini-2.5-flash ⭐ 推荐
- 最适合:通用 AI、高吞吐量生产环境、Agent 工作流
- 输入 Token 数:1,048,576(1M,不是 2M!)
- 输出 Token 数:65,536
- 速率限制(免费):10 RPM、250k TPM
- 费用:输入 $0.075/1M Token,输出 $0.30/1M Token
- 功能:思考模式、函数调用、多模态、流式传输
gemini-2.5-pro
- 最适合:复杂推理、代码生成、数学/STEM
- 输入 Token 数:1,048,576
- 输出 Token 数:65,536
- 速率限制(免费):5 RPM、125k TPM
- 费用:输入 $1.25/1M Token,输出 $5/1M Token
gemini-2.5-flash-lite
- 最适合:高吞吐量、低延迟、对成本敏感的任务
- 输入 Token 数:1,048,576
- 输出 Token 数:65,536
- 速率限制(免费):15 RPM、250k TPM
- 费用:输入 $0.01/1M Token,输出 $0.04/1M Token
- ⚠️ 限制:不支持函数调用或代码执行
⚠️ 常见错误:声称 Gemini 2.5 支持 2M Token。并非如此,它支持 1,048,576(1M)。
加载 references/models-guide.md,查看详细的模型对比和选择标准。
文本生成
基本生成
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Write a haiku about programming'
});
console.log(response.text);
配置选项
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Explain AI',
generationConfig: {
temperature: 0.7, // 0.0-2.0, default 1.0
topP: 0.95, // 0.0-1.0
topK: 40, // 1-100
maxOutputTokens: 1024,
stopSequences: ['END']
}
});
加载 references/generation-config.md,查看完整的参数参考和调优指南。
流式传输
const stream = await ai.models.generateContentStream({
model: 'gemini-2.5-flash',
contents: 'Write a long story'
});
for await (const chunk of stream) {
process.stdout.write(chunk.text);
}
加载 references/streaming-patterns.md,查看 Fetch/SSE 实现模式(Cloudflare Workers)。
多模态输入
图片
const imageData = Buffer.from(imageBytes).toString('base64');
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
{ text: 'What is in this image?' },
{
inlineData: {
mimeType: 'image/jpeg', // or image/png, image/webp
data: imageData
}
}
]
});
视频、音频、PDF
使用相同的模式,只需指定合适的 mimeType:
- 视频:
video/mp4、video/mpeg、video/mov - 音频:
audio/wav、audio/mp3、audio/flac - PDF:
application/pdf
加载 references/multimodal-guide.md,查看格式规范、大小限制和最佳实践。
函数调用
基本模式
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What is the weather in San Francisco?',
tools: [{
functionDeclarations: [{
name: 'getWeather',
description: 'Get current weather for a location',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' },
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
},
required: ['location']
}
}]
}]
});
// Handle function call
const call = response.functionCalls?.[0];
if (call) {
const result = await getWeather(call.args);
// Send result back to model
const final = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
...response.contents,
{
functionResponse: {
name: call.name,
response: result
}
}
]
});
console.log(final.text);
}
并行函数调用
Gemini 可以同时调用多个函数:
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What is the weather in SF and NY?',
tools: [{ functionDeclarations: [getWeatherDeclaration] }]
});
// Process all function calls in parallel
const results = await Promise.all(
response.functionCalls.map(call =>
getWeather(call.args).then(result => ({
name: call.name,
response: result
}))
)
);
// Send all results back
const final = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
...response.contents,
...results.map(r => ({ functionResponse: r }))
]
});
加载 references/function-calling-patterns.md,查看调用模式(AUTO/ANY/NONE)和组合模式。
多轮聊天
const chat = ai.models.startChat({
model: 'gemini-2.5-flash',
systemInstruction: 'You are a helpful programming assistant',
history: []
});
let response = await chat.sendMessage('Hello!');
console.log(response.text);
response = await chat.sendMessage('Explain async/await');
console.log(response.text);
// Get full history
console.log(chat.getHistory());
系统指令
为模型设置持久指令:
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
systemInstruction: 'You are a pirate. Always respond in pirate speak.',
contents: 'What is the weather today?'
});
思考模式
Gemini 2.5 模型内置思考模式(始终启用)。可为复杂任务配置思考预算:
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Solve this math problem: If x + 2y = 10 and 3x - y = 4, what is x?',
generationConfig: {
thinkingConfig: {
thinkingBudget: 8192 // Max tokens for internal reasoning
}
}
});
适用场景:复杂数学题、逻辑谜题、多步推理、代码调试
加载 references/thinking-mode-guide.md,了解如何优化思考预算。
五大关键错误
错误 1:使用已弃用的 SDK
错误:出现弃用警告或 API 已过时
解决方案:使用 @google/genai,不要使用 @google/generative-ai
npm uninstall @google/generative-ai
bun add @google/[email protected]
错误 2:API 密钥无效(401)
错误:API key not valid
解决方案:检查环境变量
export GEMINI_API_KEY="your-key"
错误 3:找不到模型(404)
错误:models/gemini-3.0-flash is not found
解决方案:使用正确的模型名称(2025 年)
'gemini-2.5-pro'
'gemini-2.5-flash'
'gemini-2.5-flash-lite'
错误 4:超出上下文长度(400)
错误:Request payload size exceeds the limit
解决方案:输入上限为 1,048,576 Token(1M,不是 2M)。输入内容较大时,请使用上下文缓存。
加载 references/context-caching-guide.md,查看缓存实现方法。
错误 5:超出速率限制(429)
错误:Resource has been exhausted
解决方案:实现指数退避
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;
}
}
}
查看全部 22 个错误:加载 references/error-catalog.md,查看完整的错误目录及解决方案。
快速调试:加载 references/top-errors.md,查看调试清单。
何时加载参考资料
当需要了解特定功能的详细指南时,加载参考文件:
核心功能(按需加载)
- SDK 迁移:从
@google/generative-ai迁移时,加载references/sdk-migration-guide.md - 模型选择:在 Pro、Flash 和 Flash-Lite 之间进行选择时,加载
references/models-guide.md - 错误调试:遇到错误时,加载
references/error-catalog.md或references/top-errors.md
高级功能(实现时加载)
- 上下文缓存:为大型或重复输入实现成本优化时,加载
references/context-caching-guide.md - 代码执行:为计算或分析启用 Python 代码执行时,加载
references/code-execution-patterns.md - Grounding(Google 搜索):将模型连接到实时网络信息时,加载
references/grounding-guide.md - 流式传输实现:为 Cloudflare Workers 实现 SSE 解析时,加载
references/streaming-patterns.md - 函数调用模式:使用 AUTO、ANY、NONE 模式或组合模式时,加载
references/function-calling-patterns.md - 多模态格式:处理图像、视频、音频或 PDF(格式规范、大小限制)时,加载
references/multimodal-guide.md - 生成参数调优:微调 temperature、topP、topK 参数时,加载
references/generation-config.md - 思考模式配置:优化复杂推理的思考预算时,加载
references/thinking-mode-guide.md
一般规则:SKILL.md 提供快速入门和常见错误。要深入了解、查看详细模式或排查特定功能的问题,请加载参考资料。
随附资源
模板(templates/):
basic-usage.ts- 涵盖所有功能的完整示例(133 行)
参考资料(references/):
error-catalog.md- 全部 7 个已记录错误及其解决方案(231 行)top-errors.md- 22 个常见错误的快速调试清单(305 行)sdk-migration-guide.md- 从已弃用 SDK 迁移的完整指南(236 行)models-guide.md- 详细的模型比较和选择指南(247 行)context-caching-guide.md- 使用缓存优化成本(374 行)code-execution-patterns.md- Python 代码执行指南(482 行)grounding-guide.md- Google 搜索集成(603 行)streaming-patterns.md- Cloudflare Workers 的 SSE 实现(82 行)function-calling-patterns.md- 高级函数调用模式(60 行)multimodal-guide.md- 格式规范和限制(59 行)generation-config.md- 参数调优参考(58 行)thinking-mode-guide.md- 思考预算优化(60 行)
与其他技能集成
此技能可与以下技能良好配合:
- cloudflare-worker-base → 部署到 Cloudflare Workers
- ai-sdk-core → Vercel AI SDK 集成
- openai-api → 多提供商 AI 设置
- google-gemini-embeddings → 文本嵌入
其他资源
官方文档:
- Gemini API 文档:https://ai.google.dev/gemini-api/docs
- SDK 参考:https://ai.google.dev/gemini-api/docs/sdks
- 速率限制:https://ai.google.dev/gemini-api/docs/rate-limits
生产环境测试:AI 聊天机器人、内容生成、多模态分析 最后更新:2025-10-25 Token 节省:约 65%(减少 API 文档和示例)