Skip to main content
MAGIAI
핵심 API검증일 2026-12-02

MAGI-2 프로덕션 SDK 예제: TypeScript, Python & cURL

플래그십 MAGI-2는 표준 HTTPS REST 기반의 깔끔한 JSON 인터페이스를 사용하므로 별도의 독점 바이너리 SDK가 전혀 필요하지 않습니다. 아래에 제공된 프로덕션용 TypeScript, Python 및 cURL 클라이언트는 20슬롯 / 30초 옴니 레퍼런스 사전 검증기, 7~26분 대기열을 고려한 60초 유예 + 25초 지터(Jitter) 폴링, 자동 `policy_filtered` 처리 및 직접 MP4 아카이빙 기능을 즉시 사용할 수 있도록 포함하고 있습니다.

지원 언어
TypeScript · Python · cURL
의존성
네이티브 fetch / httpx / curl
사전 검증 항목
길이, 레퍼런스 및 프롬프트
인증 표준
Bearer 토큰 HTTPS

TypeScript / Node.js 22+ 프로덕션 클라이언트 (T2V, I2V & Omni-Ref)

의존성이 전혀 없는 이 TypeScript 모듈은 Node.js 22+, Bun, Cloudflare Workers(제출 단계) 또는 백그라운드 작업 러너(BullMQ / Trigger.dev / Inngest)에서 깔끔하게 실행됩니다. 네트워크 요청을 보내기 전에 2026년 12월 2일 기준 검증된 MAGI-2 제약을 모두 적용하므로, 잘못된 영상 길이나 31초짜리 영상 레퍼런스 번들은 불필요한 HTTP 왕복 없이 로컬에서 1밀리초 만에 즉시 실패 처리됩니다.

magi2-client.ts — 사전 검증 및 비동기 폴링이 포함된 완전한 타입 지원 클라이언트
typescript
export type AspectRatio = "16:9" | "9:16" | "21:9" | "4:3" | "3:4" | "1:1";

export type Magi2Request =
  | {
      mode: "text-to-video";
      prompt: string;
      duration: number;
      aspect_ratio?: AspectRatio;
    }
  | {
      mode: "image-to-video";
      prompt: string;
      duration: number;
      image: string;
      last_image?: string;
    }
  | {
      mode: "reference-to-video";
      prompt: string;
      duration: number;
      aspect_ratio?: AspectRatio;
      images?: string[];
      videos?: string[];
      audios?: string[];
    };

const BASE_URL = "https://api.atlascloud.ai";

function validateRequest(req: Magi2Request): void {
  if (!Number.isInteger(req.duration) || req.duration < 4 || req.duration > 30) {
    throw new Error("duration must be an integer between 4 and 30 seconds.");
  }
  if (!req.prompt.trim() || req.prompt.length > 15_000) {
    throw new Error("prompt must be 1 to 15,000 characters.");
  }
  if (req.mode === "reference-to-video") {
    const imgs = req.images?.length ?? 0;
    const vids = req.videos?.length ?? 0;
    const auds = req.audios?.length ?? 0;
    if (imgs > 10 || vids > 5 || auds > 5 || imgs + vids + auds > 20) {
      throw new Error("Omni-Ref cap exceeded: max 10 images, 5 videos, 5 audios, 20 total.");
    }
  }
}

export async function submitMagi2(req: Magi2Request, apiKey: string): Promise<string> {
  validateRequest(req);
  const { mode, ...rest } = req;
  const payload = { model: `sand-ai/magi-2/${mode}`, ...rest };

  const res = await fetch(`${BASE_URL}/api/v1/model/generateVideo`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload),
  });

  if (!res.ok) {
    throw new Error(`Submit failed (${res.status}): ${await res.text()}`);
  }
  const json = (await res.json()) as { data?: { id?: string }; id?: string };
  const id = json.data?.id ?? json.id;
  if (!id) throw new Error("Missing prediction request_id in upstream response.");
  return id;
}

export async function waitForMagi2Mp4(
  requestId: string,
  apiKey: string,
  maxWaitMs = 40 * 60_000,
): Promise<{ status: "completed"; mp4Url: string } | { status: "policy_filtered" | "failed"; reason: string }> {
  const deadline = Date.now() + maxWaitMs;
  await new Promise((r) => setTimeout(r, 60_000)); // 60s initial grace window

  while (Date.now() < deadline) {
    const res = await fetch(`${BASE_URL}/api/v1/model/prediction/${encodeURIComponent(requestId)}`, {
      headers: { Authorization: `Bearer ${apiKey}` },
    });

    if (res.ok) {
      const raw = (await res.json()) as { data?: { status?: string; outputs?: string[]; error?: string }; status?: string; outputs?: string[]; error?: string };
      const data = raw.data ?? raw;
      const st = (data.status ?? "").toLowerCase();

      if (st === "completed" || st === "succeeded") {
        const mp4Url = data.outputs?.[0];
        if (!mp4Url) return { status: "policy_filtered", reason: "Empty output array (PG-13 filtered; $0 charge)." };
        return { status: "completed", mp4Url };
      }
      if (st === "failed" || st === "canceled" || st === "cancelled") {
        const reason = data.error ?? "Upstream render failed";
        return {
          status: /policy|safety|nsfw|filter/i.test(reason) ? "policy_filtered" : "failed",
          reason,
        };
      }
    }
    await new Promise((r) => setTimeout(r, 25_000 + Math.floor(Math.random() * 4_000)));
  }
  throw new Error(`Timed out waiting for prediction ${requestId}`);
}

