Keyboard shortcuts

Press ← or → to navigate between chapters

Press ? to show this help

Press Esc to hide this help

함수에서 모델 추론 호출

모델 함수(Model function)는 온라인 모델 배포를 감싸는 자동 생성 함수입니다. 일반 함수에서 모델을 호출하면 온톨로지 객체를 입력으로 변환하거나 여러 모델을 조합하고, 예측 결과에 업무 로직을 적용할 수 있습니다.

직접 모델 배포는 모델 페이지에서, Modeling Objective 온라인 배포는 배포 상세에서 함수를 게시합니다. 두 경로 모두 모델 API에 맞는 입력과 출력의 함수를 만들며 TSv1, TSv2와 Python에서 사용할 수 있습니다. API 변경과 함수 버전은 모델 함수 게시를 따릅니다.

가져오기와 연결 범위

Resource Imports > Add > Query Functions에서 게시할 때 정한 함수 이름으로 검색하여 가져옵니다. TSv1은 Models에서 가져와도 같습니다. Modeling Objective의 API Name 카드를 사용하는 기존 함수는 Modeling Objectives 아래에서 가져올 수 있는 지원 중 Sunset 경로입니다.

2026년 2월 이후의 새 모델 함수는 온톨로지에 연결됩니다. 이전 함수는 모델의 공간(Space)에 연결되어 있을 수 있습니다. TSv2와 Python은 온톨로지에 연결된 모델 함수만 가져올 수 있으며 TSv1은 두 방식을 모두 지원합니다. 모델 페이지에서 이전 가능 안내가 나오면 공간에 연결된 함수입니다.

Marketplace는 저장소에 가져온 모델 함수의 의존성을 추적합니다. 지원 모델과 직접 배포를 함께 패키징하거나 설치 시 사용자가 선택할 입력으로 구성할 수 있습니다. 모델 함수를 가져오지 않고 Platform SDK로 직접 호출하면 Marketplace는 이 의존성을 추적하지 않습니다.

예제 모델 API

가상의 Flight에 Timestamp lastArrivalTime과 lastExpectedArrivalTime이 있고, 모델은 두 시각을 받아 Double prediction을 반환한다고 가정합니다. Python 속성 이름은 last_arrival_time과 last_expected_arrival_time입니다.

모델 어댑터 api()에서 사용할 입력과 출력 선언은 다음과 같습니다. 모델의 실제 predict 구현은 이 API에 맞는 df_out을 생성해야 합니다.

from datetime import datetime
import palantir_models as pm

inputs = {
    "df_in": pm.Pandas(columns=[
        ("lastArrivalTime", datetime),
        ("lastExpectedArrivalTime", datetime),
    ])
}
outputs = {"df_out": pm.Pandas(columns=[("prediction", float)])}

모델 API가 표 입력 하나와 표 출력 하나만 선언하면 Enable row-wise processing은 기본으로 켜집니다. 추가 입력이나 출력이 하나라도 있으면 행 단위 게시를 지원하지 않습니다. 객체나 객체 집합을 모델 API에 직접 쓰는 대안도 있습니다.

다음 온톨로지 함수 예제는 df_in과 df_out의 배열을 사용하므로 게시할 때 행 단위 처리를 꺼야 합니다. 이 예제 모델은 입력 한 행마다 예측 한 행을 같은 순서로 반환한다는 계약입니다.

Python

가져온 생성 SDK의 flight_model_deployment를 호출합니다. @function(beta=True)를 사용합니다.

from functions.api import Double, UserFacingError, function
from ontology_sdk import FoundryClient
from ontology_sdk.ontology.objects import Flight


@function(beta=True)
def predict_flight_delays(flight: Flight) -> Double:
    if flight.last_arrival_time is None or flight.last_expected_arrival_time is None:
        raise UserFacingError("실제 도착 시각과 예정 도착 시각이 필요합니다.")
    output = FoundryClient().ontology.queries.flight_model_deployment(df_in=[{
        "lastArrivalTime": flight.last_arrival_time,
        "lastExpectedArrivalTime": flight.last_expected_arrival_time,
    }])
    if len(output.df_out) != 1 or output.df_out[0].prediction is None:
        raise UserFacingError("모델이 항공편 한 개에 대한 예측 한 개를 반환해야 합니다.")
    return output.df_out[0].prediction

TypeScript v2

predictFlightDelays.ts에 작성합니다. 입력 인스턴스는 생성 정의 Flight 자체가 아니라 Osdk.Instance<Flight>입니다.

import { Client, Osdk } from "@osdk/client";
import { Double, UserFacingError } from "@osdk/functions";
import { flightModelDeployment, Flight } from "@ontology/sdk";

export default async function predictFlightDelays(client: Client, flight: Osdk.Instance<Flight>): Promise<Double> {
    if (flight.lastArrivalTime === undefined || flight.lastExpectedArrivalTime === undefined) {
        throw new UserFacingError("실제 도착 시각과 예정 도착 시각이 필요합니다.");
    }
    const output = await client(flightModelDeployment).executeFunction({
        df_in: [{
            lastArrivalTime: flight.lastArrivalTime,
            lastExpectedArrivalTime: flight.lastExpectedArrivalTime,
        }],
    });
    const prediction = output.df_out[0]?.prediction;
    if (output.df_out.length !== 1 || typeof prediction !== "number") {
        throw new UserFacingError("모델이 항공편 한 개에 대한 예측 한 개를 반환해야 합니다.");
    }
    return prediction;
}

