Gemini API 常见错误与解决方案
使用 Gemini API 时遇到错误?本文汇总 400、403、429、500、503 等常见错误码的含义和解决方案,帮你快速排查问题。
400 Bad Request
请求格式错误,API 无法解析你的请求。
常见原因
- JSON 格式错误(缺少引号、多余逗号等)
- 必填参数缺失
- 参数类型错误(如 temperature 传了字符串)
- 模型名称拼写错误
解决方案
# 检查请求格式是否正确
from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
# 正确写法
response = client.models.generate_content(
model="gemini-2.5-flash", # 确认模型名称正确
contents="你好" # contents 不能为空
)
# 错误写法示例
# model="gemini-2.5-flsh" ← 模型名拼错
# contents="" ← 内容为空
403 Forbidden / Permission Denied
API Key 没有访问权限。
常见原因
- API Key 无效或已被撤销
- 未启用 Generative Language API
- API Key 设置了 IP 或 Referrer 限制
- 所在地区不支持 Gemini API
解决方案
- 在 Google Cloud Console 确认 API Key 有效
- 检查是否已启用 Generative Language API
- 查看 API Key 的限制设置,确保当前环境符合条件
- 如在国内使用,建议通过中转服务访问
提示:如果因地区限制无法使用 Gemini API,轻舟 AI(claude4u.com)提供中转服务,绕过地区限制,国内直连使用全部 Gemini 模型。
429 Too Many Requests / Rate Limit
请求频率超过限制。
不同等级的速率限制
- 免费用户:Gemini 2.5 Pro 每分钟 5 次,2.5 Flash 每分钟 10 次
- 付费用户:根据计费等级,可达每分钟 1000+ 次
解决方案
import time
from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
def call_with_backoff(prompt, max_retries=5):
for i in range(max_retries):
try:
return client.models.generate_content(
model="gemini-2.5-flash",
contents=prompt
)
except Exception as e:
if '429' in str(e):
wait = 2 ** i # 指数退避:1, 2, 4, 8, 16 秒
print(f"速率限制,{wait}秒后重试...")
time.sleep(wait)
continue
raise
raise Exception("超过最大重试次数")
- 升级到付费方案提高限额
- 使用批量 API 处理大量请求
- 使用中转服务的多账户负载均衡分散请求
500 Internal Server Error
Google 服务器内部错误,通常是暂时性问题。
解决方案
- 等待几秒后重试
- 检查输入内容是否包含可能触发问题的特殊字符
- 减少输入长度,排除是否因输入过长导致
- 查看 Google Cloud Status Dashboard 确认是否有服务中断
503 Service Unavailable / Model Overloaded
这是 Gemini API 最常见的错误,表示模型服务器过载。
常见错误消息
503 The model is overloaded. Please try again later.
RESOURCE_EXHAUSTED: Model capacity exhausted
解决方案
- 自动重试:加入重试逻辑,503 通常很快恢复
- 切换模型:从 2.5 Pro 切换到 2.5 Flash,容量更充足
- 错峰使用:避开北美工作时间高峰
- 使用中转服务:中转站内置自动重试机制
提示:轻舟 AI(claude4u.com)对 503 错误内置了智能重试机制(最多 60 次自动重试),并支持多账户轮转分散负载,大幅降低 503 错误率。
通用排查步骤
- 确认 API Key 有效且有足够额度
- 检查请求格式和参数是否正确
- 查看错误响应的详细信息(error.message)
- 检查网络连接和代理配置
- 查看 Google Cloud Status 页面
注意:生产环境中务必实现错误重试和降级策略。不要让单次 API 错误导致整个应用崩溃。建议结合使用中转服务和自定义错误处理逻辑。
轻舟 AI