如要在 Vertex AI 上使用 Gemini,您需要使用 Google Cloud API 金鑰或應用程式預設憑證進行驗證。建議您在測試時使用 API 金鑰,在正式環境中使用應用程式預設憑證。本頁說明如何根據您是否已有帳戶,取得 Google Cloud API 金鑰 Google Cloud 。
選取你是否擁有 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.managed.disableServiceAccountApiKeyCreation的政策。
- 依序點選「動作」>「編輯政策」。
- 在「政策來源」下方,選取「覆寫父項政策」,然後按一下「新增規則」。
- 在「Enforcement」(強制執行) 下方,選取「Off」(關閉)。
- 按一下 [完成]。
- 按一下「設定政策」。在彈出的對話方塊中,再次點選「設定政策」。
建立新的服務帳戶
- 開啟「IAM 與管理」>「服務帳戶」。
- 按一下「建立服務帳戶」。
- 請按照下列步驟設定服務帳戶:
- 服務帳戶名稱:
vertex-ai-runner
- 服務帳戶 ID:
vertexairunner
- 服務帳戶名稱:
- 按一下「建立並繼續」。
- 在「權限」下方,按一下「選取角色」,然後從選單中選取「Vertex AI Platform Express 使用者」。
- 按一下「繼續」。
- 按一下 [完成]。
建立 API 金鑰
- 開啟「API 和服務」>「憑證」。
- 依序按一下 [Create credentials] (建立憑證) > [API key] (API 金鑰)。
- 請按照下列步驟設定 API 金鑰:
- Name (名稱):
vertexaiapikey
- 透過服務帳戶驗證 API 呼叫:已選取。
- Name (名稱):
- 按一下「選取服務帳戶」。
- 選取您在上一個步驟中建立的服務帳戶,然後按一下「選取」。
- 點選「建立」。
發出第一項 API 要求
取得 API 金鑰後,請參閱 API 快速入門,瞭解如何使用 API 金鑰發出第一個要求。
選用:在本機設定 API 金鑰
進行初步測試時,您可以將 API 金鑰寫死在程式碼中,但這並非安全做法,因此只能暫時使用。本節其餘內容將說明如何在不同作業系統中,將 API 金鑰在本機設為環境變數。
按一下即可展開操作說明
Linux/macOS
-
執行下列指令,查看您使用的指令列殼層:
echo $SHELL
輸出結果會與下列內容相似:
/bin/bash
-
新增 API 金鑰的殼層匯出變數,方法如下:
-
如果上一個步驟的輸出內容為
/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
- 套用變更