API protocol

Kling 4.0: parameters, scenarios and API guide

Preview guide

Paste into an AI assistant to help with integration. Documentation and examples only; no real credentials.

Preview guide

Kling 4.0: parameters, scenarios and API guide

Direct answercontents is an array with a prompt item carrying text; settings configures output. Simple prompt/seconds/size is also supported.

Updated · Reviewed

Purpose and workflows

The standard model composes shots from text, frame images and image/video references. Create a custom voice before referencing voice_id. Flash uses a different voice contract.

This guide checks the site request contract; it does not claim paid generation acceptance for every scenario. Use the exact model, group and available endpoint shown in the marketplace. Replace example.com media and placeholder task IDs. Confirm a minimal request before adding references and advanced parameters. Consult marketplace pricing and actual billing for charges.

Models and endpoints

kling-4.0

POST /v1/videos

Reference media formats

MediaFieldsEncoding and transportPreparation and limits
Images / framescontents[].url (first_frame / middle_frame / last_frame / refer_image)HTTP(S) image URL; raw PNG/JPEG Base64 or data:image/png;base64,... / data:image/jpeg;base64,... URI.Inline images at most 30 MiB decoded; prefer PNG/JPEG. JSON cannot contain disk paths; multiple references need unique ids.
Reference / edit videocontents[].url (feature_video / base_video)HTTP(S) video URLs only; no raw Base64 or video data URI.Prefer MP4 (H.264). feature_video is a reference; base_video is the edit source. At most 5 videos and one base_video.
Reference audioPOST /v1/general/custom-voices: voice_url 或 fileCreate a voice first: JSON voice_url uses an HTTP(S) MP3/WAV/MP4/MOV URL; local uploads use multipart file. Never put an audio URL/Base64 in voice_id.Local upload requires 5–30 seconds of PCM WAV, at most 15 MiB. Both sites returned 404 in testing; this workflow needs the endpoint enabled and is not accepted live.
Voice IDcontents[].voice_id + idOnly a voice_id returned by successful site voice creation; reference @id in the prompt.A creation task_id is not a voice_id. Standard supports at most 3 voice references; no direct reference-audio content item.

Parameters and combinations

  • contents is an array with a prompt item carrying text; settings configures output. Simple prompt/seconds/size is also supported.
  • first_frame/middle_frame/last_frame control frames; refer_image is an image reference, feature_video a video reference, base_video the video to edit.
  • At most 10 images, 5 videos, one base_video and 3 voices, with 15 total materials. Multiple reference images/middle frames need unique ids.
  • voice_id is not an audio URL. Create through POST /v1/general/custom-voices and poll GET the same path/{task_id}. On success use voice_id plus a local reference id. The site must have enabled this new endpoint.
  • id=voice_1 corresponds to @voice_1 in the prompt. Voice listing/deletion are not exposed; refer_audio/audio/reference_audio content types are not supported.
  • Do not mix an input envelope with flat contents/settings, or prompt with contents. Media format, duration and content acceptance still require a successful task result.
  • 2026-11-15 business-site checks: three-second frame and base_video edit tasks completed and decoded; the edited background color changed. This does not validate middle frames, feature_video, voices or other sites. Both sites returned 404 for POST /v1/general/custom-voices; local WAV creation, voice_id retrieval and voice generation remain unverified live.
