驗證

本頁面說明如何使用 OpenAI Python 程式庫,向 Vertex AI Chat Completions API 進行驗證。

本頁面說明下列驗證主題:

  • 選擇驗證方法比較程式輔助用戶端設定與環境變數的驗證方式。
  • 重新整理憑證瞭解如何自動重新整理存取權杖,以維持驗證狀態。

下圖概略說明整體工作流程:

安裝 OpenAI SDK

如要使用 OpenAI Python 程式庫,請安裝 OpenAI SDK

pip install openai

驗證方法

如要使用 Chat Completions API 進行驗證,您可以修改用戶端設定,也可以變更環境設定,改用 Google 驗證和 Vertex AI 端點。下表比較這些方法,協助您選擇最適合自己用途的方法。

方法 說明 優點 缺點 用途
用戶端設定 在應用程式程式碼中,以程式輔助方式使用 Google 憑證和 Vertex AI 端點設定 OpenAI 用戶端。 設定明確且獨立於應用程式程式碼中,不依賴外部環境設定。 您必須將憑證和端點網址硬式編碼,或使用個別的設定管理系統。 環境變數不易管理,或需要完全在程式碼中控管設定的應用程式。
環境變數 設定程式庫會自動讀取的標準 OpenAI 環境變數 (OPENAI_API_KEYOPENAI_BASE_URL)。 將憑證和設定與程式碼分開。輕鬆切換環境 (開發、正式版)。 需要在主機系統上管理環境變數,在某些部署情境中可能相當複雜。 建議用於大多數應用程式,特別是部署在容器化或雲端環境中的應用程式,因為設定環境變數是標準做法。

部分模型 (例如 Model Garden 中的模型和支援的 Hugging Face 模型) 必須部署至 Vertex AI 端點,才能處理要求。透過 Chat Completions API 呼叫這些自行部署的模型時,您必須指定端點 ID。如要列出現有的 Vertex AI 端點,請使用 gcloud ai endpoints list 指令

用戶端設定

如要在 Python 中以程式輔助方式取得 Google 憑證,請使用 google-auth Python SDK:

pip install google-auth requests

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Python API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import openai

from google.auth import default
import google.auth.transport.requests

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "us-central1"

# Programmatically get an access token
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
credentials.refresh(google.auth.transport.requests.Request())
# Note: the credential lives for 1 hour by default (https://cloud.google.com/docs/authentication/token-types#at-lifetime); after expiration, it must be refreshed.

##############################
# Choose one of the following:
##############################

# If you are calling a Gemini model, set the ENDPOINT_ID variable to use openapi.
ENDPOINT_ID = "openapi"

# If you are calling a self-deployed model from Model Garden, set the
# ENDPOINT_ID variable and set the client's base URL to use your endpoint.
# ENDPOINT_ID = "YOUR_ENDPOINT_ID"

# OpenAI Client
client = openai.OpenAI(
    base_url=f"https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/{ENDPOINT_ID}",
    api_key=credentials.token,
)

根據預設,存取權杖的效期為 1 小時。您可以延長存取權杖的效期,或是定期更新權杖並更新 openai.api_key 變數。

環境變數

安裝 Google Cloud CLI。OpenAI 程式庫會自動讀取 OPENAI_API_KEYOPENAI_BASE_URL 環境變數,在預設用戶端中設定驗證和端點。設定下列變數:

$ export PROJECT_ID=PROJECT_ID
$ export LOCATION=LOCATION
$ export OPENAI_API_KEY="$(gcloud auth application-default print-access-token)"

如要呼叫 Gemini 模型,請設定 MODEL_ID 變數並使用 openapi 端點:

$ export MODEL_ID=MODEL_ID
$ export OPENAI_BASE_URL="https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/endpoints/openapi"

如要從 Model Garden 呼叫自行部署的模型,請設定 ENDPOINT 變數,並在網址中使用該變數:

$ export ENDPOINT=ENDPOINT_ID
$ export OPENAI_BASE_URL="https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/endpoints/${ENDPOINT}"

接著,初始化用戶端:

client = openai.OpenAI()

Gemini Chat Completions API 會使用 OAuth 搭配短期存取權杖進行驗證。根據預設,存取權杖的效期為 1 小時。您可以延長存取權杖的效期,或定期更新權杖並更新 OPENAI_API_KEY 環境變數。

重新整理憑證

存取權杖的效期很短,預設為一小時。如要讓工作階段的驗證時間超過一小時,可以建立公用程式,自動重新整理憑證。以下 Python 範例說明如何實作這項公用程式。

Python

from typing import Any

import google.auth
import google.auth.transport.requests
import openai


class OpenAICredentialsRefresher:
    def __init__(self, **kwargs: Any) -> None:
        # Set a placeholder key here
        self.client = openai.OpenAI(**kwargs, api_key="PLACEHOLDER")
        self.creds, self.project = google.auth.default(
            scopes=["https://www.googleapis.com/auth/cloud-platform"]
        )

    def __getattr__(self, name: str) -> Any:
        if not self.creds.valid:
            self.creds.refresh(google.auth.transport.requests.Request())

            if not self.creds.valid:
                raise RuntimeError("Unable to refresh auth")

            self.client.api_key = self.creds.token
        return getattr(self.client, name)



    # TODO(developer): Update and un-comment below lines
    # project_id = "PROJECT_ID"
    # location = "us-central1"

    client = OpenAICredentialsRefresher(
        base_url=f"https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
    )

    response = client.chat.completions.create(
        model="google/gemini-2.0-flash-001",
        messages=[{"role": "user", "content": "Why is the sky blue?"}],
    )

    print(response)

後續步驟