透過 OAuth 進行驗證的快速入門導覽課程

Gemini API 可讓您對自己的資料執行語意擷取作業。由於這是您的資料,因此所需存取權控管機制比 API 金鑰更嚴格。

本快速入門導覽課程採用適用於測試環境的簡化驗證方法。如果是實際工作環境,請先瞭解驗證和授權,再選擇應用程式適用的存取憑證

目標

  • 設定 OAuth 的雲端專案
  • 設定 application-default-credentials
  • 管理程式中的憑證,而非使用 gcloud auth

必要條件

如要執行這個快速入門導覽課程,您需要:

設定 Cloud 專案

如要完成本快速入門導覽課程,您必須先設定 Cloud 專案。

1. 啟用 API

使用 Google API 前,請先在 Google Cloud 專案中啟用 API。

  • 在 Google Cloud 控制台中啟用 Google Generative Language API。

    啟用 API

2. 設定 OAuth 同意畫面

接下來,請設定專案的 OAuth 同意畫面,然後將您自己新增為測試使用者。如果您已完成 Cloud 專案的這個步驟,請跳到下一節。

  1. 在 Google Cloud 控制台中,依序前往「選單」>「API 和服務」>「OAuth 同意畫面」

    前往 OAuth 同意畫面

  2. 為應用程式選取「外部」使用者類型,然後按一下「建立」。

  3. 完成應用程式註冊表單 (大部分的欄位可留空),然後按一下「Save and Continue」

  4. 目前,您可以略過新增範圍,然後按一下「儲存並繼續」。日後建立用於 Google Workspace 機構外部的應用程式時,您必須新增並驗證應用程式需要的授權範圍。

  5. 新增測試使用者:

    1. 在「測試使用者」下方,點選「新增使用者」
    2. 輸入您的電子郵件地址及任何其他授權測試使用者,然後按一下「Save and Continue」
  6. 查看您的應用程式註冊摘要。如要變更,請按一下「編輯」。如果應用程式註冊看起來沒問題,請按一下「Back to Dashboard」(返回資訊主頁)

3. 為桌面應用程式授權憑證

如要以使用者身分進行驗證及存取應用程式中的使用者資料,您必須建立一或多個 OAuth 2.0 用戶端 ID。用戶端 ID 可用來向 Google 的 OAuth 伺服器識別單一應用程式。如果您的應用程式是在多個平台上執行,您就必須為每個平台建立個別的用戶端 ID。

  1. 在 Google Cloud 控制台中,依序前往「Menu」(選單) >「APIs & Services」(API 和服務) >「Credentials」(憑證)

    前往「憑證」

  2. 依序按一下「建立憑證」 >「OAuth 用戶端 ID」

  3. 依序按一下「應用程式類型」 >「電腦版應用程式」

  4. 在「名稱」欄位中,輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。

  5. 點選「建立」。畫面上會顯示 OAuth 用戶端已建立的畫面,顯示您的新用戶端 ID 與用戶端密鑰。

  6. 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 Client ID」(OAuth 2.0 用戶端 ID) 下方。

  7. 點選下載按鈕即可儲存 JSON 檔案。系統會將其儲存為 client_secret_<identifier>.json,並將其重新命名為 client_secret.json,並移至您的工作目錄。

設定應用程式預設憑證

如要將 client_secret.json 檔案轉換為可用的憑證,請透過 gcloud auth application-default login 指令的 --client-id-file 引數傳送其位置。

gcloud auth application-default login \
    --client-id-file=client_secret.json \
    --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.retriever'

本教學課程中簡化的專案設定會觸發「Google 尚未驗證這個應用程式」對話方塊。這是正常現象,請選擇「繼續」

這會將產生的權杖放在知名位置,方便 gcloud 或用戶端程式庫存取。

gcloud auth application-default login 
--no-browser --client-id-file=client_secret.json
--scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.retriever'

設定應用程式預設憑證 (ACD) 後,大部分語言的用戶端程式庫只需極少地找到它們。

Curl

如要測試是否正常運作,最快的方法就是使用 curl 存取 REST API:

access_token=$(gcloud auth application-default print-access-token)
project_id=<MY PROJECT ID>

curl -X GET https://generativelanguage.googleapis.com/v1/models \
    -H 'Content-Type: application/json' \
    -H "Authorization: Bearer ${access_token}" \
    -H "x-goog-user-project: ${project_id}" | grep '"name"'

Python

在 Python 中,用戶端程式庫應會自動找到這些程式庫:

pip install google-generativeai

適合測試的最簡單指令碼如下:

import google.generativeai as genai

print('Available base models:', [m.name for m in genai.list_models()])

後續步驟

如果這一切運作正常,您可以嘗試對文字資料進行語意擷取

自行管理憑證 [Python]

在多數情況下,您無法利用 gcloud 指令從用戶端 ID (client_secret.json) 建立存取權杖。Google 提供多種語言的程式庫,方便您在應用程式內管理該程序。本節會以 Python 語言示範程序。另外,Drive API 說明文件也有同樣適用於其他語言的程序範例。

1. 安裝所需的程式庫

安裝 Python 適用的 Google 用戶端程式庫以及 Gemini 用戶端程式庫。

pip install --upgrade -q google-api-python-client google-auth-httplib2 google-auth-oauthlib

pip install google-generativeai

2. 寫入憑證管理工具

為了盡可能減少您必須點閱授權畫面的次數,請在工作目錄中建立名為 load_creds.py 的檔案,快取一個之後可以重複使用的 token.json 檔案,或者在檔案過期後重新整理。

請使用以下程式碼,將 client_secret.json 檔案轉換為可使用 genai.configure 的權杖:

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['https://www.googleapis.com/auth/generative-language.retriever']

def load_creds():
    """Converts `client_secret.json` to a credential object.

    This function caches the generated tokens to minimize the use of the
    consent screen.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secret.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return creds

3. 編寫程式

現在來建立 script.py

import pprint
import google.generativeai as genai
from load_creds import load_creds

creds = load_creds()

genai.configure(credentials=creds)

print()
print('Available base models:', [m.name for m in genai.list_models()])

4. 執行程式

在工作目錄中,執行範例:

python script.py

首次執行指令碼時,系統會開啟瀏覽器視窗,並提示您授予存取權。

  1. 如果尚未登入 Google 帳戶,系統會提示您登入。如果您登入多個帳戶,請務必在設定專案時選取您設為「測試帳戶」的帳戶

  2. 授權資訊會儲存在檔案系統中,因此下次您執行程式碼範例時,系統不會提示您取得授權。

您已成功設定驗證。