FieldTypeUse and constraints
Authorizationheader stringRequired: Bearer <site API key>, with Content-Type: application/json.
modelstringRequired: kling-4.0. Do not apply this contract to Flash or older models.
promptstringSite text shortcut; mutually exclusive with contents, mapped to a prompt content item.
contentsobject[]Must contain a prompt item. Text/media array; up to 15 assets, ≤10 images, ≤5 videos, ≤7 elements and ≤3 voices. Video elements also consume the video quota.
contents[].typestringRequired: prompt/first_frame/middle_frame/last_frame/refer_image/feature_video/base_video/element/voice. middle_frame and base_video require a compatible site route; not all routes accept them.
contents[].textstringRequired for prompt items. Site limits: 26,000 English or 11,000 non-English characters, proportionally combined. Reference assets using @id.
contents[].urlstringFor frame/image/video items. Images accept HTTP(S) or route-supported Base64; videos use HTTP(S). Do not replace voice/element resource IDs with media URLs. Official images: JPG/JPEG/PNG, ≤30 MB, dimensions ≥300px, ratio 0.4–2.5. Official videos: MP4/MOV, ≤300 MB, individual and total duration 3–30s, 24–60fps; totals include video elements.
contents[].idstringNon-empty unique prompt reference name. Name multiple middle frames/reference images individually; required for voice/element.
contents[].element_idstringRequired for element. Use an accessible site element ID after successful creation; distinct from the prompt reference id.
contents[].voice_idstringRequired for voice: a successfully created site voice ID, not an audio URL. See the voice guide for creation and known availability limits.
settings.durationinteger3–30 seconds; the site explicitly sends 10 when omitted, rather than inferring duration from text.
settings.audiostringOptional native (default, generated audio) or original (input-video audio). original requires base_video or feature_video and excludes voice references; base_video takes priority, otherwise the first feature_video is used. Validation and forwarding are supported; audio output still requires generation acceptance.
settings.resolutionstring720p/1080p; site default 1080p. Consumer-product 4K claims do not establish a site API enum.
settings.aspect_ratiostringSupports adaptive/16:9/9:16/1:1/21:9/4:3/3:4; adaptive requires a compatible reference mode. Must agree with size when both are provided.
options.watermark_info.enabledbooleanOptional watermark toggle, also accepted as top-level watermark. Avoid conflicting values; false is preserved. Official default false; custom watermarks are unsupported.
options.external_task_idstringOptional business correlation ID; does not guarantee idempotent creation. Officially unique per account; does not replace the system task ID.
options.callback_urlstringOptional HTTP(S) callback; compatible routes may move it to top-level callback_url. Keep polling and do not assume callback IDs are site IDs.
seconds / size / watermarksite aliasesAliases for duration, resolution+aspect_ratio and watermark. Conflicts with nested settings fail; prefer nested fields.

Scenarios and code examples

Text to video

Applies to: kling-4.0

POST /v1/videos

{
  "model": "kling-4.0",
  "prompt": "一位旅行者在海边散步,镜头平稳跟拍。",
  "seconds": "8",
  "size": "1280x720",
  "watermark": false
}

curl

curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 120 --request POST 'https://api.tu-zi.com/v1/videos' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-4.0",
  "prompt": "一位旅行者在海边散步,镜头平稳跟拍。",
  "seconds": "8",
  "size": "1280x720",
  "watermark": false
}'

python

import json
import os
import requests

url = "https://api.tu-zi.com/v1/videos"
headers = json.loads("{\"Authorization\":\"Bearer YOUR_API_KEY\",\"Content-Type\":\"application/json\"}")
for name in ["API_KEY"]:
    if not os.environ.get(name, "").strip():
        raise RuntimeError("Set environment variable: " + name)
headers["Authorization"] = "Bearer " + os.environ["API_KEY"]
payload = json.loads("{\"model\":\"kling-4.0\",\"prompt\":\"一位旅行者在海边散步,镜头平稳跟拍。\",\"seconds\":\"8\",\"size\":\"1280x720\",\"watermark\":false}")
response = requests.request("POST", url, headers=headers, json=payload, timeout=120)
response.raise_for_status()
result = response.json()
if isinstance(result, dict) and (result.get("success") is False or result.get("code") is False or result.get("error")):
    raise RuntimeError(json.dumps(result, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False, indent=2))

javascript

// Node.js 20+
const url = "https://api.tu-zi.com/v1/videos";
const headers = {
  "Authorization": "Bearer YOUR_API_KEY",
  "Content-Type": "application/json"
};
for (const name of ["API_KEY"]) {
  if (!process.env[name]?.trim()) throw new Error("Set environment variable: " + name);
}
headers.Authorization = 'Bearer ' + process.env.API_KEY;
const response = await fetch(url, { method: "POST", headers, body: JSON.stringify({
  "model": "kling-4.0",
  "prompt": "一位旅行者在海边散步,镜头平稳跟拍。",
  "seconds": "8",
  "size": "1280x720",
  "watermark": false
}), signal: AbortSignal.timeout(120000) });
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
if (result?.success === false || result?.code === false || result?.error) throw new Error(JSON.stringify(result));
console.log(JSON.stringify(result, null, 2));

