인증

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를 지정해야 합니다.

인증 방식

코드에서 클라이언트 객체를 직접 구성하거나 환경 변수를 설정하여 인증할 수 있습니다. 다음 워크플로는 이 프로세스를 간략하게 보여줍니다.

흐름 차트

사용 사례에 가장 적합한 방법을 선택합니다.

메서드 장점 단점 권장
클라이언트 설정 프로그래매틱하고 유연합니다. 애플리케이션 내에서 동적 사용자 인증 정보 관리를 허용합니다. 사용자 인증 정보와 엔드포인트를 직접 관리하는 코드가 더 필요합니다. 여러 클라이언트를 관리하거나 인증 정보를 동적으로 새로고침해야 하는 애플리케이션
환경 변수 구성을 코드와 분리하는 간단한 설정입니다. 로컬 개발과 테스트에 적합합니다. 올바르게 관리하지 않으면 보안이 취약해집니다. 유연하게 동적 사용자 인증 정보를 변경하기가 어렵습니다. 환경 변수가 표준인 빠른 시작, 로컬 개발, 컨테이너화된 배포

클라이언트 설정

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_KEYOPENAI_BASE_URL 환경 변수를 읽어 기본 클라이언트를 구성합니다.

  1. 일반 환경 변수 설정:

    export PROJECT_ID=PROJECT_ID
    export LOCATION=LOCATION
    export OPENAI_API_KEY="$(gcloud auth application-default print-access-token)"
            
  2. 모델 유형의 기준 URL 설정:

    • 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}"
                  
  3. 클라이언트 초기화:

    클라이언트는 개발자가 설정한 환경 변수를 사용합니다.

    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)
    

다음 단계