예측

비동기 생성 작업 이해하기 — 제출, 폴링, 결과 조회

예측이란?

Atlas Cloud에 이미지 또는 동영상 생성 요청을 제출하면 작업이 즉시 완료되지 않습니다. 대신, 작업 진행 상황을 추적하고 준비되면 결과를 조회하는 데 사용할 수 있는 예측 ID를 받게 됩니다.

이 비동기 패턴은 LLM이 아닌 모든 생성 작업(이미지, 동영상 등)에 사용됩니다. 이러한 작업은 완료까지 몇 초에서 몇 분이 걸릴 수 있기 때문입니다.

예측 수명 주기

┌─────────┐     ┌────────────┐     ┌───────────┐
│ 작업     │ ──→ │  처리 중    │ ──→ │  완료     │
│ 제출     │     │            │     │           │
└─────────┘     └────────────┘     └───────────┘


                ┌───────────┐
                │   실패    │
                └───────────┘

상태 값:

  • processing — 모델이 작업을 처리 중
  • completed — 생성 완료, 출력 사용 가능
  • failed — 생성 실패, 오류 상세 정보 사용 가능

작업 제출

이미지 생성

import requests

response = requests.post(
    "https://api.atlascloud.ai/api/v1/model/generateImage",
    headers={
        "Authorization": "Bearer your-api-key",
        "Content-Type": "application/json"
    },
    json={
        "model": "seedream-3.0",
        "prompt": "A beautiful mountain landscape at golden hour"
    }
)

data = response.json()
prediction_id = data["data"]["id"]
print(f"Task submitted: {prediction_id}")

동영상 생성

response = requests.post(
    "https://api.atlascloud.ai/api/v1/model/generateVideo",
    headers={
        "Authorization": "Bearer your-api-key",
        "Content-Type": "application/json"
    },
    json={
        "model": "kling-v2.0",
        "prompt": "Ocean waves crashing on a rocky shore at sunset"
    }
)

data = response.json()
prediction_id = data["data"]["id"]

결과 폴링

예측 ID를 사용하여 작업 상태를 확인하고 출력을 조회합니다:

import requests
import time

def wait_for_result(prediction_id, api_key, interval=5, timeout=300):
    """타임아웃과 함께 생성 결과를 폴링합니다."""
    elapsed = 0
    while elapsed < timeout:
        response = requests.get(
            f"https://api.atlascloud.ai/api/v1/model/prediction/{prediction_id}",
            headers={"Authorization": f"Bearer {api_key}"}
        )
        result = response.json()
        status = result["data"]["status"]

        if status == "completed":
            return result["data"]["outputs"][0]
        elif status == "failed":
            raise Exception(f"Generation failed: {result['data'].get('error')}")

        print(f"Status: {status} ({elapsed}s elapsed)")
        time.sleep(interval)
        elapsed += interval

    raise TimeoutError(f"Task did not complete within {timeout}s")

# 사용 예
output = wait_for_result("your-prediction-id", "your-api-key")
print(f"Result: {output}")

Node.js 예제

async function waitForResult(predictionId, apiKey, interval = 5000, timeout = 300000) {
  const startTime = Date.now();

  while (Date.now() - startTime < timeout) {
    const response = await fetch(
      `https://api.atlascloud.ai/api/v1/model/prediction/${predictionId}`,
      { headers: { Authorization: `Bearer ${apiKey}` } }
    );
    const result = await response.json();
    const status = result.data.status;

    if (status === "completed") return result.data.outputs[0];
    if (status === "failed") throw new Error(`Failed: ${result.data.error}`);

    console.log(`Status: ${status}`);
    await new Promise((r) => setTimeout(r, interval));
  }

  throw new Error("Timeout");
}

const output = await waitForResult("your-prediction-id", "your-api-key");
console.log(`Result: ${output}`);

cURL 예제

curl "https://api.atlascloud.ai/api/v1/model/prediction/your-prediction-id" \
  -H "Authorization: Bearer your-api-key"

폴링 모범 사례

  • 긴 간격으로 시작하세요: 동영상 생성에는 5초, 이미지 생성에는 2초 간격 사용
  • 타임아웃을 설정하세요: 무한 폴링을 방지하기 위해 항상 최대 대기 시간을 설정
  • 실패를 적절히 처리하세요: failed 상태를 확인하고 오류를 적절히 처리
  • 진행 상황을 기록하세요: 사용자가 작업이 계속 진행 중임을 알 수 있도록 상태를 출력

일반적인 생성 시간

작업 유형일반적인 시간
이미지 생성2~10초
동영상 생성30초 ~ 3분
이미지-투-비디오30초 ~ 3분
이미지 도구 (업스케일 등)5~15초

실제 시간은 모델, 파라미터(해상도, 길이) 및 현재 부하에 따라 달라집니다.

오류 처리

예측이 실패하면 결과에 오류 메시지가 포함됩니다:

{
  "status": "failed",
  "error": "Invalid parameter: resolution not supported by this model"
}

일반적인 실패 원인:

  • 잘못된 모델 파라미터
  • 접근할 수 없는 입력 이미지 URL
  • 허용되지 않는 콘텐츠가 포함된 프롬프트
  • 부족한 계정 잔액

전체 오류 코드 문서는 API 레퍼런스를 참조하세요.