Frame control

Applies to: kling-4.0

POST /v1/videos

{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "从首帧平稳过渡到 @middle 再到尾帧。"
    },
    {
      "type": "first_frame",
      "url": "https://example.com/subject.png"
    },
    {
      "type": "middle_frame",
      "url": "https://example.com/middle.png",
      "id": "middle"
    },
    {
      "type": "last_frame",
      "url": "https://example.com/end.png"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}

curl

curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 120 --request POST 'https://api.tu-zi.com/v1/videos' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "从首帧平稳过渡到 @middle 再到尾帧。"
    },
    {
      "type": "first_frame",
      "url": "https://example.com/subject.png"
    },
    {
      "type": "middle_frame",
      "url": "https://example.com/middle.png",
      "id": "middle"
    },
    {
      "type": "last_frame",
      "url": "https://example.com/end.png"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}'

python

import json
import os
import requests

url = "https://api.tu-zi.com/v1/videos"
headers = json.loads("{\"Authorization\":\"Bearer YOUR_API_KEY\",\"Content-Type\":\"application/json\"}")
for name in ["API_KEY"]:
    if not os.environ.get(name, "").strip():
        raise RuntimeError("Set environment variable: " + name)
headers["Authorization"] = "Bearer " + os.environ["API_KEY"]
payload = json.loads("{\"model\":\"kling-4.0\",\"contents\":[{\"type\":\"prompt\",\"text\":\"从首帧平稳过渡到 @middle 再到尾帧。\"},{\"type\":\"first_frame\",\"url\":\"https://example.com/subject.png\"},{\"type\":\"middle_frame\",\"url\":\"https://example.com/middle.png\",\"id\":\"middle\"},{\"type\":\"last_frame\",\"url\":\"https://example.com/end.png\"}],\"settings\":{\"duration\":8,\"resolution\":\"720p\",\"aspect_ratio\":\"16:9\"}}")
response = requests.request("POST", url, headers=headers, json=payload, timeout=120)
response.raise_for_status()
result = response.json()
if isinstance(result, dict) and (result.get("success") is False or result.get("code") is False or result.get("error")):
    raise RuntimeError(json.dumps(result, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False, indent=2))

javascript

// Node.js 20+
const url = "https://api.tu-zi.com/v1/videos";
const headers = {
  "Authorization": "Bearer YOUR_API_KEY",
  "Content-Type": "application/json"
};
for (const name of ["API_KEY"]) {
  if (!process.env[name]?.trim()) throw new Error("Set environment variable: " + name);
}
headers.Authorization = 'Bearer ' + process.env.API_KEY;
const response = await fetch(url, { method: "POST", headers, body: JSON.stringify({
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "从首帧平稳过渡到 @middle 再到尾帧。"
    },
    {
      "type": "first_frame",
      "url": "https://example.com/subject.png"
    },
    {
      "type": "middle_frame",
      "url": "https://example.com/middle.png",
      "id": "middle"
    },
    {
      "type": "last_frame",
      "url": "https://example.com/end.png"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}), signal: AbortSignal.timeout(120000) });
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
if (result?.success === false || result?.code === false || result?.error) throw new Error(JSON.stringify(result));
console.log(JSON.stringify(result, null, 2));

Multiple reference images

Applies to: kling-4.0

POST /v1/videos

{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "@person 站在 @scene 中,光照自然。"
    },
    {
      "type": "refer_image",
      "url": "https://example.com/subject.png",
      "id": "person"
    },
    {
      "type": "refer_image",
      "url": "https://example.com/end.png",
      "id": "scene"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}

curl

curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 120 --request POST 'https://api.tu-zi.com/v1/videos' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "@person 站在 @scene 中,光照自然。"
    },
    {
      "type": "refer_image",
      "url": "https://example.com/subject.png",
      "id": "person"
    },
    {
      "type": "refer_image",
      "url": "https://example.com/end.png",
      "id": "scene"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}'

python

import json
import os
import requests

url = "https://api.tu-zi.com/v1/videos"
headers = json.loads("{\"Authorization\":\"Bearer YOUR_API_KEY\",\"Content-Type\":\"application/json\"}")
for name in ["API_KEY"]:
    if not os.environ.get(name, "").strip():
        raise RuntimeError("Set environment variable: " + name)
headers["Authorization"] = "Bearer " + os.environ["API_KEY"]
payload = json.loads("{\"model\":\"kling-4.0\",\"contents\":[{\"type\":\"prompt\",\"text\":\"@person 站在 @scene 中,光照自然。\"},{\"type\":\"refer_image\",\"url\":\"https://example.com/subject.png\",\"id\":\"person\"},{\"type\":\"refer_image\",\"url\":\"https://example.com/end.png\",\"id\":\"scene\"}],\"settings\":{\"duration\":8,\"resolution\":\"720p\",\"aspect_ratio\":\"16:9\"}}")
response = requests.request("POST", url, headers=headers, json=payload, timeout=120)
response.raise_for_status()
result = response.json()
if isinstance(result, dict) and (result.get("success") is False or result.get("code") is False or result.get("error")):
    raise RuntimeError(json.dumps(result, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False, indent=2))

javascript

// Node.js 20+
const url = "https://api.tu-zi.com/v1/videos";
const headers = {
  "Authorization": "Bearer YOUR_API_KEY",
  "Content-Type": "application/json"
};
for (const name of ["API_KEY"]) {
  if (!process.env[name]?.trim()) throw new Error("Set environment variable: " + name);
}
headers.Authorization = 'Bearer ' + process.env.API_KEY;
const response = await fetch(url, { method: "POST", headers, body: JSON.stringify({
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "@person 站在 @scene 中,光照自然。"
    },
    {
      "type": "refer_image",
      "url": "https://example.com/subject.png",
      "id": "person"
    },
    {
      "type": "refer_image",
      "url": "https://example.com/end.png",
      "id": "scene"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}), signal: AbortSignal.timeout(120000) });
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
if (result?.success === false || result?.code === false || result?.error) throw new Error(JSON.stringify(result));
console.log(JSON.stringify(result, null, 2));

Video motion reference

Applies to: kling-4.0

POST /v1/videos

{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "参考 @motion 的动作和运镜。"
    },
    {
      "type": "feature_video",
      "url": "https://example.com/action.mp4",
      "id": "motion"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}

curl

curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 120 --request POST 'https://api.tu-zi.com/v1/videos' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "参考 @motion 的动作和运镜。"
    },
    {
      "type": "feature_video",
      "url": "https://example.com/action.mp4",
      "id": "motion"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}'

python

import json
import os
import requests

url = "https://api.tu-zi.com/v1/videos"
headers = json.loads("{\"Authorization\":\"Bearer YOUR_API_KEY\",\"Content-Type\":\"application/json\"}")
for name in ["API_KEY"]:
    if not os.environ.get(name, "").strip():
        raise RuntimeError("Set environment variable: " + name)
headers["Authorization"] = "Bearer " + os.environ["API_KEY"]
payload = json.loads("{\"model\":\"kling-4.0\",\"contents\":[{\"type\":\"prompt\",\"text\":\"参考 @motion 的动作和运镜。\"},{\"type\":\"feature_video\",\"url\":\"https://example.com/action.mp4\",\"id\":\"motion\"}],\"settings\":{\"duration\":8,\"resolution\":\"720p\",\"aspect_ratio\":\"16:9\"}}")
response = requests.request("POST", url, headers=headers, json=payload, timeout=120)
response.raise_for_status()
result = response.json()
if isinstance(result, dict) and (result.get("success") is False or result.get("code") is False or result.get("error")):
    raise RuntimeError(json.dumps(result, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False, indent=2))

