Google Gemini API 是目前最强大的多模态 AI API 之一。无论是文本生成、图像理解,还是代码辅助,Gemini API 都能提供卓越的性能。
而且,对于有学生认证的用户,Gemini API 的价格极具竞争力。本教程将带你从零开始,快速集成 Gemini API 到你的应用中。
为什么选择 Gemini API?
在开始之前,先了解为什么 Gemini 值得你的时间:
- 多模态能力:同时支持文本、图像、视频、音频
- 长上下文窗口:最高支持 200 万 tokens( Gemini 2.0 Pro)
- 价格优势:学生认证后 $2/月 → API 也有优惠
- 速度快:响应延迟通常比 GPT-4 低
- 免费额度:每天有免费调用额度
前置准备
1. 获取 API Key
- 访问 Google AI Studio
- 登录你的 Google 账号
- 点击 “Get API Key”
- 创建一个新的 API Key(或者使用现有的)
⚠️ 安全提示:
- 不要把 API Key 硬编码到代码里
- 使用环境变量存储
- 定期轮换 API Key
2. 安装 SDK
Google 提供了官方 SDK,支持 Python、Node.js、Go 等多种语言。
Python:
pip install google-generativeai
Node.js:
npm install @google/generative-ai
快速开始
Python 示例
import os
import google.generativeai as genai
# 配置 API Key
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
# 创建模型
model = genai.GenerativeModel('gemini-2.0-flash-exp')
# 生成文本
response = model.generate_content("写一首关于编程的诗")
print(response.text)
Node.js 示例
import { GoogleGenerativeAI } from '@google/generative-ai';
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash-exp' });
const prompt = "写一首关于编程的诗";
const result = await model.generateContent(prompt);
console.log(result.response.text());
核心功能详解
1. 文本生成
基础文本生成是最常用的功能:
response = model.generate_content(
"解释什么是量子计算,用简单的语言"
)
print(response.text)
参数控制:
response = model.generate_content(
"写一个 Python 快速排序",
generation_config=genai.types.GenerationConfig(
temperature=0.7,
top_p=0.9,
top_k=40,
max_output_tokens=2048,
)
)
2. 多轮对话
保持上下文的多轮对话:
chat = model.start_chat(history=[])
response = chat.send_message("我是 Python 初学者")
print(response.text)
response = chat.send_message("给我推荐一些学习资源")
print(response.text)
# chat.history 会自动保存对话历史
3. 多模态输入
Gemini 的杀手锏之一:理解图像!
import PIL.Image
# 加载图片
img = PIL.Image.open('screenshot.png')
# 图像理解
response = model.generate_content([
"这张图里有什么?请详细描述",
img
])
print(response.text)
同时上传多张图片:
img1 = PIL.Image.open('image1.jpg')
img2 = PIL.Image.open('image2.jpg')
response = model.generate_content([
"比较这两张图片的区别",
img1, img2
])
4. 流式输出
对于长文本生成,流式输出能提升用户体验:
response = model.generate_content(
"写一个完整的 Flask 应用教程",
stream=True
)
for chunk in response:
print(chunk.text, end='')
print() # 逐块输出
5. 系统指令
设置角色和行为:
model = genai.GenerativeModel(
'gemini-2.0-flash-exp',
system_instruction=[
"你是一个资深 Python 开发者",
"你的回答要简洁、实用、包含代码示例"
]
)
response = model.generate_content("如何优化 Python 代码性能?")
高级技巧
1. Function Calling(函数调用)
让 AI 能调用外部工具:
def get_weather(location: str) -> dict:
"""获取指定位置的天气"""
# 实际实现中调用天气 API
return {"location": location, "temp": 25, "condition": "晴"}
# 定义可用的函数
tools = [{
"function_declarations": [
{
"name": "get_weather",
"description": "获取天气信息",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称"
}
},
"required": ["location"]
}
}
]
}]
model = genai.GenerativeModel(
'gemini-2.0-flash-exp',
tools=tools
)
response = model.generate_content("北京今天天气怎么样?")
# Gemini 会返回需要调用 get_weather("北京")
2. 上下文窗口管理
Gemini 2.0 支持超长上下文:
# 读取长文档
with open('large_document.txt', 'r') as f:
long_text = f.read()
response = model.generate_content([
"总结这个文档的核心观点",
long_text
])
⚠️ 注意:
- Flash 模型适合快速响应
- Pro 模型适合复杂任务和长上下文
- 超长上下文会消耗更多 tokens
3. 安全过滤器
配置内容安全级别:
safety_settings = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
}
]
response = model.generate_content(
prompt,
safety_settings=safety_settings
)
实战案例
案例 1:智能客服机器人
class CustomerServiceBot:
def __init__(self):
self.model = genai.GenerativeModel('gemini-2.0-flash-exp')
self.chat = self.model.start_chat(history=[])
self.system_prompt = """
你是一个专业的客服代表。
规则:
1. 语气友好、专业
2. 先理解用户问题
3. 提供具体解决方案
4. 如果无法解决,建议转人工
"""
def respond(self, user_message: str) -> str:
response = self.chat.send_message(
f"{self.system_prompt}\n\n用户:{user_message}"
)
return response.text
# 使用
bot = CustomerServiceBot()
print(bot.respond("我的订单什么时候到?"))
案例 2:代码审查助手
def code_review(code: str, language: str) -> str:
model = genai.GenerativeModel('gemini-2.0-flash-exp')
prompt = f"""
作为资深 {language} 开发者,审查以下代码:
```{language}
{code}
```
请分析:
1. 潜在 bug
2. 性能问题
3. 代码风格建议
4. 安全漏洞
"""
response = model.generate_content(prompt)
return response.text
案例 3:图像描述生成器
def describe_image(image_path: str) -> str:
model = genai.GenerativeModel('gemini-2.0-flash-exp')
img = PIL.Image.open(image_path)
response = model.generate_content([
"详细描述这张图片的内容,包括主体、背景、颜色、风格",
img
])
return response.text
成本优化
定价策略(2026)
| 模型 | 输入 | 输出 | 免费额度 |
|---|---|---|---|
| Gemini 2.0 Flash | $0.075/1M tokens | $0.30/1M tokens | 每天 15 次/分钟 |
| Gemini 2.0 Pro | $1.25/1M tokens | $5.00/1M tokens | 每天 2 次/分钟 |
学生优惠:
- Gemini Advanced:$2/月(原价 $20)
- API 也有相应折扣
省钱技巧
-
选择合适的模型
- 简单任务用 Flash
- 复杂任务用 Pro
-
缓存常用响应
import hashlib import json def cache_key(prompt: str) -> str: return hashlib.md5(prompt.encode()).hexdigest() # 检查缓存 → 调用 API → 保存结果 -
限制输出长度
generation_config=genai.types.GenerationConfig( max_output_tokens=1024, # 不要太长 ) -
批量处理
- 合并相似的请求
- 减少调用次数
错误处理
from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold
try:
response = model.generate_content(
prompt,
generation_config=GenerationConfig(
temperature=0.7,
max_output_tokens=2048
)
)
# 检查是否被安全过滤器阻止
if response.candidates[0].finish_reason == 2: # SAFETY
print("内容被安全过滤器阻止")
except Exception as e:
print(f"API 调用失败: {e}")
常见问题
Q: Gemini 和 ChatGPT 怎么选?
A: 看需求:
- 需要长上下文 → Gemini 2.0 Pro(200万 tokens)
- 需要图像理解 → Gemini
- 需要最便宜 → Gemini Flash + 学生认证
- 需要最好推理 → GPT-4
Q: API Key 泄露了怎么办?
A: 立即:
- 在 AI Studio 删除旧 Key
- 生成新的 Key
- 更新所有应用
- 检查调用日志,确认没有被滥用
Q: 免费额度够用吗?
A: 对于个人项目,通常够用:
- Flash 模型:15 次/分钟
- 每天约 21,600 次调用
- 对于测试、小规模应用完全足够
生产环境建议付费。
下一步
掌握了基础后,你可以:
-
深入学习:Google AI 官方文档
-
探索模型:在 AI Studio 测试不同模型
-
构建应用:
- 聊天机器人
- 内容生成器
- 图像分析工具
- 代码助手
-
进阶技能:
- 微调模型(Fine-tuning)
- 批量处理
- 异步调用
- 监控和日志
总结:
Gemini API 是目前最全面的 AI API 之一。无论是功能、价格还是易用性,都表现出色。特别是对于学生和初创公司,Gemini 提供了极具性价比的方案。
从文本生成到多模态理解,从简单对话到复杂应用,Gemini API 都能胜任。开始使用吧!
了解更多 AI 工具和技术,访问 80aj.com