如需将 OpenAI Python 库与 Vertex AI 搭配使用,您需要使用 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。
身份验证方法
您可以通过直接在代码中配置客户端对象或设置环境变量来进行身份验证。以下工作流程概述了该流程。
选择最适合您的应用场景的方法。
方法 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
客户端设置 | 程序化且灵活。允许在应用中进行动态凭据管理。 | 需要更多代码才能直接管理凭据和端点。 | 需要管理多个客户端或动态刷新凭据的应用。 |
环境变量 | 简单的设置,可将配置与代码分开。非常适合本地开发和测试。 | 如果未正确管理,安全性会降低。对动态凭据更改的灵活性较低。 | 快速入门、本地开发和容器化部署(环境变量为标准)。 |
客户端设置
您可以在 Python 代码中以编程方式获取 Google 凭据并配置 OpenAI 客户端。默认情况下,访问令牌会在 1 小时后过期。对于长时间运行的应用,请参阅如何刷新凭据。
查看用于设置客户端的 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()
默认情况下,访问令牌会在 1 小时后过期。您需要定期刷新令牌并更新 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。