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 Use ltx-2.5-fast Audio-to-Video via the HiAPI API: curl and Python

A working request walkthrough: auth, audio upload, job polling, and cost planning

Nov 25, 2026 14 min read
用层叠薄纸片构成的抽象封面图,米色底上有石墨色与赤陶色纸层。
On this page

What the audio-to-video job actually does

An audio-to-video call on HiAPI is not a single blocking HTTP request. It is a small pipeline with four observable stages, and the shape of that pipeline is what determines how you write the client.

Stage one is authentication. Every request carries your API key in a header, and the gateway uses it to route the call and attribute usage.

Stage two is input submission. You send the audio asset that should drive the video, together with the model identifier ltx-2.5-fast/audio-to-video and any generation parameters you want to set. The platform takes the audio, queues generation, and hands you back a job handle rather than a rendered file. Video generation takes long enough that synchronous responses would be impractical, so the API is asynchronous by design.

Stage three is polling. You take the job identifier from the submission response and ask the platform whether the job has finished. A job moves through states — accepted, running, then either succeeded or failed. Because generation time varies with audio length and output settings, you cannot assume a fixed wait; you check, back off, and check again.

Stage four is retrieval. When the job reports success, the response contains a reference to the finished video, which you download and store wherever your application expects media to live.

The practical consequence: your integration has two distinct pieces of code — a submitter and a poller — and you should treat them as separate concerns. The submitter should be fast and idempotent-ish; the poller should be patient, bounded, and loud when it gives up. Everything in the following sections follows from that split.

There is one more thing worth internalising before you write a line: this is an audio-conditioned video model, so the audio is not decoration. It is the primary conditioning signal. That means your audio upload path is a real part of the system, not an afterthought, and it deserves its own validation step.

Prerequisites and API authentication

You need three things before the first request can succeed: an API key from your HiAPI account, the platform base URL, and a clear idea of how the key travels on each call.

The base URL is the same host for every endpoint you will call in this walkthrough. Keep it in an environment variable rather than pasting it into scripts, so that moving between environments is a one-line change:

export HIAPI_BASE_URL="https://api.hiapi.ai"
export HIAPI_API_KEY="your-api-key-here"

Authentication is a bearer token in the Authorization header. Two headers appear on essentially every request: Authorization and Content-Type. The content type differs between the upload step (multipart) and the JSON steps (application/json), which is a common source of avoidable 400s.

Verify the key works before you debug anything else. A minimal call that lists or describes the model will fail loudly and quickly if the key is wrong, the base URL is malformed, or a proxy is rewriting headers. Distinguishing an auth failure from a request-shape failure early saves a lot of guesswork later.

Two hygiene rules that pay off:

  • Never commit keys. Read them from the environment or a secrets manager in both your shell and your Python code.
  • Use a separate key per environment. When a key leaks or a quota is exhausted, you want the blast radius to be one environment, not all of them.

Confirm the current header conventions and the exact endpoint paths against the platform documentation rather than against a blog post — including this one. Paths and parameter names are versioned, and the docs are the authority.

Uploading the audio input

The audio file has to reach the platform before generation can be queued. Depending on how the current API surface exposes inputs, you will either upload the asset in a separate call and receive an identifier to reference, or attach it directly in the generation request. Both patterns are common; check the model page for which one applies to ltx-2.5-fast/audio-to-video at the time you build.

If you upload separately, the multipart step looks like this:

curl -sS -X POST "$HIAPI_BASE_URL/v1/files" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -F "file=@./narration.wav" \
  -F "purpose=audio_input"

The response gives you an asset reference — an ID or URL field. Capture it; that string is what the generation request will point at. Do not re-upload the same file on every retry of the generation call, or you will accumulate orphaned assets.

If the audio is attached inline instead, the generation request itself becomes multipart, and the same file field appears alongside your JSON parameters. The validation advice is identical either way.

What to check so the upload is not the failure point:

  • Container and codec. Prefer a widely supported container such as WAV or MP3 and confirm the model page lists yours. An unsupported codec usually surfaces as a 4xx at upload time — catch it there, not at generation time.
  • Size limits. Large files fail for boring reasons. Enforce a client-side cap and reject early with a clear message.
  • Duration. Very long audio means very long jobs. Decide your maximum acceptable duration before you accept uploads from users.
  • Channel and sample rate. Downmix or resample on your side if your pipeline can produce exotic formats; it is cheaper than debugging a server-side rejection.
  • Filenames. Sanitise them. Spaces and unicode in filenames cause surprises in shell examples that do not appear in Python clients.

