Gemini API Key 获取与配置

使用 Google Gemini API 需要 API Key 进行身份验证。本文介绍通过 Google AI Studio 和 Vertex AI 两种方式获取 Key,以及通过中转服务简化使用流程。

获取方式一:Google AI Studio(推荐个人开发者)

Google AI Studio 是最快获取 Gemini API Key 的方式:

  1. 访问 aistudio.google.com
  2. 使用 Google 账户登录
  3. 点击左侧导航栏的 Get API Key
  4. 选择 Create API Key in new project(或选择已有项目)
  5. 系统自动生成 API Key,点击复制
提示:Google AI Studio 生成的 Key 以 AIza 开头,可直接用于调用 Gemini API。免费额度每分钟最多 15 次请求。

获取方式二:Google Cloud Vertex AI(适合企业用户)

Vertex AI 提供企业级的 Gemini API 访问:

  1. 在 Google Cloud Console 创建项目
  2. 启用 Vertex AI API
  3. 创建服务账户并下载 JSON 凭证文件
  4. 设置环境变量指向凭证文件
# 设置 Vertex AI 凭证
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/credentials.json"
export GOOGLE_CLOUD_PROJECT="your-project-id"
export GOOGLE_CLOUD_LOCATION="us-central1"
from google import genai

client = genai.Client(
    vertexai=True,
    project="your-project-id",
    location="us-central1"
)

response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents="你好"
)
print(response.text)

API Key 安全管理

存储规范

# .env 文件
GEMINI_API_KEY=AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

# Python 中使用
import os
from google import genai

client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

API Key 限制设置

在 Google Cloud Console 中可以为 API Key 添加限制:

通过中转服务使用(国内推荐)

国内开发者直接使用 Google API Key 可能面临网络问题。使用中转服务可以一键解决:

提示:轻舟 AI(claude4u.com)支持 Gemini 全系列模型中转。你无需自己管理 Google API Key,只需使用中转站分配的统一 Key 即可。
# 通过中转服务调用 Gemini,无需 Google API Key
from openai import OpenAI

client = OpenAI(
    api_key="your-relay-key",
    base_url="https://claude4u.com/v1"
)

response = client.chat.completions.create(
    model="gemini-2.5-pro",
    messages=[{"role": "user", "content": "介绍一下量子计算"}]
)
print(response.choices[0].message.content)

常见问题

API Key 无效怎么办?

免费额度用完了怎么办?

注意:不要在公开的 GitHub 仓库、博客文章或客户端代码中暴露你的 API Key。一旦泄露,应立即在 Google Cloud Console 中撤销并重新生成。

Start Using 轻舟 AI

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

Sign Up Now