前置条件
Google Cloud 项目
启用 Vertex AI API
本地安装 gcloud CLI
两种配置模式
模式1:非Express模式(完整功能)
适用场景:生产环境,需要完整功能
配置步骤:
身份验证
gcloud auth application-default login
设置环境变量
export GOOGLE_CLOUD_PROJECT="your-project-id"
export GOOGLE_CLOUD_LOCATION="global" # 对于Gemini API使用global
永久保存(ZSH用户)
echo 'export GOOGLE_CLOUD_PROJECT="your-project-id"' >> ~/.zshrc
echo 'export GOOGLE_CLOUD_LOCATION="global"' >> ~/.zshrc
source ~/.zshrc
模式2:Express模式(简化版)
适用场景:快速开始,简单项目
配置步骤:
export GOOGLE_API_KEY="your-api-key"
echo 'export GOOGLE_API_KEY="your-api-key"' >> ~/.zshrc
🔍 获取必要信息
获取项目ID
# 查看当前项目
gcloud config get-value project
# 查看所有项目
gcloud projects list
获取API密钥(Express模式)
导航到 "APIs & Services" > "Credentials"
点击 "Create Credentials" > "API Key"
区域选择
Gemini API: 使用
global
其他服务: 选择就近区域
美国:
us-central1
,us-east1
亚太:
asia-east1
,asia-northeast1
欧洲:
europe-west1
,europe-west2
常见问题解决
权限不足错误 (PERMISSION_DENIED)
症状:Request had insufficient authentication scopes
解决方案:
重新认证
gcloud auth application-default login
启用必要API
gcloud services enable aiplatform.googleapis.com
gcloud services enable generativelanguage.googleapis.com
完全重置(如果还有问题)
# 撤销所有认证
gcloud auth revoke --all
# 重新登录
gcloud auth login
gcloud auth application-default login
# 设置项目
gcloud config set project your-project-id
验证配置
# 检查认证状态
gcloud auth list
# 检查项目配置
gcloud config list
# 检查环境变量
echo $GOOGLE_CLOUD_PROJECT
echo $GOOGLE_CLOUD_LOCATION
# 检查API状态
gcloud services list --enabled | grep -E "(aiplatform|generative)"
# 测试访问令牌
gcloud auth application-default print-access-token
完整配置示例
基于实际项目的配置:
# 1. 身份验证
gcloud auth application-default login
# 2. 启用API
gcloud services enable aiplatform.googleapis.com
gcloud services enable generativelanguage.googleapis.com
# 3. 设置环境变量
export GOOGLE_CLOUD_PROJECT="gen-lang-client-006224"
export GOOGLE_CLOUD_LOCATION="global"
# 4. 永久保存
echo 'export GOOGLE_CLOUD_PROJECT="gen-lang-client-00224"' >> ~/.zshrc
echo 'export GOOGLE_CLOUD_LOCATION="global"' >> ~/.zshrc
source ~/.zshrc
# 5. 验证
gcloud auth application-default print-access-token
🎯 最佳实践
选择合适模式
学习/开发:Express模式
生产环境:非Express模式
安全考虑
不要将API密钥提交到代码仓库
定期轮换API密钥
使用环境变量存储敏感信息
Shell配置
Bash用户:修改
~/.bashrc
Zsh用户:修改
~/.zshrc
通用:修改
~/.profile
故障排除
配置更改后重启终端或运行
source
API启用可能需要1-2分钟生效
检查项目计费状态和API配额
📚 相关链接
更新时间:2025年7月9日
适用版本:gcloud CLI 最新版本