Python 3.11+ 비동기 작업 러너 (`httpx` + 자동 MP4 아카이빙)

Python 미디어 파이프라인, ComfyUI 사이드카 또는 AI 영상 에이전트를 위한 이 `httpx` 스크립트는 20슬롯 옴니 레퍼런스 렌더링을 제출하고, 지수 오류 백오프로 안전하게 폴링하며, PG-13 `policy_filtered` 종료를 깔끔하게 감지한 뒤 생성된 1080p @ 25fps MP4를 디스크에 직접 스트리밍 저장합니다.

magi2_runner.py — MP4 다운로드를 포함한 Python 프로덕션 스크립트
python
import os
import time
import random
import httpx

BASE_URL = "https://api.atlascloud.ai"
API_KEY = os.environ["ATLAS_API_KEY"]

def render_magi2_omni_ref(
    prompt: str,
    duration: int = 8,
    aspect_ratio: str = "9:16",
    images: list[str] | None = None,
    videos: list[str] | None = None,
    audios: list[str] | None = None,
    output_path: str = "magi2_output.mp4",
) -> str:
    assert 4 <= duration <= 30, "MAGI-2 duration must be integer 4..30"
    headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
    payload: dict = {
        "model": "sand-ai/magi-2/reference-to-video",
        "prompt": prompt,
        "duration": duration,
        "aspect_ratio": aspect_ratio,
    }
    if images:
        payload["images"] = images[:10]
    if videos:
        payload["videos"] = videos[:5]
    if audios:
        payload["audios"] = audios[:5]

    with httpx.Client(timeout=60.0) as client:
        submit = client.post(f"{BASE_URL}/api/v1/model/generateVideo", headers=headers, json=payload)
        submit.raise_for_status()
        body = submit.json()
        req_id = (body.get("data") or body)["id"]
        print(f"Submitted MAGI-2 job {req_id} (est. wholesale ${duration * 0.08:.2f})")

        time.sleep(60)  # Grace period before first poll
        deadline = time.time() + 40 * 60
        while time.time() < deadline:
            r = client.get(f"{BASE_URL}/api/v1/model/prediction/{req_id}", headers=headers)
            if r.status_code == 200:
                data = r.json().get("data") or r.json()
                status = (data.get("status") or "").lower()
                if status in ("completed", "succeeded"):
                    outputs = data.get("outputs") or []
                    if not outputs:
                        raise RuntimeError("policy_filtered: $0 upstream charge; revise PG-13 prompt.")
                    with client.stream("GET", outputs[0]) as dl:
                        dl.raise_for_status()
                        with open(output_path, "wb") as f:
                            for chunk in dl.iter_bytes():
                                f.write(chunk)
                    return output_path
                if status in ("failed", "canceled", "cancelled"):
                    raise RuntimeError(f"Job failed ($0 charge if filtered): {data.get('error')}")
            time.sleep(25 + random.uniform(0, 4))
    raise TimeoutError(f"Prediction {req_id} exceeded 40-minute wait window")

시작/끝 프레임 I2V 및 옴니 레퍼런스용 cURL 복사-붙여넣기 스니펫

터미널에서 빠르게 스모크 테스트를 실행할 수 있도록 아래 두 가지 cURL 명령어를 활용하세요. `image-to-video`에서는 출력 해상도와 비율이 시작 키프레임을 상속받기 때문에 의도적으로 `aspect_ratio`를 생략한다는 점을 기억하세요.

시작 및 종료 키프레임을 사용한 Image-to-Video (cURL)
bash
curl -sS -X POST "https://api.atlascloud.ai/api/v1/model/generateVideo" \
  -H "Authorization: Bearer $ATLAS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "sand-ai/magi-2/image-to-video",
    "image": "https://assets.magiai.ai/examples/espresso-start.webp",
    "last_image": "https://assets.magiai.ai/examples/espresso-pour-end.webp",
    "prompt": "Macro 100mm locked push-in as tiger-striped espresso crema flows into the stoneware demitasse. Audio: pump hum, steady espresso pour, ceramic resonance, no music.",
    "duration": 6
  }'
옴니 레퍼런스 20슬롯 멀티모달 렌더링 (cURL)
bash
curl -sS -X POST "https://api.atlascloud.ai/api/v1/model/generateVideo" \
  -H "Authorization: Bearer $ATLAS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "sand-ai/magi-2/reference-to-video",
    "prompt": "Using @image_1 wearing the linen shirt inside @image_3, holding @image_2 at collarbone height, match @audio_1 dry timbre and @video_1 slow handheld framing. [00:00-00:05] She says warmly: \"Three drops after cleansing keeps winter redness calm all day.\" Audio: clean room tone, no music.",
    "duration": 8,
    "aspect_ratio": "9:16",
    "images": [
      "https://assets.magiai.ai/examples/founder-portrait.webp",
      "https://assets.magiai.ai/examples/serum-bottle.webp",
      "https://assets.magiai.ai/examples/bathroom-vanity.webp"
    ],
    "videos": ["https://assets.magiai.ai/examples/handheld-framing-4s.mp4"],
    "audios": ["https://assets.magiai.ai/examples/founder-voice-5s.wav"]
  }'

관련 기술 문서

MAGI-2 코드 예제: TypeScript, Python, cURL