Gemini API Key 获取与配置
使用 Google Gemini API 需要 API Key 进行身份验证。本文介绍通过 Google AI Studio 和 Vertex AI 两种方式获取 Key,以及通过中转服务简化使用流程。
获取方式一:Google AI Studio(推荐个人开发者)
Google AI Studio 是最快获取 Gemini API Key 的方式:
- 访问
aistudio.google.com - 使用 Google 账户登录
- 点击左侧导航栏的 Get API Key
- 选择 Create API Key in new project(或选择已有项目)
- 系统自动生成 API Key,点击复制
提示:Google AI Studio 生成的 Key 以
AIza 开头,可直接用于调用 Gemini API。免费额度每分钟最多 15 次请求。
获取方式二:Google Cloud Vertex AI(适合企业用户)
Vertex AI 提供企业级的 Gemini API 访问:
- 在 Google Cloud Console 创建项目
- 启用 Vertex AI API
- 创建服务账户并下载 JSON 凭证文件
- 设置环境变量指向凭证文件
# 设置 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文件存储,不要硬编码 - 将
.env加入.gitignore,避免提交到代码仓库 - 生产环境使用密钥管理服务(如 Google Secret Manager)
# .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 添加限制:
- HTTP 来源限制:只允许特定域名使用
- IP 限制:只允许特定 IP 地址访问
- API 限制:只允许调用特定的 Google API
通过中转服务使用(国内推荐)
国内开发者直接使用 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 无效怎么办?
- 确认 Key 复制完整,无多余空格
- 检查 Key 对应的 Google Cloud 项目是否已启用 Generative Language API
- 确认 Key 没有设置过于严格的访问限制
免费额度用完了怎么办?
- 在 Google AI Studio 中升级为付费方案
- 或使用 claude4u.com 中转服务,按实际用量付费,无需绑定 Google 付费账户
注意:不要在公开的 GitHub 仓库、博客文章或客户端代码中暴露你的 API Key。一旦泄露,应立即在 Google Cloud Console 中撤销并重新生成。
轻舟 AI