Models and Cost

Video generation API access tutorial: asynchronous tasks, polling and result acceptance

Explain clearly the task creation, status polling, timeout and idempotence, result download, quality evaluation and cost recording of the video generation API to avoid repeated tasks and unlimited waiting.

Updated on 2026-07-15Checked 2026-07-15Estimated reading time: 11 minutesFor text-to-video, image-to-video, and asynchronous media generation jobs
Configuration fields were checked against public documentation. Models, prices, and capabilities can change; verify current values in the console and live API responses.

Video generation is usually not an HTTP request waiting for the file to be returned, but an asynchronous process of "creating tasks, querying status, and downloading results." If you do not save task IDs, limit polling, and process idempotence when accessing, it is easy to charge fees repeatedly or generate duplicate videos.

Confirm the API form first

Confirm from the current model page and API documentation:

  1. Confirm whether the model supports text-to-video, image-to-video, or video editing.
  2. What input and upload methods are required to create a task.
  3. Whether to return the task ID.
  4. What endpoint to use for querying status and downloading results.
  5. Whether parameters such as duration, resolution, aspect ratio, and audio are supported.

ViewCurrent video models and prices. Do not apply request fields from other platforms to the current model by default.

Correct task state machine

The application handles at least these states:

created -> queued -> running -> succeeded
                         \-> failed
                         \-> cancelled
The client observation time exceeds the upper limit -> timed_out(Application side status)

The server task may still be running even if the client has timed out. Before re-creating the task, you should first query with the original task ID to avoid misjudgment of "query timeout" as "task does not exist".

Universal access skeleton

Endpoints and fields must be copied from the current API documentation. Only the application structure is shown below:

import time

CREATE_URL = "Create endpoint from task copied from document"
STATUS_URL_TEMPLATE = "Status query endpoint copied from document,Contains tasksIDplaceholder"

def create_video_task(payload):
    response = authenticated_post(CREATE_URL, payload, timeout=30)
    return response["task_id"]

def wait_for_video(task_id, max_wait_seconds=600):
    deadline = time.monotonic() + max_wait_seconds
    interval = 3

    while time.monotonic() < deadline:
        result = authenticated_get(
            STATUS_URL_TEMPLATE.replace("{task_id}", task_id),
            timeout=20,
        )
        if result["status"] == "succeeded":
            return result
        if result["status"] in {"failed", "cancelled"}:
            raise RuntimeError(result)
        time.sleep(interval)
        interval = min(interval + 2, 15)

    raise TimeoutError(f"task {task_id} is still not finished")

authenticated_post and authenticated_get Represents your own HTTP wrapper. The example does not assume that the current video API of AIFast must be used task_id or these status names, which should be mapped to real responses.

Idempotent and repeating tasks

Generate each business task its own unique ID and save it:

  • Business task ID.
  • Upstream task ID.
  • Request model and key parameters.
  • Creation time and last query time.
  • Current status and result address.
  • Number of attempts.

When the user refreshes the page or the queue consumer restarts, first query the existing tasks instead of directly creating them again. Only when the current API clearly supports idempotent keys, the business ID will be put into the corresponding request header or field.

Don’t write polling like this

The following practices increase failures and costs:

  • Infinite polling per second.
  • Retry immediately when encountering all 4xx and 5xx.
  • Create a new task directly after the client times out.
  • Do not save the task ID, just place the task in memory.
  • As a result, the download fails and the video is regenerated.

It is recommended to distinguish between creation timeout, status query timeout, task failure and result download failure. Download failures usually only require retrying the download, not regeneration.

How to check video quality

Fixed prompt words, reference images and supported parameters, respectively checked:

Dimensions Recording method
Instruction completed Whether subjects, actions, shots and scenes appear
time consistency Whether characters, clothing, and objects are stable in consecutive frames
movement quality Whether the movements are natural, whether there are jumps or mold-breaking
Picture quality Clarity, compression, flickering and watermark conditions
task performance Queue time, build time, failure rate, and download time
full cost Total cost of successful tasks, failed tasks, and repeated tasks

Verify composition and movement with shorter duration and lower-cost configurations before increasing formal output specifications. Don’t just compare one successful sample.

Result storage and expiration

If the temporary download address is returned:

  1. Immediately download to your own object storage after successful generation.
  2. Check status code,Content-Type, file size and video duration.
  3. Save the upstream task ID and its own storage address.
  4. If the download fails, the download will only be retried, and an alarm will be issued when the upper limit is reached.

Do not send temporary URLs directly to long-term users, and do not save the full download address including signature parameters in the logs.

Common mistakes

Created successfully but kept queued

Log the model, task ID, creation time, and query response. Check model maintenance, queue status, account quota and concurrency limits, and do not continue to increase the polling frequency.

Status query returns 404

Confirm whether the task ID, status endpoint and account are consistent. Some task query paths and creation paths are not under the same prefix and cannot be spliced ​​together by themselves.

Image-to-video input failed

Check image format, size, accessibility and upload method. External image URLs may be unable to be read by the server due to hotlink protection, expiration, or access rights.

Video generated successfully but download failed

Think of generation and download as two stages. Save the original task ID, re-obtain or retry the result address, and do not re-create the generation task immediately.

Check before going online

  • Task creation, query, and results endpoints all come from the current document.
  • The business task ID and the upstream task ID are persisted.
  • There are caps on the polling interval, total wait time, and number of retries.
  • Query timeout will not automatically re-create the task.
  • Temporary results will be dumped and verified in the file.
  • The fixed question set covers action, characters and shot failure cases.
  • Cost statistics include failed and repeated tasks.

Continue readingLLM API Cost EstimationandProduction on-line checklist, incorporating media tasks into queues, alerts, and budget protection.

Source checked

Reference and Check Sources

Next step

Check the model and price first, then create an independent test Key

The model ID, open status and price will change; it will be added to production after passing small-scale verification.

Model PricingCreate Account View API documentation