javascript

// Node.js 20+
const url = "https://api.tu-zi.com/v1/videos";
const headers = {
  "Authorization": "Bearer YOUR_API_KEY",
  "Content-Type": "application/json"
};
for (const name of ["API_KEY"]) {
  if (!process.env[name]?.trim()) throw new Error("Set environment variable: " + name);
}
headers.Authorization = 'Bearer ' + process.env.API_KEY;
const response = await fetch(url, { method: "POST", headers, body: JSON.stringify({
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "参考 @motion 的动作和运镜。"
    },
    {
      "type": "feature_video",
      "url": "https://example.com/action.mp4",
      "id": "motion"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}), signal: AbortSignal.timeout(120000) });
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
if (result?.success === false || result?.code === false || result?.error) throw new Error(JSON.stringify(result));
console.log(JSON.stringify(result, null, 2));

Video editing

Applies to: kling-4.0

POST /v1/videos

{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "将 @source 的背景改成海滩,保持人物动作。"
    },
    {
      "type": "base_video",
      "url": "https://example.com/action.mp4",
      "id": "source"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}

curl

curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 120 --request POST 'https://api.tu-zi.com/v1/videos' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "将 @source 的背景改成海滩,保持人物动作。"
    },
    {
      "type": "base_video",
      "url": "https://example.com/action.mp4",
      "id": "source"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}'

python

import json
import os
import requests

url = "https://api.tu-zi.com/v1/videos"
headers = json.loads("{\"Authorization\":\"Bearer YOUR_API_KEY\",\"Content-Type\":\"application/json\"}")
for name in ["API_KEY"]:
    if not os.environ.get(name, "").strip():
        raise RuntimeError("Set environment variable: " + name)
headers["Authorization"] = "Bearer " + os.environ["API_KEY"]
payload = json.loads("{\"model\":\"kling-4.0\",\"contents\":[{\"type\":\"prompt\",\"text\":\"将 @source 的背景改成海滩,保持人物动作。\"},{\"type\":\"base_video\",\"url\":\"https://example.com/action.mp4\",\"id\":\"source\"}],\"settings\":{\"duration\":8,\"resolution\":\"720p\",\"aspect_ratio\":\"16:9\"}}")
response = requests.request("POST", url, headers=headers, json=payload, timeout=120)
response.raise_for_status()
result = response.json()
if isinstance(result, dict) and (result.get("success") is False or result.get("code") is False or result.get("error")):
    raise RuntimeError(json.dumps(result, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False, indent=2))

javascript

// Node.js 20+
const url = "https://api.tu-zi.com/v1/videos";
const headers = {
  "Authorization": "Bearer YOUR_API_KEY",
  "Content-Type": "application/json"
};
for (const name of ["API_KEY"]) {
  if (!process.env[name]?.trim()) throw new Error("Set environment variable: " + name);
}
headers.Authorization = 'Bearer ' + process.env.API_KEY;
const response = await fetch(url, { method: "POST", headers, body: JSON.stringify({
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "将 @source 的背景改成海滩,保持人物动作。"
    },
    {
      "type": "base_video",
      "url": "https://example.com/action.mp4",
      "id": "source"
    }
  ],
  "settings": {
    "duration": 8,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}), signal: AbortSignal.timeout(120000) });
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
if (result?.success === false || result?.code === false || result?.error) throw new Error(JSON.stringify(result));
console.log(JSON.stringify(result, null, 2));

Custom voice

Applies to: kling-4.0

POST /v1/videos

Both sites return 404 for voice creation; a site voice_id cannot yet be obtained. This is the contract for an enabled endpoint, not a claim of availability. Never submit the placeholder.

{
  "model": "kling-4.0",
  "contents": [
    {
      "type": "prompt",
      "text": "人物用 @voice_1 的声音说:欢迎。"
    },
    {
      "type": "voice",
      "voice_id": "voice_REPLACE_WITH_RESULT",
      "id": "voice_1"
    }
  ],
  "settings": {
    "duration": 5,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }
}