TypeScript v1의 온톨로지 모델 함수

Queries에서 온톨로지 함수 API 이름을 사용합니다. 게시 함수의 의존성을 @Uses로 명시합니다.

import { Double, Function, Uses, UserFacingError } from "@foundry/functions-api";
import { Queries, Flight } from "@foundry/ontology-api";

export class ModelFunctions {
    @Uses({ queries: [Queries.flightModelDeployment] })
    @Function()
    public async predictFlightDelays(flight: Flight): Promise<Double> {
        if (flight.lastArrivalTime === undefined || flight.lastExpectedArrivalTime === undefined) {
            throw new UserFacingError("실제 도착 시각과 예정 도착 시각이 필요합니다.");
        }
        const output = await Queries.flightModelDeployment({
            df_in: [{
                lastArrivalTime: flight.lastArrivalTime,
                lastExpectedArrivalTime: flight.lastExpectedArrivalTime,
            }],
        });
        const prediction = output.df_out[0]?.prediction;
        if (output.df_out.length !== 1 || typeof prediction !== "number") {
            throw new UserFacingError("모델이 항공편 한 개에 대한 예측 한 개를 반환해야 합니다.");
        }
        return prediction;
    }
}

TypeScript v1의 공간 모델 함수

공간 연결 함수는 Resource imports에 표시된 import 코드를 사용합니다. 실제 패키지 경로와 바인딩 이름을 복사해야 하며 온톨로지의 Queries 문법과 구분합니다.

행 단위 처리 여부에 따라 입력과 출력 구조가 달라집니다. 다음 helper는 생성된 모델 함수를 인수로 받아 호출합니다. 함수형 인수는 Foundry 게시 함수의 입력으로 사용할 수 없으므로 게시된 클래스 메서드 안에서 가져온 모델 바인딩을 전달하여 사용합니다.

import { Double, FunctionsMap, Timestamp, UserFacingError } from "@foundry/functions-api";
import { Flight } from "@foundry/ontology-api";

interface FlightInput {
    lastArrivalTime: Timestamp;
    lastExpectedArrivalTime: Timestamp;
}
interface Prediction {
    prediction: Double;
}
type RowWiseModel = (input: FlightInput) => Promise<Prediction>;
type BatchModel = (input: { df_in: FlightInput[] }) => Promise<{ df_out: Prediction[] }>;

function toModelInput(flight: Flight): FlightInput {
    if (flight.lastArrivalTime === undefined || flight.lastExpectedArrivalTime === undefined) {
        throw new UserFacingError("실제 도착 시각과 예정 도착 시각이 필요합니다.");
    }
    return { lastArrivalTime: flight.lastArrivalTime, lastExpectedArrivalTime: flight.lastExpectedArrivalTime };
}

export async function predictFlightDelaysRowWise(flight: Flight, invokeModel: RowWiseModel): Promise<Double> {
    const output = await invokeModel(toModelInput(flight));
    return output.prediction;
}

export async function predictFlightDelays(flights: Flight[], invokeModel: BatchModel): Promise<FunctionsMap<Flight, Double>> {
    const result = new FunctionsMap<Flight, Double>();
    if (flights.length === 0) return result;
    const output = await invokeModel({ df_in: flights.map(toModelInput) });
    if (output.df_out.length !== flights.length) {
        throw new UserFacingError("모델 출력 행 수가 입력 항공편 수와 다릅니다.");
    }
    for (let index = 0; index < flights.length; index++) {
        result.set(flights[index]!, output.df_out[index]!.prediction);
    }
    return result;
}

행 단위 helper는 입력 한 행과 출력 한 행을 직접 주고받습니다. 여러 항공편의 helper는 행 단위 처리를 끈 모델의 df_in/df_out 배열을 사용하고 객체별 예측 맵을 반환합니다. 배열 순서가 입력 객체와 대응한다는 모델 계약이 필요하며, 출력 행 수 검사가 행 순서까지 확인하는 것은 아닙니다.

온톨로지 연결로 이전

UI에서 공간 모델 함수를 온톨로지 연결로 이전하면 이미 게시한 TSv1 소비 함수 버전은 계속 동작합니다. 그러나 기존 import 문법은 새 바인딩에서 인식하지 않으므로 저장소 미리보기와 새 태그 게시가 실패합니다.

  1. 소비 저장소의 Resource imports를 엽니다.
  2. resources.json에서 새 모델 함수 버전을 선택합니다.
  3. 코드의 import와 호출을 Queries 기반 문법으로 변경합니다.

Platform SDK의 Functions.Query로 API 이름을 직접 호출하는 소비자는 이전 즉시 영향을 받습니다. API 이름은 모든 모델 함수 버전에 걸쳐 한꺼번에 이전하므로 직접 호출의 이름을 새 값으로 바꿔야 합니다.

실행 한도

모델 호출 시간은 호출한 함수의 실행 시간에 포함됩니다. 네트워크로 주고받는 모델 입력과 출력은 50 MB 한도를 따르며 전송 시간도 포함합니다. 함수 시간과 자원 설정을 확인하고 제공 범위를 넘는 조정이 필요하면 Palantir Support에 요청합니다.

함수 기반 액션이면 액션 편집 한도도 적용합니다. 모델 실행의 크기와 시간 한도가 편집할 수 있는 객체 수를 늘려 주지는 않습니다.