身份验证

本页面介绍了如何使用 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

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Python 设置说明执行操作。 如需了解详情,请参阅 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)

后续步骤