Log the asset reference alongside your own job intent so that a failed generation can be replayed without re-uploading.

A working curl request

This is the full submitter, from a cold shell to a queued job. It assumes the environment variables from earlier and an asset reference from the upload step.

#!/usr/bin/env bash
set -euo pipefail

: "${HIAPI_BASE_URL:?set HIAPI_BASE_URL}"
: "${HIAPI_API_KEY:?set HIAPI_API_KEY}"
: "${AUDIO_ASSET_ID:?set AUDIO_ASSET_ID}"

response=$(curl -sS -X POST "$HIAPI_BASE_URL/v1/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d @- <<JSON
{
  "model": "ltx-2.5-fast/audio-to-video",
  "input": {
    "audio": "$AUDIO_ASSET_ID"
  }
}
JSON
)

echo "$response"

A few deliberate choices in that snippet:

set -euo pipefail makes a failed curl or an unset variable abort immediately. Silent fallbacks are how you end up with an empty "audio" field and a confusing server error.

The heredoc with -d @- keeps the JSON readable and lets you substitute variables without a templating library. If your asset reference is a URL rather than an ID, the same structure applies.

The model identifier appears verbatim as ltx-2.5-fast/audio-to-video. Treat it as a constant, not something you assemble from parts.

The response is echoed rather than parsed, because the first thing you want is to see the raw shape. Once you have seen it, extract the job identifier with jq:

job_id=$(echo "$response" | jq -r '.id')

Generation parameters beyond the audio input — resolution, frame rate, any style controls the model accepts — belong in the same JSON object. Add them once you have confirmed the minimal request works; changing one thing at a time is the fastest route to a working call. Check the model reference for the parameters that ltx-2.5-fast/audio-to-video currently accepts.

The same request in Python

The Python version is the same request shape with better ergonomics. Use requests and a session, so that connection pooling and default headers are handled once.

import os
import requests

BASE_URL = os.environ["HIAPI_BASE_URL"]
API_KEY = os.environ["HIAPI_API_KEY"]
MODEL = "ltx-2.5-fast/audio-to-video"


def submit_audio_to_video(audio_ref: str, **params) -> str:
    """Submit an audio-to-video job and return the job id."""
    payload = {"model": MODEL, "input": {"audio": audio_ref}}
    payload["input"].update(params)

    response = requests.post(
        f"{BASE_URL}/v1/generations",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json=payload,
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["id"]


if __name__ == "__main__":
    job_id = submit_audio_to_video(
        os.environ["AUDIO_ASSET_ID"],
    )
    print(job_id)

Point by point against the curl version: the URL is constructed the same way, the Authorization and Content-Type headers are identical, the JSON body is the same object, and the job identifier comes out of the same field.

The timeout=30 is not optional decoration. Without it, a stalled connection hangs forever, and your worker silently stops making progress. Thirty seconds is generous for a submission call; it is not a generation timeout, because submission returns immediately.

raise_for_status() converts 4xx and 5xx responses into exceptions. That is the behaviour you want — swallowing them and parsing for a job ID that will never exist is the most common way this integration goes wrong.

The **params escape hatch lets you add generation parameters without changing the signature. Keep the call sites explicit about what they pass:

job_id = submit_audio_to_video(asset_id, resolution="1080p")

If your upload step is multipart, mirror it with requests.post(..., files={"file": open(path, "rb")}) — same endpoint, same header, different body encoding. For the model's accepted parameters and current pricing model, see the ltx-2.5-fast/audio-to-video model page.

Polling the job and retrieving the result

Generation is asynchronous, so you need a poll loop with three properties: it waits, it backs off, and it terminates.

import time
import requests

TERMINAL = {"succeeded", "failed", "cancelled"}


def wait_for_job(job_id: str, *, interval: float = 2.0,
                 max_interval: float = 30.0,
                 deadline: float = 900.0,
                 session: requests.Session | None = None) -> dict:
    sess = session or requests.Session()
    start = time.monotonic()
    delay = interval

    while True:
        if time.monotonic() - start > deadline:
            raise TimeoutError(f"job {job_id} exceeded {deadline}s")

        r = sess.get(
            f"{BASE_URL}/v1/generations/{job_id}",
            headers={"Authorization": f"Bearer {API_KEY}"},
            timeout=30,
        )
        if r.status_code >= 500:
            time.sleep(delay)
            delay = min(delay * 2, max_interval)
            continue
        r.raise_for_status()

        body = r.json()
        status = body.get("status")

        if status in TERMINAL:
            if status != "succeeded":
                raise RuntimeError(f"job {job_id} ended as {status}: {body}")
            return body

        time.sleep(delay)
        delay = min(delay * 2, max_interval)

The backoff starts at two seconds and doubles up to a ceiling. Polling every 200ms against a job that takes minutes is wasted requests and wasted rate-limit budget; a two-second floor with growth is a reasonable default. The deadline matters more than the interval: it is the difference between a job that eventually errors and a worker that hangs until your orchestrator kills it.

The >= 500 retry branch is deliberate. Transient gateway or backend errors during polling are not the job's fault, and re-checking after a backoff is correct. A 4xx on the poll endpoint means something structural — a bad job ID, a revoked key — and retrying will not fix it.

On success, the job body carries the output reference. Download it and store it in your own bucket or filesystem; the platform's URL is not your permanent archive.

def download_output(body: dict, dest: str) -> None:
    url = body["output"]["video_url"]
    with requests.get(url, stream=True, timeout=60) as r:
        r.raise_for_status()
        with open(dest, "wb") as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)

