Keyboard shortcuts

Press ← or → to navigate between chapters

Press ? to show this help

Press Esc to hide this help

Google Vertex AI 모델 연결

Vertex AI의 표 예측 엔드포인트를 Foundry의 외부 모델로 연결합니다. Model Adapter Library에 어댑터를 게시하고 태그를 만듭니다. 저장소가 권장하는 Python 3.10 이상 환경에 google-cloud-aiplatform, google-auth, pandas와 palantir_models를 추가하고 선택한 SDK의 지원 조건에 맞게 의존성을 해결합니다.

접속 정보와 어댑터

입력은 표이고 각 행을 이름 있는 JSON 레코드로 전달합니다. 응답 predictions는 pandas.json_normalize로 표로 만들 수 있어야 합니다. project_id, region_name 및 endpoint_id는 연결 설정이며 google_application_credentials에는 서비스 계정 키 파일 전체를 JSON 문자열로 저장합니다.

어댑터마다 프로젝트, 리전과 자격 증명을 보관하고 Endpoint 생성자에 명시적으로 전달합니다. 프로세스 전역 기본값을 다른 모델의 설정으로 바꾸지 않습니다.

import json
import logging
import pandas as pd
import palantir_models as pm
from google.oauth2 import service_account
from google.cloud import aiplatform
from google.api_core import exceptions

logger = logging.getLogger(__name__)

class VertexAITabularAdapter(pm.ExternalModelAdapter):
    def __init__(self, project_id, region_name, endpoint_id, google_application_credentials):
        self.project_id = project_id
        self.region_name = region_name
        self.endpoint_id = endpoint_id
        self.credentials = service_account.Credentials.from_service_account_info(
            json.loads(google_application_credentials),
            scopes=["https://www.googleapis.com/auth/cloud-platform"],
        )

    @classmethod
    def init_external(cls, external_context):
        return cls(
            external_context.connection_config["project_id"],
            external_context.connection_config["region_name"],
            external_context.connection_config["endpoint_id"],
            external_context.resolved_credentials["google_application_credentials"],
        )

    @classmethod
    def api(cls):
        return {"df_in": pm.Pandas()}, {"df_out": pm.Pandas()}

    def predict(self, df_in):
        instances = df_in.to_dict(orient="records")
        try:
            endpoint = aiplatform.Endpoint(
                endpoint_name=self.endpoint_id,
                project=self.project_id,
                location=self.region_name,
                credentials=self.credentials,
            )
        except ValueError:
            logger.error("Check endpoint_id, project_id and region_name.")
            raise
        try:
            prediction_result = endpoint.predict(instances=instances)
        except exceptions.Forbidden:
            logger.error("The configured Google credentials lack inference permission.")
            raise
        except exceptions.BadRequest:
            logger.error("Check the input dataframe against the endpoint contract.")
            raise
        return pd.json_normalize(prediction_result.predictions)

잘못된 엔드포인트 초기화 값은 ValueError, 추론 권한 부족은 Forbidden, 잘못된 입력 요청은 BadRequest로 기록하고 다시 발생시킵니다. 큰 응답을 표로 만드는 과정에서 실행기 메모리가 부족할 수 있습니다. 열을 지정하지 않은 표 API를 함수로 게시하려면 명시적 스키마가 필요합니다.

송신 정책과 어댑터

예시 리전은 us-central1이며 us-central1-aiplatform.googleapis.com의 443 포트를 허용합니다. 실제 리전에 맞는 Vertex AI 주소를 선택합니다.

외부 모델 연결 대화상자에서 게시한 VertexAITabularAdapter를 선택합니다.

연결 설정과 자격 증명

이 어댑터는 URL 필드를 읽지 않으므로 비워 둡니다.

연결 설정 키값
region_nameVertex AI 엔드포인트 리전입니다.
project_id외부 모델이 속한 Google Cloud 프로젝트 식별자입니다.
endpoint_id호출할 Vertex AI 엔드포인트 식별자입니다.

google_application_credentials에는 서비스 계정 비공개 키 파일의 전체 내용을 넣습니다. 파일 경로가 아니라 JSON 내용입니다. 키는 Google Cloud Console의 Credentials에서 생성할 수 있으며 Foundry의 Credentials Configuration에 암호화하여 저장합니다.

추론에서 사용

Modeling Objective의 온라인 배포 또는 송신을 구성한 Python 변환에서 사용할 수 있습니다. 모델에 접근하는 사용자는 저장한 서비스 계정의 권한으로 호출합니다. Modeling Objective의 배치 배포와 자동 평가는 지원하지 않습니다.