驗證

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

pip install openai

如要使用 Chat Completions API 進行驗證,您可以修改用戶端設定,或變更環境設定,以使用 Google 驗證和 Vertex AI 端點。選擇較簡單的方法,然後根據您要呼叫 Gemini 模型還是自行部署的 Model Garden 模型,按照步驟進行設定。

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

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)

後續步驟