Notice: Black Friday 2026 × Cyber Monday: Get up to 30% extra on top-ups, DeepSeek free to use · View the promotion
Blog

Tutorial

How to Call ltx-2.5-pro Image-to-Video via the HiAPI API (curl + Python)

A working request flow: first-frame upload, task submission, async polling, and video download

Nov 25, 2026 10 min read
简洁的层叠纸张封面图:米色底上多张薄纸逐层后退,石墨色纸边,其中一张为陶土红色。
On this page

What the image-to-video endpoint expects from you

Before writing any code, it helps to understand the shape of the contract. ltx-2.5-pro/image-to-video does not stream frames back to you while you wait. It is an async, task-based endpoint: you send one request that describes the job, the API acknowledges it with a task identifier, and the work happens on the server side over seconds or minutes depending on the clip you asked for. Your job as an integrator is therefore threefold: submit a well-formed job, observe its state until it reaches a terminal one, and collect the output.

The second structural fact is that this is first-frame-driven image-to-video. The image you provide is the starting frame; the model generates motion forward from it. That has real consequences for request design. The first frame is not decorative context — it anchors composition, subject identity, and lighting, so any defect in that image (wrong aspect ratio, motion-blurred subject, distracting text) propagates into every generated frame. Validation of the input image belongs on your side of the wire, before submission.

Because the call is asynchronous, you should also design around the assumption that wall-clock latency is variable. A request that returns a task ID quickly says nothing about how fast the render completes. Any caller that treats "submitted" as "nearly done" will waste requests polling too early. Plan for a task lifecycle with at least three observable conditions: accepted and in progress, finished successfully, and failed. The submission parameters describe what to generate; polling describes when it is done. Keeping those two concerns separate in your code is the single biggest favor you can do for your future self.

Finally, treat the endpoint as parameterized generation, not a magic filter. The first frame plus your parameters are the entire specification of the output. If a result surprises you, the fix is almost always in the request, not in a retry of the same request.

Build a working curl request

The fastest way to prove your understanding is a raw HTTP submission. The exact field names and the base URL come from the model's reference page; the layout below is the canonical request shape for ltx-2.5-pro/image-to-video — a first-frame image plus generation parameters, sent as a JSON body with your API credentials in the header. Check the model page for the authoritative field list before you ship.

curl -X POST "https://api.hiapi.ai/v1/tasks" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ltx-2.5-pro/image-to-video",
    "input": {
      "first_frame_image": "https://your-cdn.example.com/frames/scene_001.png",
      "prompt": "Slow push-in on the subject, gentle breeze in the hair, natural light",
      "duration": 5
    }
  }'

Walk through the body from the outside in. model selects the endpoint; keep it explicit in every request rather than defaulting, so logs are self-describing. input is a nested object that carries everything the generation needs. first_frame_image points at your starting frame — pass a stable, publicly fetchable URL (or a supported inline encoding, if the reference permits it) rather than a link that expires mid-render, or the job may fail before it begins. prompt describes motion and camera behavior; since the first frame already fixes appearance, this is where you say what changes. duration is expressed in seconds and is the parameter with the most direct effect on render time and on how the job is billed, so it deserves to be a deliberate constant in your code, not a hardcoded afterthought.

The response is small and pragmatic: you get back a task identifier and an initial status. Save that identifier immediately — it is the only handle you will have on the job, and losing it means losing the output. Nothing about the video itself is in this response.

If you prefer exploring interactively before writing a service, the model page for ltx-2.5-pro/image-to-video is the right place to confirm current parameters and try a submission.

The same request in Python

The curl call maps one-to-one onto a small Python client. Keep it deliberately dumb — submission only, no hidden polling, no retry magic — so the transport layer stays easy to reason about.

import os
import requests

BASE_URL = "https://api.hiapi.ai/v1"

def submit_video_job(first_frame_url: str, prompt: str, duration: int = 5) -> str:
    payload = {
        "model": "ltx-2.5-pro/image-to-video",
        "input": {
            "first_frame_image": first_frame_url,
            "prompt": prompt,
            "duration": duration,
        },
    }
    resp = requests.post(
        f"{BASE_URL}/tasks",
        headers={
            "Authorization": f"Bearer {os.environ['HIAPI_API_KEY']}",
            "Content-Type": "application/json",
        },
        json=payload,
        timeout=30,
    )
    resp.raise_for_status()
    body = resp.json()
    task_id = body.get("id") or body.get("task_id")
    if not task_id:
        raise RuntimeError(f"No task id in response: {body}")
    return task_id

Three habits are worth building in from day one. First, the API key comes from the environment, never from source. Second, the timeout on the POST bounds only the submission round-trip — a hung submission should fail fast, while the render itself is covered by polling. Third, the task ID extraction tolerates the common naming variants and raises loudly on a malformed response, because a silent None propagating into your polling loop produces a confusing failure much further from its cause. If you are wiring this into a larger service, log the full submission body (minus credentials) alongside the returned task ID; when someone asks why a clip looks wrong, what they actually want to see is the exact prompt and frame that produced it.

