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 秒 Omni-Reference 前置驗證器、因應 7–26 分鐘佇列的 60 秒初始寬限期+25 秒抖動輪詢、`policy_filtered` 自動辨識處理,以及 MP4 檔案直接歸檔下載。

支援語言
TypeScript · Python · cURL
相依套件
原生 fetch / httpx / curl
前置檢查
秒數、參考素材與提示詞
驗證標準
Bearer Token HTTPS

TypeScript / Node.js 22+ 生產級用戶端(T2V、I2V 與 Omni-Ref)

這份零相依性的 TypeScript 模組可在 Node.js 22+、Bun、Cloudflare Workers(送單步驟)或背景任務執行器(BullMQ / Trigger.dev / Inngest)中穩定運行。程式會在發起網路連線前先強制檢查所有 2026-12-02 已驗證的 MAGI-2 限制條件,讓無效秒數或 31 秒影片參考組合在 1 毫秒內於本地直接報錯,避免浪費一次 HTTP 來回延遲。

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 旁掛程式(Sidecar)或 AI 影片代理程式,這支 `httpx` 腳本可送出 20 槽位 Omni-Reference 算圖請求、以安全且具退避機制的間隔進行輪詢、精準偵測 PG-13 `policy_filtered` 終止狀態,並將產出的 1080p @ 25fps MP4 直接串流寫入磁碟。

magi2_runner.py — Python 生產級腳本(含 MP4 下載)
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)與 Omni-Reference 的 cURL 速查範例

將這兩組 cURL 指令備妥,即可在終端機快速執行冒煙測試(Smoke Test)。請特別留意:`image-to-video` 刻意省略 `aspect_ratio` 欄位,因為輸出畫幅會直接繼承起始關鍵影格(Start Keyframe)的長寬比例。

具首尾關鍵影格的圖生影片(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
  }'
Omni-Reference 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