如需在 Vertex AI 上使用 Gemini,您需要使用 Google Cloud API 密钥或应用默认凭据进行身份验证。我们建议您在测试时使用 API 密钥,在生产环境中使用应用默认凭据。本页介绍了如何根据您是否已拥有 Google Cloud 账号来获取 Google Cloud API 密钥。
选择您是否有 Google Cloud 账号:
创建 Google Cloud API 密钥
如果您已有 Google Cloud 账号,请按照以下说明获取标准 Google Cloud API 密钥。或者,您也可以使用应用默认凭据,而不是使用 API 密钥。
准备工作
选择项目、启用结算功能、启用 Vertex AI API
-
Sign in to your Google Account.
If you don't already have one, sign up for a new account.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
启用服务账号 API 密钥创建功能
- 依次打开 IAM 和管理 > 组织政策。
- 在政策列表中,过滤出名为 iam.managed.disableServiceAccountApiKeyCreation 的政策。
- 依次点击操作 > 修改政策。
- 在政策来源下方,选择覆盖父资源的政策,然后点击添加规则。
- 在强制执行下方,选择关闭。
- 点击完成。
- 点击设置政策。在弹出的对话框中,再次点击设置政策。
创建新服务账号
- 依次打开 IAM 和管理 > 服务账号。
- 点击创建服务账号。
- 按如下方式配置服务账号:
- 服务账号名称:
vertex-ai-runner
- 服务账号 ID:
vertexairunner
- 服务账号名称:
- 点击创建并继续。
- 在权限下,点击选择角色,然后从菜单中选择 Vertex AI Platform Express User。
- 点击继续。
- 点击完成。
创建 API 密钥
- 依次打开 API 和服务 > 凭据。
- 点击创建凭据 > API 密钥。
- 按如下方式配置 API 密钥:
- 名称:
vertexaiapikey
- 通过服务账号对 API 调用进行身份验证:已选中。
- 名称:
- 点击选择服务账号。
- 选择您在上一步中创建的服务账号,然后点击选择。
- 点击创建。
发出您的第一个 API 请求
获取 API 密钥后,请参阅 API 快速入门,了解如何使用 API 密钥发出首个请求。
可选:在本地设置 API 密钥
对于初始测试,您可以对 API 密钥进行硬编码,但这应该只是暂时性的,因为这样做不安全。本部分的其余内容将介绍如何在本地将 API 密钥作为环境变量设置为不同的操作系统。
点击即可展开说明
Linux/macOS
-
运行以下命令,查看您使用的是哪种命令行 shell:
echo $SHELL
输出类似于以下内容:
/bin/bash
-
为您的 API 密钥添加 shell 导出变量,具体方法如下:
-
如果上一步的输出为
/bin/bash
:-
打开
.bashrc
:touch ~/.bashrc open ~/.bashrc
-
将以下行添加到
.bashrc
中:export GEMINI_API_KEY=YOUR_API_KEY
-
保存文件,然后运行以下命令以应用更改:
source ~/.bashrc
-
-
如果上一步的输出为
/bin/zsh
:-
打开
.zshrc
:touch ~/.zshrc open ~/.zshrc
-
将以下行添加到
.zshrc
中:export GEMINI_API_KEY= YOUR_API_KEY
-
保存文件,然后运行以下命令以应用更改:
source ~/.zshrc
-
-
Windows
- 在系统设置中搜索“环境变量”
- 修改“用户变量”(适用于当前用户)或“系统变量”(适用于所有用户,请谨慎使用)。
- 创建变量并添加
export GEMINI_API_KEY=YOUR_API_KEY
- 应用更改