Poll the task until the video is ready

Polling is where most integrations acquire their bad habits. The rules are simple: poll on a backoff, cap the total wait, and classify every status you see into one of three buckets — in progress, succeeded, failed.

import time

def wait_for_video(task_id: str, max_wait: int = 600) -> dict:
    deadline = time.monotonic() + max_wait
    delay = 2.0
    while time.monotonic() < deadline:
        resp = requests.get(
            f"{BASE_URL}/tasks/{task_id}",
            headers={"Authorization": f"Bearer {os.environ['HIAPI_API_KEY']}"},
            timeout=15,
        )
        resp.raise_for_status()
        task = resp.json()
        status = (task.get("status") or "").lower()

        if status in {"succeeded", "completed", "success", "done"}:
            return task
        if status in {"failed", "error", "cancelled", "canceled"}:
            raise RuntimeError(f"Task {task_id} failed: {task}")

        time.sleep(delay)
        delay = min(delay * 1.5, 15.0)
    raise TimeoutError(f"Task {task_id} not finished after {max_wait}s")

Why a backoff instead of a fixed short interval? Because the render will take at least several seconds, and hitting the status endpoint every 200 ms buys you nothing but load. Start around a couple of seconds and grow the gap toward a ceiling of roughly ten to fifteen seconds. The max_wait deadline is the important part: it turns "forever" into a bounded, debuggable failure. Choose it against your slowest realistic render, not your average one, and use the model's duration parameter as your guide.

Treat anything you don't explicitly recognize as "still running" — but log it. New or unexpected status strings are a signal that the API surface has moved, and a log line is cheaper than a mystery. On a failed task, capture the task body verbatim; the error reason is your only chance to fix the request rather than blindly resubmitting it.

Download and persist the generated video

The completed task carries the output reference — typically a URL rather than raw bytes. Download it promptly and move it into your own storage: signed or time-limited output URLs are a poor fit for archival, and you do not want a database row pointing at something that has since expired.

def download_video(task: dict, dest_path: str) -> str:
    outputs = task.get("output") or task.get("outputs") or {}
    url = outputs.get("video_url") or outputs.get("url")
    if not url:
        raise RuntimeError(f"No video URL in task output: {task}")

    with requests.get(url, stream=True, timeout=120) as r:
        r.raise_for_status()
        with open(dest_path, "wb") as f:
            for chunk in r.iter_content(chunk_size=1 << 20):
                f.write(chunk)
    return dest_path

Stream the download rather than buffering it whole, and verify the file size against any Content-Length the server reports. Write to a temporary filename and rename on success, so a crashed transfer never leaves a half-video that later looks legitimate. Alongside the file, persist a small metadata record: the task ID, the submitted prompt and first-frame URL, duration, the terminal status, and the completion timestamp. That record is what makes a future "why does clip #4821 look like that?" question answerable in minutes instead of hours, and it is also the anchor you need for cost accounting.

Error handling and production guardrails

Harden the integration by separating failure kinds, because they demand different responses.

Validation failures (your bug). Before submitting, check that the first frame is actually fetchable, that its aspect ratio is sane for the target output, and that the prompt is present and within length limits. These should never consume a retry — retrying a bad image produces the same rejection, just later. Validate locally and surface the error to whoever submitted it.

Transient failures (retry with limits). Network timeouts, connection resets, and server-side 5xx responses fall here. Retry with exponential backoff and jitter, but cap the attempt count — three is a reasonable default — and never retry the download and the submission with the same policy, since their cost profiles differ entirely.

Permanent failures (stop and report). A rejected payload, an unsupported parameter, or a task that reaches a failed terminal state will not fix itself. Log the full response, mark the job failed in your own system, and alert a human rather than looping.

Beyond retries, three guardrails carry most of the weight. Bound every wait — submission timeout, polling deadline, download timeout, all explicit. Centralize the task state machine in one module so status handling cannot drift between code paths. And control cost at the request level: how the job is billed follows from your parameters, so fix duration deliberately, avoid resubmitting identical jobs on ambiguous errors, and stamp every task with a caller identifier so the expensive ones are traceable. A deduplication check on (first_frame_url, prompt, duration) in your own database will save more money than any client-side optimization.

Where to go next

You now have the full loop: validate a first frame, submit the job, poll to a terminal state on a backoff, and store the result with enough metadata to explain it later. The natural next step is parameter tuning — experiment with prompt phrasing and duration on the ltx-2.5-pro/image-to-video model page to learn how each dial moves the output, then lock your findings into defaults. From there, batching and queue-level cost control are straightforward extensions of the state machine you already have.

Related articles

View all articles →

Start building with persistent AI artifacts

Get your API key and call image, video and audio models through one task-based API.

Read the API docs