Create a voice from local WAV

Requires voice creation to be enabled on the site. Upload a 5–30 second PCM WAV of at most 15 MiB; voice_name is 1–20 characters. Choose multipart file or JSON voice_url; do not combine them or manually set the multipart boundary. When data.task_status is succeed, read data.task_result.voices[0].voice_id and use it in the voice item above. A task ID is not a voice ID.

curl --fail-with-body 'https://api.tu-zi.com/v1/general/custom-voices' \
  -H "Authorization: Bearer $TUZI_API_KEY" \
  -F 'voice_name=我的音色' \
  -F 'file=@./sample.wav;type=audio/wav'
curl --fail-with-body 'https://api.tu-zi.com/v1/general/custom-voices' \
  -H "Authorization: Bearer $TUZI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"voice_name":"我的音色","voice_url":"https://example.com/sample.wav"}'
curl --fail-with-body 'https://api.tu-zi.com/v1/general/custom-voices/task_REPLACE_WITH_RESULT' \
  -H "Authorization: Bearer $TUZI_API_KEY"
import os
import time
import requests

base = os.environ.get("TUZI_BASE_URL", "https://api.tu-zi.com").rstrip("/")
headers = {"Authorization": "Bearer " + os.environ["TUZI_API_KEY"]}

# Submit once. Save the returned task ID before polling.
with open("sample.wav", "rb") as audio:
    response = requests.post(
        base + "/v1/general/custom-voices", headers=headers,
        data={"voice_name": "My voice"},
        files={"file": ("sample.wav", audio, "audio/wav")}, timeout=120,
    )
response.raise_for_status()
task_id = response.json()["data"]["task_id"]
print("voice task_id:", task_id, flush=True)

deadline = time.monotonic() + 600
while time.monotonic() < deadline:
    response = requests.get(
        base + "/v1/general/custom-voices/" + task_id,
        headers=headers, timeout=30,
    )
    response.raise_for_status()
    data = response.json()["data"]
    if data["task_status"] == "succeed":
        voice_id = data["task_result"]["voices"][0]["voice_id"]
        break
    if data["task_status"] == "failed":
        raise RuntimeError(data.get("task_status_msg", "Voice creation failed"))
    time.sleep(5)
else:
    raise TimeoutError("Keep polling the existing task: " + task_id)

print("voice_id:", voice_id, flush=True)
response = requests.post(base + "/v1/videos", headers=headers, json={
    "model": "kling-4.0",
    "contents": [
        {"type": "prompt", "text": "A person says hello using @voice_1."},
        {"type": "voice", "voice_id": voice_id, "id": "voice_1"},
    ],
    "settings": {"duration": 5, "resolution": "720p", "aspect_ratio": "16:9"},
}, timeout=120)
response.raise_for_status()
print("video task:", response.json())
# Query GET /v1/videos/{id} with the ID returned above until completed or failed.

Voice creation reference

Create an element and reference it

Elements keep one character or object consistent across videos. JSON only: element_name 1–20 characters and element_description 1–100; image_refer takes one frontal image plus 1–3 other angles (public URL or Base64), video_refer one public 3–8 second video. element_voice_id can bind a site voice. When data.task_status is succeed, read data.task_result.elements[0].element_id and use it in an element item in contents. Only site element_ IDs are accepted, not numeric Kling IDs; a task ID is not an element ID.

curl --fail-with-body 'https://api.tu-zi.com/v1/general/advanced-custom-elements' \
  -H "Authorization: Bearer $TUZI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
  "element_name": "兔子",
  "element_description": "白色卡通兔子,红色围巾",
  "reference_type": "image_refer",
  "element_image_list": {
    "frontal_image": "https://example.com/front.png",
    "refer_images": [
      {
        "image_url": "https://example.com/side.png"
      }
    ]
  }
}'
curl --fail-with-body 'https://api.tu-zi.com/v1/general/advanced-custom-elements/task_REPLACE_WITH_RESULT' \
  -H "Authorization: Bearer $TUZI_API_KEY"
import os
import time
import requests

