MiniMax H3 视频生成 API
使用 OpenAI 兼容的视频任务接口生成 MiniMax H3 视频 —— 复刻并完善版,重点补全首尾帧与多参考图用法。
01概述
MiniMax H3 通过 OpenAI 兼容的视频任务接口调用。接口是异步的,标准流程分三步:
- 提交任务:POST JSON 请求体,拿到任务 ID;
- 轮询状态:按固定间隔(建议 5 秒)查询,直到
completed或failed; - 下载视频:用同一个任务 ID 调用带鉴权的 content 接口获取 mp4。
所有请求都使用 Authorization: Bearer <API_KEY>。提交任务使用 JSON 请求体,查询和下载不需要请求体。
https://token.hzhun.com。该协议是 OpenAI 兼容的通用视频协议,任何实现相同协议的网关(如自建 new-api 站点)只需替换 Base URL 与密钥即可复用全部示例。
02模型列表
| 模型 | 说明 | 首尾帧 | 多参考图 |
|---|---|---|---|
minimax-h3-hq-fast | 画质增强快速档,速度更快、价格更低。 | 不支持 | 以账号配置为准 |
minimax-h3-hq | 画质增强高质档。 | 不支持 | 以账号配置为准 |
minimax-h3-mm-fast | 多模式快速档,支持 metadata.style 1–6。 | 不支持 | 以账号配置为准 |
minimax-h3-mm | 多模式高质档,支持真人与漫剧风格;5 为漫剧文戏,6 为漫剧武戏。 | 不支持 | 以账号配置为准 |
minimax-h3-hq-audio-fast | 画质增强快速档,最多 3 段参考音频;metadata.style 1–4。 | 不支持 | 以账号配置为准 |
minimax-h3-hq-audio | 画质增强高质档,最多 3 段参考音频;metadata.style 1–4。 | 不支持 | 以账号配置为准 |
minimax-h3-mm-audio-fast | 多模式快速档,最多 3 段参考音频;metadata.style 1–6。 | 不支持 | 以账号配置为准 |
minimax-h3-mm-audio | 多模式高质档,最多 3 段参考音频;metadata.style 1–6。 | 不支持 | 以账号配置为准 |
minimax-h3-nosub | 无字幕版本,其他能力按标准 H3 视频接口处理。 | 按标准 H3 | 按标准 H3 |
minimax-h3-x | T8、24fps、原生音画,支持文生、首帧、首尾帧和多参考素材。 | 支持 | 支持 |
minimax-h3-xs | 24fps、原生音画,支持文生、首帧、首尾帧和多参考素材。 | 支持 | 支持 |
标准 H3 模型通常支持 3–15 秒、9:16 或 16:9、480P / 768P / 1088P / 1440P,以及最多 9 张参考图。HQ/MM 系列不支持首尾帧和参考视频。X/XS 的素材能力以实际模型和账号配置为准。模型可用性、分辨率和计费以控制台当前配置为准。
03快速开始(文生视频)
最小请求只需要模型、提示词、时长和尺寸。seconds 使用数字,size 使用 宽x高;也可以使用 resolution 传入 480p、768p、1088p 或 1440p(两者二选一)。
curl https://token.hzhun.com/v1/videos \
-H "Authorization: Bearer <API_KEY>" \
-H "Content-Type: application/json" \
-d '{
"model": "minimax-h3-hq-fast",
"prompt": "一只白色恐龙在海边奔跑,电影感镜头",
"seconds": 5,
"size": "1024x576"
}'
import requests
resp = requests.post(
"https://token.hzhun.com/v1/videos",
headers={"Authorization": "Bearer <API_KEY>"},
json={
"model": "minimax-h3-hq-fast",
"prompt": "一只白色恐龙在海边奔跑,电影感镜头",
"seconds": 5,
"size": "1024x576",
},
timeout=60,
)
resp.raise_for_status()
task_id = resp.json()["id"] # 保存任务 ID,用于轮询和下载
print("task_id:", task_id)
const resp = await fetch("https://token.hzhun.com/v1/videos", {
method: "POST",
headers: {
"Authorization": "Bearer <API_KEY>",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "minimax-h3-hq-fast",
prompt: "一只白色恐龙在海边奔跑,电影感镜头",
seconds: 5,
size: "1024x576",
}),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
const data = await resp.json();
console.log("task_id:", data.id); // 保存任务 ID,用于轮询和下载
<?php
$ch = curl_init("https://token.hzhun.com/v1/videos");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <API_KEY>",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode([
"model" => "minimax-h3-hq-fast",
"prompt" => "一只白色恐龙在海边奔跑,电影感镜头",
"seconds" => 5,
"size" => "1024x576",
], JSON_UNESCAPED_UNICODE),
]);
$resp = curl_exec($ch);
curl_close($ch);
$taskId = json_decode($resp, true)["id"];
echo "task_id: $taskId\n";
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
body, _ := json.Marshal(map[string]any{
"model": "minimax-h3-hq-fast",
"prompt": "一只白色恐龙在海边奔跑,电影感镜头",
"seconds": 5,
"size": "1024x576",
})
req, _ := http.NewRequest("POST",
"https://token.hzhun.com/v1/videos", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer <API_KEY>")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data map[string]any
json.NewDecoder(resp.Body).Decode(&data)
fmt.Println("task_id:", data["id"]) // 保存任务 ID
}
import java.net.URI;
import java.net.http.*;
public class SubmitVideo {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "minimax-h3-hq-fast",
"prompt": "一只白色恐龙在海边奔跑,电影感镜头",
"seconds": 5,
"size": "1024x576"
}""";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://token.hzhun.com/v1/videos"))
.header("Authorization", "Bearer <API_KEY>")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body()); // 取 JSON 中的 id 作为任务 ID
}
}
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "<API_KEY>");
var body = JsonSerializer.Serialize(new {
model = "minimax-h3-hq-fast",
prompt = "一只白色恐龙在海边奔跑,电影感镜头",
seconds = 5,
size = "1024x576",
});
var resp = await client.PostAsync(
"https://token.hzhun.com/v1/videos",
new StringContent(body, Encoding.UTF8, "application/json"));
resp.EnsureSuccessStatusCode();
var json = await resp.Content.ReadAsStringAsync();
Console.WriteLine(json); // 取 JSON 中的 id 作为任务 ID
提交成功后,响应中返回任务 ID:
{
"id": "video_xxx",
"status": "queued",
"model": "minimax-h3-hq-fast"
}保存 id,然后按 第 9 节轮询状态、第 10 节下载视频。
04请求参数
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | H3 模型名,使用模型列表中的完整名称。 |
prompt | string | 是 | 视频内容描述。带参考素材时,可在提示词中用「参考图 1 / 参考图 2」等指代。 |
seconds | number | 建议 | 视频时长;标准 H3 通常为 3–15 秒。 |
size | string | 二选一 | 输出宽高,例如 1024x576(16:9 横版)或 576x1024(9:16 竖版)。 |
resolution | string | 二选一 | 分辨率档位:480p / 768p / 1088p / 1440p。与 size 二选一。 |
input_reference | string | 否 | 单张参考图的 URL,通常作为首帧。详见第 5 节。 |
images | array<string> | 否 | 多张参考图 URL 数组,最多 9 张,数组顺序即「参考图 1/2/3…」。详见第 7 节。 |
metadata.style | number | 否 | 多模式模型的风格编号;范围由模型决定(mm 系列 1–6,hq-audio 系列 1–4)。详见第 8 节。 |
metadata.media | array<object> | 否 | 带角色标记的媒体输入扩展,用于首尾帧、参考视频、参考音频。详见第 6 节。 |
input_reference 是单个 URL 字符串;images 是 URL 数组。只传一张图时两者等价,多张图必须用 images。JSON 客户端请传公网可访问的图片地址(http/https)。
05图生视频(首帧单图)
只需要一张首帧图时,把图片 URL 放进 input_reference(或等价地放进单元素 images 数组)。模型会以该图为起始画面,按提示词生成后续运动。
curl https://token.hzhun.com/v1/videos \
-H "Authorization: Bearer <API_KEY>" \
-H "Content-Type: application/json" \
-d '{
"model": "minimax-h3-xs",
"prompt": "以参考图作为视频首帧,镜头缓慢推进,人物自然眨眼并微笑",
"seconds": 5,
"size": "854x480",
"input_reference": "https://example.com/first-frame.png"
}'
import requests
resp = requests.post(
"https://token.hzhun.com/v1/videos",
headers={"Authorization": "Bearer <API_KEY>"},
json={
"model": "minimax-h3-xs",
"prompt": "以参考图作为视频首帧,镜头缓慢推进,人物自然眨眼并微笑",
"seconds": 5,
"size": "854x480",
# 单张首帧图:URL 字符串
"input_reference": "https://example.com/first-frame.png",
},
timeout=60,
)
resp.raise_for_status()
print("task_id:", resp.json()["id"])
const resp = await fetch("https://token.hzhun.com/v1/videos", {
method: "POST",
headers: {
"Authorization": "Bearer <API_KEY>",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "minimax-h3-xs",
prompt: "以参考图作为视频首帧,镜头缓慢推进,人物自然眨眼并微笑",
seconds: 5,
size: "854x480",
input_reference: "https://example.com/first-frame.png",
}),
});
const data = await resp.json();
console.log("task_id:", data.id);
06首尾帧视频
首尾帧模式让视频从指定画面开始、在指定画面结束,中间由模型补全自然过渡。这是原文档着墨最少、但最容易用错的部分。
6.1 为什么不用 input_reference / images?
input_reference 和 images 只是「一组参考图」,表达不了哪张是首帧、哪张是尾帧。首尾帧必须走 metadata.media,用 type 字段显式标记每张图的角色:
| metadata.media[].type | 含义 | 说明 |
|---|---|---|
first_frame | 首帧图 | 视频第一帧画面,URL 必须是公网可访问的 http(s) 图片地址。 |
last_frame | 尾帧图 | 视频最后一帧画面。可单独与首帧搭配,也可只传首帧。 |
reference_video | 参考视频 | 动作 / 运镜参考,仅部分模型支持(HQ/MM 系列不支持)。 |
reference_audio | 参考音频 | audio 系列模型最多 3 段。 |
数组成员结构统一为 {"type": "...", "url": "https://..."}。普通参考图不要放进 media——不区分角色的参考图请使用 images(见第 7 节)。
6.2 模型与参数限制
- 仅
minimax-h3-x/minimax-h3-xs等支持首尾帧,HQ/MM 系列不支持,误用会直接报 400。 - 首帧、尾帧两张图的宽高比应一致,并与
size的比例匹配(竖版图配480x854,横版图配854x480),否则可能被裁切或生成失败。 - 提示词建议明确写出「以第一张图片作为视频首帧,第二张图片作为视频尾帧」,并描述两帧之间的运动与光影过渡。
6.3 请求示例
curl https://token.hzhun.com/v1/videos \
-H "Authorization: Bearer <API_KEY>" \
-H "Content-Type: application/json" \
-d '{
"model": "minimax-h3-xs",
"prompt": "以第一张图片作为视频首帧,第二张图片作为视频尾帧,生成一段自然连贯的过渡视频。橘猫先安静望向窗外,随后缓慢转头看向镜头,镜头轻微稳定推进,保持真实摄影质感。",
"seconds": 5,
"size": "480x854",
"metadata": {
"media": [
{ "type": "first_frame", "url": "https://example.com/first.png" },
{ "type": "last_frame", "url": "https://example.com/last.png" }
]
}
}'
import requests
resp = requests.post(
"https://token.hzhun.com/v1/videos",
headers={"Authorization": "Bearer <API_KEY>"},
json={
"model": "minimax-h3-xs", # 首尾帧仅 X/XS 等支持
"prompt": (
"以第一张图片作为视频首帧,第二张图片作为视频尾帧,"
"生成一段自然连贯的过渡视频。橘猫先安静望向窗外,"
"随后缓慢转头看向镜头,镜头轻微稳定推进,保持真实摄影质感。"
),
"seconds": 5,
"size": "480x854",
"metadata": {
"media": [
{"type": "first_frame", "url": "https://example.com/first.png"},
{"type": "last_frame", "url": "https://example.com/last.png"},
]
},
},
timeout=60,
)
resp.raise_for_status()
print("task_id:", resp.json()["id"])
const resp = await fetch("https://token.hzhun.com/v1/videos", {
method: "POST",
headers: {
"Authorization": "Bearer <API_KEY>",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "minimax-h3-xs",
prompt: "以第一张图片作为视频首帧,第二张图片作为视频尾帧,生成自然连贯的过渡视频。",
seconds: 5,
size: "480x854",
metadata: {
media: [
{ type: "first_frame", url: "https://example.com/first.png" },
{ type: "last_frame", url: "https://example.com/last.png" },
],
},
}),
});
const data = await resp.json();
console.log("task_id:", data.id);
<?php
$ch = curl_init("https://token.hzhun.com/v1/videos");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <API_KEY>",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode([
"model" => "minimax-h3-xs",
"prompt" => "以第一张图片作为视频首帧,第二张图片作为视频尾帧,生成自然连贯的过渡视频。",
"seconds" => 5,
"size" => "480x854",
"metadata" => [
"media" => [
["type" => "first_frame", "url" => "https://example.com/first.png"],
["type" => "last_frame", "url" => "https://example.com/last.png"],
],
],
], JSON_UNESCAPED_UNICODE),
]);
$resp = curl_exec($ch);
curl_close($ch);
echo json_decode($resp, true)["id"], "\n";
body, _ := json.Marshal(map[string]any{
"model": "minimax-h3-xs",
"prompt": "以第一张图片作为视频首帧,第二张图片作为视频尾帧,生成自然连贯的过渡视频。",
"seconds": 5,
"size": "480x854",
"metadata": map[string]any{
"media": []map[string]string{
{"type": "first_frame", "url": "https://example.com/first.png"},
{"type": "last_frame", "url": "https://example.com/last.png"},
},
},
})
// 其余提交逻辑同快速开始 Go 示例
.../首尾帧视频.png),建议先做百分号编码再提交,避免上游拉图失败。Python 可用 urllib.parse.quote 处理路径部分,完整封装见第 11 节。
07多参考图视频
多参考图模式用于主体一致性生成:例如多张同一人物的照片锁定长相,再加一张场景图指定环境。与首尾帧不同,这些图不指定出现顺序,只作为内容参考。
7.1 images 数组的语义
- 使用
images字段,值为 URL 字符串数组,最多 9 张(具体上限以模型为准)。 - 数组顺序即参考图编号:第 1 个元素是「参考图 1」,第 2 个是「参考图 2」,依此类推;提示词中用编号引用即可精确分工。
- 典型分工:人物图放前面负责身份一致,场景 / 光影图放后面负责环境基准。
7.2 与首尾帧的区别
| 对比项 | 多参考图 images | 首尾帧 metadata.media |
|---|---|---|
| 图片角色 | 内容参考(人物 / 场景 / 风格) | 明确的时间锚点(第一帧 / 最后一帧) |
| 图片顺序 | 顺序 = 参考图编号,供提示词引用 | 由 type 标记决定,与数组顺序无关 |
| 数量上限 | 最多 9 张 | 首帧 + 尾帧通常各 1 张 |
| 支持模型 | X/XS 及标准 H3(以账号配置为准) | 仅 X/XS 等,HQ/MM 不支持 |
7.3 请求示例
curl https://token.hzhun.com/v1/videos \
-H "Authorization: Bearer <API_KEY>" \
-H "Content-Type: application/json" \
-d '{
"model": "minimax-h3-xs",
"prompt": "以参考图 1 和参考图 2 中的同一位年轻女性为主角,参考图 3 作为场景与光影基准。主角坐在森林咖啡馆窗边,先低头看书,随后轻轻合上书,抬眼望向窗外并微笑;镜头从书本缓慢推进到人物半身。人物始终保持同一张脸、同一发型和同一套服装,整体写实电影质感。",
"seconds": 5,
"size": "854x480",
"images": [
"https://example.com/person-1.png",
"https://example.com/person-2.png",
"https://example.com/scene.png"
]
}'
import requests
resp = requests.post(
"https://token.hzhun.com/v1/videos",
headers={"Authorization": "Bearer <API_KEY>"},
json={
"model": "minimax-h3-xs",
"prompt": (
"以参考图 1 和参考图 2 中的同一位年轻女性为主角,"
"参考图 3 作为场景与光影基准。主角坐在森林咖啡馆窗边,"
"先低头看书,随后轻轻合上书,抬眼望向窗外并微笑;"
"镜头从书本缓慢推进到人物半身。人物始终保持同一张脸、"
"同一发型和同一套服装,整体写实电影质感。"
),
"seconds": 5,
"size": "854x480",
# 数组顺序 = 参考图 1 / 2 / 3,最多 9 张
"images": [
"https://example.com/person-1.png",
"https://example.com/person-2.png",
"https://example.com/scene.png",
],
},
timeout=60,
)
resp.raise_for_status()
print("task_id:", resp.json()["id"])
const resp = await fetch("https://token.hzhun.com/v1/videos", {
method: "POST",
headers: {
"Authorization": "Bearer <API_KEY>",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "minimax-h3-xs",
prompt: "以参考图 1 和参考图 2 中的同一位年轻女性为主角,参考图 3 作为场景与光影基准……",
seconds: 5,
size: "854x480",
images: [
"https://example.com/person-1.png",
"https://example.com/person-2.png",
"https://example.com/scene.png",
],
}),
});
const data = await resp.json();
console.log("task_id:", data.id);
<?php
$ch = curl_init("https://token.hzhun.com/v1/videos");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <API_KEY>",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode([
"model" => "minimax-h3-xs",
"prompt" => "以参考图 1 和参考图 2 中的同一位年轻女性为主角,参考图 3 作为场景与光影基准……",
"seconds" => 5,
"size" => "854x480",
"images" => [
"https://example.com/person-1.png",
"https://example.com/person-2.png",
"https://example.com/scene.png",
],
], JSON_UNESCAPED_UNICODE),
]);
$resp = curl_exec($ch);
curl_close($ch);
echo json_decode($resp, true)["id"], "\n";
body, _ := json.Marshal(map[string]any{
"model": "minimax-h3-xs",
"prompt": "以参考图 1 和参考图 2 中的同一位年轻女性为主角,参考图 3 作为场景与光影基准……",
"seconds": 5,
"size": "854x480",
"images": []string{
"https://example.com/person-1.png",
"https://example.com/person-2.png",
"https://example.com/scene.png",
},
})
// 其余提交逻辑同快速开始 Go 示例
08多模式风格 style
多模式(mm 系列)与带音频模型支持 metadata.style 风格编号。mm 系列范围 1–6,其中 5 为漫剧文戏、6 为漫剧武戏;hq-audio 系列范围 1–4。该字段与 metadata.media 可以共存于同一个 metadata 对象中。
{
"model": "minimax-h3-mm",
"prompt": "古风漫剧场景,两人对坐饮茶交谈",
"seconds": 5,
"size": "1024x576",
"metadata": { "style": 5 }
}09查询任务状态
提交成功后保存响应中的 id,按固定间隔(建议 5 秒)查询。不要在任务仍为 queued 或 in_progress 时重复提交相同请求。
| status | 含义 | 处理 |
|---|---|---|
queued | 排队中 | 继续轮询 |
in_progress | 生成中,可能带 progress 进度 | 继续轮询 |
completed | 生成完成 | 进入下载步骤 |
failed | 生成失败 | 读取 error.message 排查,修正后重新提交 |
curl https://token.hzhun.com/v1/videos/<TASK_ID> \
-H "Authorization: Bearer <API_KEY>"
import time
import requests
HEADERS = {"Authorization": "Bearer <API_KEY>"}
while True:
data = requests.get(
f"https://token.hzhun.com/v1/videos/{task_id}",
headers=HEADERS, timeout=60,
).json()
print(data["status"], data.get("progress", ""))
if data["status"] in ("completed", "failed"):
break
time.sleep(5)
if data["status"] == "failed":
raise RuntimeError(data.get("error", {}).get("message", "生成失败"))
let data;
while (true) {
const resp = await fetch(`https://token.hzhun.com/v1/videos/${taskId}`, {
headers: { "Authorization": "Bearer <API_KEY>" },
});
data = await resp.json();
console.log(data.status, data.progress ?? "");
if (data.status === "completed" || data.status === "failed") break;
await new Promise(r => setTimeout(r, 5000));
}
if (data.status === "failed") throw new Error(data.error?.message ?? "生成失败");
典型进行中的响应:
{
"id": "video_xxx",
"status": "in_progress",
"model": "minimax-h3-hq-fast"
}10下载视频
任务完成后,使用同一个任务 ID 下载内容。建议始终使用带鉴权的 content 接口:部分响应中会返回 url 字段,如果该地址是本站 /v1/videos/... 路径,直接访问会因缺少鉴权失败,仍需走 content 接口。
curl -L https://token.hzhun.com/v1/videos/<TASK_ID>/content \
-H "Authorization: Bearer <API_KEY>" \
-o result.mp4
resp = requests.get(
f"https://token.hzhun.com/v1/videos/{task_id}/content",
headers=HEADERS, timeout=60,
)
resp.raise_for_status()
with open("result.mp4", "wb") as f:
for chunk in resp.iter_content(chunk_size=65536):
f.write(chunk)
print("已保存 result.mp4")
import { writeFile } from "node:fs/promises";
const resp = await fetch(`https://token.hzhun.com/v1/videos/${taskId}/content`, {
headers: { "Authorization": "Bearer <API_KEY>" },
redirect: "follow",
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
await writeFile("result.mp4", Buffer.from(await resp.arrayBuffer()));
console.log("已保存 result.mp4");
11Python 完整封装(实测可用)
以下是对本地实测脚本的精简整理:一个类封装提交 / 轮询 / 下载全流程,配置区集中管理网关、密钥、模型与素材,修改 CONFIG 即可切换文生、首帧、首尾帧、多参考图四种模式。依赖仅 requests(pip install requests)。
# -*- coding: utf-8 -*-
"""MiniMax H3 视频生成完整示例:修改 CONFIG 后直接运行"""
import time
from urllib.parse import urlsplit, urlunsplit, quote
import requests
CONFIG = {
"gateway": "https://token.hzhun.com",
"api_key": "<API_KEY>",
"model": "minimax-h3-xs",
"prompt": "一只白色恐龙在海边奔跑,电影感镜头",
"seconds": 5,
"size": "1024x576", # 与 resolution 二选一
"resolution": None, # 480p / 768p / 1088p / 1440p
"input_reference": None, # 单张首帧图 URL
"images": None, # 多参考图 URL 列表,最多 9 张
"first_frame": None, # 首帧图 URL(首尾帧模式,仅 X/XS 支持)
"last_frame": None, # 尾帧图 URL
"style": None, # mm 系列风格编号 1-6
"out_file": "result.mp4",
}
POLL_INTERVAL = 5 # 轮询间隔(秒)
MAX_WAIT = 900 # 最长等待(秒)
def encode_url(u):
"""对 URL 路径中的中文做百分号编码,避免上游拉图失败"""
s = urlsplit(u)
return urlunsplit((s.scheme, s.netloc, quote(s.path), s.query, s.fragment))
def build_body(cfg):
body = {"model": cfg["model"], "prompt": cfg["prompt"]}
if cfg.get("seconds"):
body["seconds"] = cfg["seconds"]
if cfg.get("resolution"):
body["resolution"] = cfg["resolution"]
elif cfg.get("size"):
body["size"] = cfg["size"]
if cfg.get("input_reference"):
body["input_reference"] = encode_url(cfg["input_reference"])
if cfg.get("images"):
body["images"] = [encode_url(u) for u in cfg["images"]]
# 首尾帧走 metadata.media,普通参考图不要放这里
media = []
if cfg.get("first_frame"):
media.append({"type": "first_frame", "url": encode_url(cfg["first_frame"])})
if cfg.get("last_frame"):
media.append({"type": "last_frame", "url": encode_url(cfg["last_frame"])})
if media:
body.setdefault("metadata", {})["media"] = media
if cfg.get("style") is not None:
body.setdefault("metadata", {})["style"] = cfg["style"]
return body
class H3VideoClient:
def __init__(self, gateway, api_key):
self.base = gateway.rstrip("/").removesuffix("/v1")
self.session = requests.Session()
self.session.headers.update({"Authorization": "Bearer " + api_key})
def _request(self, method, path, **kwargs):
resp = self.session.request(method, self.base + path, timeout=60, **kwargs)
if resp.status_code != 200:
raise RuntimeError(f"HTTP {resp.status_code}: {resp.text[:300]}")
return resp
def submit(self, body):
data = self._request("POST", "/v1/videos", json=body).json()
task_id = data.get("id") or data.get("task_id")
if not task_id:
raise RuntimeError("网关未返回任务 ID")
print("[提交成功] task_id =", task_id)
return task_id
def poll(self, task_id):
waited = 0
while waited < MAX_WAIT:
data = self._request("GET", f"/v1/videos/{task_id}").json()
status = data.get("status")
print(f"[轮询] status={status} progress={data.get('progress', '')}")
if status == "completed":
return data
if status == "failed":
msg = (data.get("error") or {}).get("message", "未知原因")
raise RuntimeError("生成失败: " + msg)
time.sleep(POLL_INTERVAL)
waited += POLL_INTERVAL
raise TimeoutError(f"等待超时,任务 {task_id} 仍在处理")
def download(self, task_id, out_file):
resp = self._request("GET", f"/v1/videos/{task_id}/content")
with open(out_file, "wb") as f:
for chunk in resp.iter_content(chunk_size=65536):
f.write(chunk)
print("[下载完成]", out_file)
if __name__ == "__main__":
client = H3VideoClient(CONFIG["gateway"], CONFIG["api_key"])
tid = client.submit(build_body(CONFIG))
client.poll(tid)
client.download(tid, CONFIG["out_file"])
切换模式只需修改 CONFIG:
- 首尾帧:填入
first_frame/last_frame,模型用minimax-h3-xs; - 多参考图:填入
images列表,提示词中用「参考图 1/2/3」分工; - 多模式风格:模型换
minimax-h3-mm,设置style。
12错误码与常见问题
| 状态码 | 含义与处理 |
|---|---|
400 | 检查模型名、提示词、时长、尺寸和参考素材格式。首尾帧误用在 HQ/MM 模型上也会报 400。 |
401 | 检查 API Key 和 Authorization 请求头(Bearer 前缀不能省)。 |
404 | 检查任务 ID,或确认任务仍在当前账号下。 |
429 | 降低并发并稍后重试查询。 |
5xx | 上游或任务服务暂时不可用;不要立即重复创建任务,先查询原任务状态。 |
常见问题
- 首尾帧能用 images 传两张图吗?不能。images 不区分首帧/尾帧角色,必须用 metadata.media 并标记 type。
- images 和首尾帧能同时用吗?协议上字段可以共存,但素材能力以模型与账号配置为准,建议先用小时长任务验证。
- 参考图能传本地文件吗?JSON 客户端请传公网可访问的图片 URL;含中文文件名的 URL 先做百分号编码。
- 任务一直 queued 怎么办?耐心等待并继续轮询,不要重复提交;超过预期时长可联系服务商确认排队情况。
- 下载返回 401?content 接口同样需要 Authorization 头;不要直接无鉴权访问响应里的本站 url。