如要在 Vertex AI 中使用 OpenAI Python 程式庫,您必須使用 Google 憑證進行驗證,並設定用戶端使用 Vertex AI 端點。本文將說明如何設定環境,並使用兩種不同的方法進行驗證。
事前準備
必要條件
1. 安裝 SDK
安裝 OpenAI 和 Google Auth SDK:
pip install openai google-auth requests
2. 設定驗證方法
如要向 Vertex AI 進行驗證,請設定應用程式預設憑證 (ADC)。詳情請參閱「設定應用程式預設憑證」。
3. 找出端點
端點取決於您呼叫的模型類型:
- Gemini 模型:使用
openapi
做為端點 ID。 - 自行部署的模型:Model Garden 中的部分模型和支援的 Hugging Face 模型必須先部署,才能處理要求。呼叫這些模型時,您必須指定部署作業的專屬端點 ID。
驗證方法
您可以直接在程式碼中設定用戶端物件,或設定環境變數來進行驗證。下列工作流程概略說明這項程序。
請選擇最適合您用途的方法。
方法 | 優點 | 缺點 | 最適合 |
---|---|---|---|
用戶端設定 | 程式輔助且具彈性。允許在應用程式中動態管理憑證。 | 需要更多程式碼才能直接管理憑證和端點。 | 需要動態管理多個用戶端或重新整理憑證的應用程式。 |
環境變數 | 簡單的設定,可將設定與程式碼分開。適合用於本機開發和測試。 | 如果未妥善管理,安全性就會降低。動態憑證變更的彈性較低。 | 快速入門導覽課程、本機開發作業,以及環境變數為標準值的容器化部署作業。 |
用戶端設定
您可以透過程式輔助方式取得 Google 憑證,並在 Python 程式碼中設定 OpenAI 用戶端。根據預設,存取權杖會在一小時後失效。如為長時間執行的應用程式,請參閱如何重新整理憑證。
查看用於用戶端設定的 Python 程式碼
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, )
環境變數
您可以使用 Google Cloud CLI 取得存取權杖。OpenAI 程式庫會自動讀取 OPENAI_API_KEY
和 OPENAI_BASE_URL
環境變數,設定預設用戶端。
-
設定常見的環境變數:
export PROJECT_ID=PROJECT_ID export LOCATION=LOCATION export OPENAI_API_KEY="$(gcloud auth application-default print-access-token)"
-
設定模型類型的基礎網址:
-
Gemini 模型:
export MODEL_ID=MODEL_ID export OPENAI_BASE_URL="https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/endpoints/openapi"
-
如果是從 Model Garden 自行部署的模型:
export ENDPOINT=ENDPOINT_ID export OPENAI_BASE_URL="https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/endpoints/${ENDPOINT}"
-
-
初始化用戶端:
用戶端會使用您設定的環境變數。
client = openai.OpenAI()
根據預設,存取權杖會在一小時後失效。您需要定期重新整理權杖,並更新 OPENAI_API_KEY
環境變數。
重新整理憑證
從應用程式預設憑證取得的存取權杖會在 1 小時後失效。對於長時間執行的服務或應用程式,您應實作一種機制來重新整理權杖。以下範例示範包裝函式類別,可在權杖到期時自動重新整理權杖。
查看憑證進修課程範例
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)
後續步驟
- 請參閱使用與 OpenAI 相容的語法呼叫 Chat Completions API 的範例。
- 請參閱使用與 OpenAI 相容的語法呼叫 Inference API 的範例。
- 請參閱使用與 OpenAI 相容的語法呼叫 Function Calling API 的範例。
- 進一步瞭解 Gemini API。