
关于
将 Google Gemini API 集成到项目中时使用。涵盖模型选择、多模态输入、流式传输、函数调用和上下文缓存。
name: gemini-api-integration description: "将 Google Gemini API 集成到项目中时使用。涵盖模型选择、多模态输入、流式传输、函数调用和生产最佳实践。" risk: safe source: community date_added: "2026-03-04"
Gemini API 集成
概述
本技能指导 AI 代理将 Google Gemini API 集成到应用程序中——从基本文本生成到高级多模态、函数调用和流式传输用例。涵盖完整的 Gemini SDK 生命周期及生产级模式。
何时使用此技能
- 在 Node.js、Python 或浏览器项目中首次设置 Gemini API 时使用
- 实现多模态输入(文本 + 图像/音频/视频)时使用
- 添加流式响应以改善感知延迟时使用
- 使用 Gemini 实现函数调用/工具使用时使用
- 优化模型选择(Flash vs Pro vs Ultra)以平衡成本和性能时使用
- 调试 Gemini API 错误、速率限制或配额问题时使用
分步指南
1. 安装与设置
Node.js / TypeScript:
npm install @google/generative-ai
Python:
pip install google-generativeai
安全设置 API 密钥:
export GEMINI_API_KEY="your-api-key-here"
2. 基本文本生成
Node.js:
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent("Explain async/await in JavaScript");
console.log(result.response.text());
Python:
import google.generativeai as genai
import os
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
model = genai.GenerativeModel("gemini-1.5-flash")
response = model.generate_content("Explain async/await in JavaScript")
print(response.text)
3. 流式响应
const result = await model.generateContentStream("Write a detailed blog post about AI");
for await (const chunk of result.stream) {
process.stdout.write(chunk.text());
}
4. 多模态输入(文本 + 图像)
import fs from "fs";
const imageData = fs.readFileSync("screenshot.png");
const imagePart = {
inlineData: {
data: imageData.toString("base64"),
mimeType: "image/png",
},
};
const result = await model.generateContent(["Describe this image:", imagePart]);
console.log(result.response.text());
5. 函数调用 / 工具使用
const tools = [{
functionDeclarations: [{
name: "get_weather",
description: "Get current weather for a city",
parameters: {
type: "OBJECT",
properties: {
city: { type: "STRING", description: "City name" },
},
required: ["city"],
},
}],
}];
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro", tools });
const result = await model.generateContent("What's the weather in Mumbai?");
const call = result.response.functionCalls()?.[0];
if (call) {
// 执行实际函数
const weatherData = await getWeather(call.args.city);
// 将结果发送回模型
}
6. 多轮对话
const chat = model.startChat({
history: [
{ role: "user", parts: [{ text: "You are a helpful coding assistant." }] },
{ role: "model", parts: [{ text: "Sure! I'm ready to help with code." }] },
],
});
const response = await chat.sendMessage("How do I reverse a string in Python?");
console.log(response.response.text());
7. 模型选择指南
| 模型 | 最适用场景 | 速度 | 成本 |
|------|-----------|------|------|
| gemini-1.5-flash | 高吞吐量、成本敏感型任务 | 快 | 低 |
| gemini-1.5-pro | 复杂推理、长上下文 | 中等 | 中等 |
| gemini-2.0-flash | 最新快速模型、多模态 | 极快 | 低 |
| gemini-2.0-pro | 最强能力、高级任务 | 慢 | 高 |
最佳实践
- ✅ 推荐: 大多数任务使用
gemini-1.5-flash——速度快且性价比高 - ✅ 推荐: 面向用户的聊天界面始终使用流式响应以降低感知延迟
- ✅ 推荐: 将 API 密钥存储在环境变量中,切勿硬编码
- ✅ 推荐: 对速率限制(429)错误实现指数退避重试
- ✅ 推荐: 使用
systemInstruction设置持久的模型行为 - ❌ 避免: 对简单任务使用
gemini-pro——Flash 更便宜更快 - ❌ 避免: 对大于 20MB 的文件发送内联 base64 图像——改用 File API
- ❌ 避免: 在生产应用中忽略响应中的安全评级
错误处理
try {
const result = await model.generateContent(prompt);
return result.response.text();
} catch (error) {
if (error.status === 429) {
// 速率限制——等待并使用指数退避重试
await new Promise(r => setTimeout(r, 2 ** retryCount * 1000));
} else if (error.status === 400) {
// 无效请求——检查提示内容和格式
console.error("请求无效:", error.message);
}
}
兼容工具
Claude CodeCursor
标签
AI与机器学习