Gemini API 常见错误与解决方案

使用 Gemini API 时遇到错误?本文汇总 400、403、429、500、503 等常见错误码的含义和解决方案,帮你快速排查问题。

400 Bad Request

请求格式错误,API 无法解析你的请求。

常见原因

解决方案

# 检查请求格式是否正确
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 没有访问权限。

常见原因

解决方案

  1. 在 Google Cloud Console 确认 API Key 有效
  2. 检查是否已启用 Generative Language API
  3. 查看 API Key 的限制设置,确保当前环境符合条件
  4. 如在国内使用,建议通过中转服务访问
提示:如果因地区限制无法使用 Gemini API,轻舟 AI(claude4u.com)提供中转服务,绕过地区限制,国内直连使用全部 Gemini 模型。

429 Too Many Requests / Rate Limit

请求频率超过限制。

不同等级的速率限制

解决方案

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("超过最大重试次数")

500 Internal Server Error

Google 服务器内部错误,通常是暂时性问题。

解决方案

503 Service Unavailable / Model Overloaded

这是 Gemini API 最常见的错误,表示模型服务器过载。

常见错误消息

503 The model is overloaded. Please try again later.
RESOURCE_EXHAUSTED: Model capacity exhausted

解决方案

  1. 自动重试:加入重试逻辑,503 通常很快恢复
  2. 切换模型:从 2.5 Pro 切换到 2.5 Flash,容量更充足
  3. 错峰使用:避开北美工作时间高峰
  4. 使用中转服务:中转站内置自动重试机制
提示:轻舟 AI(claude4u.com)对 503 错误内置了智能重试机制(最多 60 次自动重试),并支持多账户轮转分散负载,大幅降低 503 错误率。

通用排查步骤

  1. 确认 API Key 有效且有足够额度
  2. 检查请求格式和参数是否正确
  3. 查看错误响应的详细信息(error.message)
  4. 检查网络连接和代理配置
  5. 查看 Google Cloud Status 页面
注意:生产环境中务必实现错误重试和降级策略。不要让单次 API 错误导致整个应用崩溃。建议结合使用中转服务和自定义错误处理逻辑。

Start Using 轻舟 AI

Stable, fast AI API relay — supports Claude, OpenAI, Gemini and more

Sign Up Now