获取 Google Cloud API 密钥

如需在 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

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Enable the API

启用服务账号 API 密钥创建功能

  1. 依次打开 IAM 和管理 > 组织政策
  2. 在政策列表中,过滤出名为 iam.managed.disableServiceAccountApiKeyCreation 的政策。
  3. 依次点击操作 > 修改政策
  4. 政策来源下方,选择覆盖父资源的政策,然后点击添加规则
  5. 强制执行下方,选择关闭
  6. 点击完成
  7. 点击设置政策。在弹出的对话框中,再次点击设置政策

创建新服务账号

  1. 依次打开 IAM 和管理 > 服务账号
  2. 点击创建服务账号
  3. 按如下方式配置服务账号:
    • 服务账号名称vertex-ai-runner
    • 服务账号 IDvertexairunner
  4. 点击创建并继续
  5. 权限下,点击选择角色,然后从菜单中选择 Vertex AI Platform Express User
  6. 点击继续
  7. 点击完成

创建 API 密钥

  1. 依次打开 API 和服务 > 凭据
  2. 点击创建凭据 > API 密钥
  3. 按如下方式配置 API 密钥:
    • 名称vertexaiapikey
    • 通过服务账号对 API 调用进行身份验证:已选中。
  4. 点击选择服务账号
  5. 选择您在上一步中创建的服务账号,然后点击选择
  6. 点击创建

发出您的第一个 API 请求

获取 API 密钥后,请参阅 API 快速入门,了解如何使用 API 密钥发出首个请求。

可选:在本地设置 API 密钥

对于初始测试,您可以对 API 密钥进行硬编码,但这应该只是暂时性的,因为这样做不安全。本部分的其余内容将介绍如何在本地将 API 密钥作为环境变量设置为不同的操作系统。

点击即可展开说明

Linux/macOS

  1. 运行以下命令,查看您使用的是哪种命令行 shell:

    echo $SHELL

    输出类似于以下内容:

    /bin/bash
  2. 为您的 API 密钥添加 shell 导出变量,具体方法如下:

    • 如果上一步的输出为 /bin/bash

      1. 打开 .bashrc

        touch ~/.bashrc
                open ~/.bashrc
      2. 将以下行添加到 .bashrc 中:

        export GEMINI_API_KEY=YOUR_API_KEY
      3. 保存文件,然后运行以下命令以应用更改:

        source ~/.bashrc
    • 如果上一步的输出为 /bin/zsh

      1. 打开 .zshrc

        touch ~/.zshrc
                open ~/.zshrc
      2. 将以下行添加到 .zshrc 中:

        export GEMINI_API_KEY= YOUR_API_KEY
      3. 保存文件,然后运行以下命令以应用更改:

        source ~/.zshrc

Windows

  1. 在系统设置中搜索“环境变量”
  2. 修改“用户变量”(适用于当前用户)或“系统变量”(适用于所有用户,请谨慎使用)。
  3. 创建变量并添加 export GEMINI_API_KEY=YOUR_API_KEY
  4. 应用更改