Field names in the job body are the one thing most likely to drift between API versions. Log the full body on the first few jobs so that a rename is obvious rather than mysterious.

Handling errors and timeouts

Most production incidents with async video APIs come from a small set of failures. Handle each explicitly.

Unsupported or oversized audio. Caught at upload or submit time as a 4xx. Validate on your side first — container, size, duration — and return a user-facing message rather than a stack trace.

Authentication and authorisation failures. A 401 means the key is missing or invalid; a 403 means the key is valid but not permitted for this action. Do not retry either. Alert, and fail fast.

Rate limiting. A 429 means back off. Respect any retry-after information the response provides; otherwise use exponential backoff with jitter. A client that hammers through a 429 will keep getting 429s.

Malformed generation parameters. Unknown fields, wrong types, or out-of-range values return 4xx from the submit call. Because you are passing **params through a wrapper, validate them at the boundary of your own code so that a typo surfaces before a round trip.

Long jobs and deadline expiry. A job that runs past your deadline should raise, not spin. Record the job ID when you raise, so you can look it up manually and decide whether to extend the deadline or abandon the job.

Terminal failure states. A job that ends as failed or cancelled is not retryable in the same loop. Log the full body, surface a clear error, and decide at the application level whether a retry is appropriate — and if so, submit a new job rather than re-polling a dead one.

Network-level errors on download. The output URL is a separate fetch. Apply its own timeout and retry with backoff; a completed job is not lost because a download came back with a 502.

Two cross-cutting rules. First, log the job ID at every stage — submit, each poll transition, download — so that one identifier traces a request through your logs. Second, give the whole operation one idempotency key of your own making, so that a retried submit does not silently create two videos from one audio file.

Planning cost before you scale

Cost per job is not a single number, and the useful discipline is understanding what drives it rather than memorising a figure. Real-time prices live in the platform's pricing panel, and they change; treat anything numeric in a blog post, including this one, as stale.

The factors that move cost per job:

  • Output duration. Audio length sets the floor on how much video is generated. Longer narration means more output, and output is typically the dominant unit.
  • Output resolution and frame rate. Higher settings mean more generated frames. The multiplier compounds: doubling both resolution and frame rate is not a modest increase.
  • Model choice. A fast variant such as ltx-2.5-fast/audio-to-video is priced differently from slower, heavier models. Speed and quality are the trade-off, and the pricing panel is where that trade-off is expressed.
  • Retries. A failed job that you resubmit, or an upload you repeat unnecessarily, is cost with nothing to show for it. This is why input validation and idempotency keys are cost controls, not just hygiene.
  • Polling load. Polling does not generate video, but it does consume request budget. Sensible backoff — as in the loop above — keeps this negligible.

The measurement approach that actually answers the question for your workload: take a small batch of representative audio files, run them through the full pipeline, and record the observed cost per job alongside duration and settings. Do this before you promise anything to a stakeholder. A batch of five to ten files with your real distribution of durations will tell you more than any published rate.

Then model the edges, not the average. Your cheapest job and your most expensive job are both real. Budget against the worst realistic case, and put a per-user cap in front of the submitter so that one pathological input cannot run up a bill.

Finally, re-check before committing to volume. Prices, model names, and accepted parameters are all versioned. The model page and the current pricing panel are the sources to trust at the moment you make a capacity decision.

That is the whole pipeline: authenticate, upload, submit, poll with backoff, download, and measure before you scale. Build the submitter and the poller as separate units and the rest follows cleanly.

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