認証

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

このサンプルを試す前に、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_KEY 環境変数と OPENAI_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 変数を設定し、代わりに URL で使用します。

$ 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)

次のステップ