base = os.environ.get("TUZI_BASE_URL", "https://api.tu-zi.com").rstrip("/")
headers = {"Authorization": "Bearer " + os.environ["TUZI_API_KEY"]}

# Submit once. Save the returned task ID before polling.
response = requests.post(base + "/v1/general/advanced-custom-elements", headers=headers, json={
    "element_name": "Rabbit",
    "element_description": "White cartoon rabbit with a red scarf",
    "reference_type": "image_refer",
    "element_image_list": {
        "frontal_image": "https://example.com/front.png",
        "refer_images": [{"image_url": "https://example.com/side.png"}],
    },
}, timeout=120)
response.raise_for_status()
task_id = response.json()["data"]["task_id"]
print("element task_id:", task_id, flush=True)

deadline = time.monotonic() + 900
while time.monotonic() < deadline:
    response = requests.get(
        base + "/v1/general/advanced-custom-elements/" + task_id,
        headers=headers, timeout=30,
    )
    response.raise_for_status()
    data = response.json()["data"]
    if data["task_status"] == "succeed":
        element_id = data["task_result"]["elements"][0]["element_id"]
        break
    if data["task_status"] == "failed":
        raise RuntimeError(data.get("task_status_msg", "Element creation failed"))
    time.sleep(5)
else:
    raise TimeoutError("Keep polling the existing task: " + task_id)

print("element_id:", element_id, flush=True)
response = requests.post(base + "/v1/videos", headers=headers, json={
    "model": "kling-4.0",
    "contents": [
        {"type": "prompt", "text": "@element_1 runs in the rain."},
        {"type": "element", "element_id": element_id, "id": "element_1"},
    ],
    "settings": {"duration": 5, "resolution": "720p", "aspect_ratio": "16:9"},
}, timeout=120)
response.raise_for_status()
print("video task:", response.json())
# Query GET /v1/videos/{id} with the ID returned above until completed or failed.

Element creation reference

Task results and downloads

Save id or task_id from submission. Poll GET /v1/videos/{task_id}: queued / in_progress lead to completed or failed. Read video_url on completion (some responses also expose metadata.url). Resolve relative URLs against the API origin. The site /content endpoint uses your site key; external downloads must not receive that key. Download expiring results promptly. Resume GET after a timeout rather than automatically repeating POST.

Complete unified video Python / JavaScript polling and download examples

Troubleshooting

SymptomCheck
Image validation / URI errorEnsure a video or task ID was not placed in an image field; check the URL returns media
Unsupported content type / fieldCheck the exact family and content/contents/input schema; voice_id cannot be an audio URL
400 conflicting fieldsCheck prompt/input, frames/references, and seconds/response_format exclusivity
HTTP success but task failedRetain the site task ID, time, model, domain and redacted request; submission 200 is not output success
404 or inaccessible taskCheck domain, key access and task type; do not use IDs from another site or the official API
Local file cannot be fetchedUse a supported upload flow or a reachable HTTPS media URL

Sources and scope

Kling 4.0 text-to-video

Kling 4.0 image-to-video

Kling 4.0 video-omni

Kling API updates

Use cases

  • Choose video models and media formats
  • Diagnose request and task failures

API protocols

  • /v1/videos

FAQ

Does a task ID prove generation succeeded?

No. Save the site task ID, poll to a successful terminal state and verify the result. Inspect failures instead of automatically creating a new task.

Can I put a local image, video or WAV path in JSON?

No. URL fields require reachable media, not localhost, disk paths or browser-login links. Kling PCM WAV requires an enabled multipart voice endpoint (both sites returned 404 on 2026-11-15). Follow each family’s asset workflow for other media.

Can parameters and task IDs be reused across models?

Do not assume compatibility. Check the exact model, endpoint, casing, media role and exclusive fields. Editing, drafts and voices require accessible successful tasks of the correct kind. Official capabilities are not evidence of site acceptance.

Official sources

  1. Kling 4.0 text-to-video Official
  2. Kling 4.0 image-to-video Official
  3. Kling 4.0 video-omni Official
  4. Kling API updates Official