欢迎使用 Luma API!
本快速开始指南将引导您完成使用最先进的 AI 模型开始修改视频的基本步骤。概述
生成的视频是异步处理的。使用回调或轮询来跟踪完成状态。
身份验证
所有 API 请求都需要通过 Bearer Token 进行身份验证。1
获取您的 API Key
访问 API Key 管理页面 获取您的 API key。
2
添加到请求头
在所有请求中包含您的 API key:
复制
Authorization: Bearer YOUR_API_KEY
请保护好您的 API key,永远不要公开分享。如果泄露,请立即在管理页面重置。
基本用法
1. 修改现有视频
首先创建您的第一个视频修改任务:复制
async function modifyVideo() {
try {
const response = await fetch('https://api.kie.ai/api/v1/modify/generate', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'A futuristic cityscape at night with towering glass spires reaching into a starry sky. Neon lights in blue and purple illuminate the buildings while flying vehicles glide silently between the structures.',
videoUrl: 'https://example.com/input-video.mp4',
callBackUrl: 'https://your-callback-url.com/luma-callback'
})
});
const result = await response.json();
if (response.ok && result.code === 200) {
console.log('任务已提交:', result);
console.log('任务 ID:', result.data.taskId);
return result.data.taskId;
} else {
console.error('请求失败:', result.msg || '未知错误');
return null;
}
} catch (error) {
console.error('错误:', error.message);
return null;
}
}
modifyVideo();
复制
{
"code": 200,
"msg": "success",
"data": {
"taskId": "774d9a7dd608a0e49293903095e45a4c"
}
}
2. 检查生成状态
使用返回的taskId 监控进度:
复制
const checkStatus = async (taskId) => {
try {
const response = await fetch(`https://api.kie.ai/api/v1/modify/record-info?taskId=${taskId}`, {
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const result = await response.json();
if (response.ok && result.code === 200) {
console.log('查询成功:', result);
console.log('成功标志:', result.data.successFlag);
console.log('结果视频:', result.data.response?.resultUrls);
return result.data;
} else {
console.error('查询失败:', result.msg || '未知错误');
return null;
}
} catch (error) {
console.error('查询状态失败:', error.message);
return null;
}
};
// 使用方法
const status = await checkStatus('774d9a7dd608a0e49293903095e45a4c');
0: 生成中 - 任务正在处理中1: 成功 - 任务成功完成2: 创建任务失败 - 无法创建任务3: 生成失败 - 任务创建成功但生成失败4: 回调失败 - 生成成功但回调失败
完整工作流示例
这是一个修改视频并等待完成的完整示例:- JavaScript
- Python
复制
class LumaAPI {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.kie.ai/api/v1/modify';
}
async modifyVideo(prompt, videoUrl, options = {}) {
const response = await fetch(`${this.baseUrl}/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
videoUrl,
callBackUrl: options.callBackUrl,
watermark: options.watermark,
...options
})
});
const result = await response.json();
if (!(response.ok && result.code === 200)) {
throw new Error(`生成失败: ${result.msg || '未知错误'}`);
}
return result.data.taskId;
}
async waitForCompletion(taskId, maxWaitTime = 900000) { // 15 分钟最大
const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) {
const status = await this.getTaskStatus(taskId);
if (status.successFlag === 1) {
return status.response;
} else if (status.successFlag === 2 || status.successFlag === 3) {
throw new Error(`生成失败: ${status.errorMessage || '未知错误'}`);
}
// 下次检查前等待 10 秒
await new Promise(resolve => setTimeout(resolve, 10000));
}
throw new Error('生成超时');
}
async getTaskStatus(taskId) {
const response = await fetch(`${this.baseUrl}/record-info?taskId=${taskId}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});
const result = await response.json();
if (!(response.ok && result.code === 200)) {
throw new Error(`查询失败: ${result.msg || '未知错误'}`);
}
return result.data;
}
}
// 使用示例
async function main() {
const api = new LumaAPI('YOUR_API_KEY');
try {
// 视频修改
console.log('开始视频修改...');
const taskId = await api.modifyVideo(
'A futuristic cityscape at night with towering glass spires reaching into a starry sky. Neon lights in blue and purple illuminate the buildings while flying vehicles glide silently between the structures. Holographic advertisements flicker and change on building facades.',
'https://example.com/input-video.mp4',
{
callBackUrl: 'https://your-callback-url.com/luma-callback',
watermark: 'your-watermark-id'
}
);
// 等待完成
console.log(`任务 ID: ${taskId}。等待完成...`);
const result = await api.waitForCompletion(taskId);
console.log('视频修改成功!');
console.log('结果视频 URL:', result.resultUrls);
console.log('原始视频 URL:', result.originUrls);
} catch (error) {
console.error('错误:', error.message);
}
}
main();
复制
import requests
import time
class LumaAPI:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'https://api.kie.ai/api/v1/modify'
self.headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
def modify_video(self, prompt, video_url, **options):
data = {
'prompt': prompt,
'videoUrl': video_url,
'callBackUrl': options.get('callBackUrl'),
'watermark': options.get('watermark'),
**options
}
# 移除 None 值
data = {k: v for k, v in data.items() if v is not None}
response = requests.post(f'{self.base_url}/generate',
headers=self.headers, json=data)
result = response.json()
if not (response.ok and result.get('code') == 200):
raise Exception(f"生成失败: {result.get('msg', '未知错误')}")
return result['data']['taskId']
def wait_for_completion(self, task_id, max_wait_time=900):
start_time = time.time()
while time.time() - start_time < max_wait_time:
status = self.get_task_status(task_id)
if status['successFlag'] == 1:
return status['response']
elif status['successFlag'] in [2, 3]:
error_msg = status.get('errorMessage', '未知错误')
raise Exception(f"生成失败: {error_msg}")
time.sleep(10) # 等待 10 秒
raise Exception('生成超时')
def get_task_status(self, task_id):
response = requests.get(f'{self.base_url}/record-info?taskId={task_id}',
headers={'Authorization': f'Bearer {self.api_key}'})
result = response.json()
if not (response.ok and result.get('code') == 200):
raise Exception(f"查询失败: {result.get('msg', '未知错误')}")
return result['data']
# 使用示例
def main():
api = LumaAPI('YOUR_API_KEY')
try:
# 视频修改
print('开始视频修改...')
task_id = api.modify_video(
'A futuristic cityscape at night with towering glass spires reaching into a starry sky. Neon lights in blue and purple illuminate the buildings while flying vehicles glide silently between the structures. Holographic advertisements flicker and change on building facades.',
'https://example.com/input-video.mp4',
callBackUrl='https://your-callback-url.com/luma-callback',
watermark='your-watermark-id'
)
# 等待完成
print(f'任务 ID: {task_id}。等待完成...')
result = api.wait_for_completion(task_id)
print('视频修改成功!')
print(f'结果视频 URL: {result["resultUrls"]}')
print(f'原始视频 URL: {result["originUrls"]}')
# 下载视频
for i, url in enumerate(result['resultUrls']):
filename = f'modified_video_{i+1}.mp4'
download_video(url, filename)
except Exception as error:
print(f'错误: {error}')
def download_video(url, filename):
response = requests.get(url, stream=True)
response.raise_for_status()
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f'已下载: {filename}')
if __name__ == '__main__':
main()
高级功能
水印支持
为生成的视频添加水印:复制
const taskId = await api.modifyVideo(
'将此场景转换为魔法森林',
'https://example.com/input-video.mp4',
{
watermark: 'your-brand-watermark'
}
);
使用回调
设置 webhook 回调以获取自动通知:复制
const taskId = await api.modifyVideo(
'创建戏剧性的日落转换',
'https://example.com/input-video.mp4',
{
callBackUrl: 'https://your-server.com/luma-callback'
}
);
// 您的回调端点将收到:
app.post('/luma-callback', (req, res) => {
const { code, data } = req.body;
if (code === 200) {
console.log('视频准备就绪:', data.resultUrls);
} else {
console.log('生成失败:', req.body.msg);
}
res.status(200).json({ status: 'received' });
});
了解更多关于回调
设置 webhook 回调以在视频准备就绪时接收自动通知。
错误处理
常见错误场景及处理方法:无效视频 URL(代码 422)
无效视频 URL(代码 422)
复制
try {
const taskId = await api.modifyVideo('提示', '无效-url');
} catch (error) {
if (error.data.code === 422) {
console.log('请提供一个有效的、可访问的视频 URL');
}
}
生成失败(代码 501)
生成失败(代码 501)
复制
try {
const result = await api.waitForCompletion(taskId);
} catch (error) {
console.log('生成失败。尝试调整您的提示或视频输入');
}
频率限制(代码 429)
频率限制(代码 429)
复制
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function generateWithRetry(prompt, videoUrl, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await api.modifyVideo(prompt, videoUrl, options);
} catch (error) {
if (error.data.code === 429 && i < maxRetries - 1) {
await delay(Math.pow(2, i) * 1000); // 指数退避
continue;
}
throw error;
}
}
}
最佳实践
性能优化
- 使用回调:设置 webhook 回调而不是轮询以获得更好的性能
- 提示工程:使用详细、具体的提示以获得更好的结果
- 视频预处理:确保输入视频经过优化且可访问
- 下载管理:及时下载生成的视频,因为它们可能会过期
- 错误处理:实施强大的错误处理和重试逻辑
重要限制
- 语言支持:提示仅支持英语
- 视频存储:生成的视频可能在一定时间后过期
- 文件大小:最大视频大小为 500MB
- 时长:最大视频时长为 10 秒
- 输入视频:必须是可公开访问的 URL
- 处理时间:视频生成可能需要几分钟
支持的参数
核心参数
| 参数 | 类型 | 描述 | 必填 |
|---|---|---|---|
prompt | string | 必填。视频修改的文本描述 | ✓ |
videoUrl | string | 必填。用于修改的输入视频 URL | ✓ |
可选参数
| 参数 | 类型 | 描述 | 默认值 |
|---|---|---|---|
callBackUrl | string | Webhook 通知 URL | - |
watermark | string | 水印标识符 | - |
下一步
支持
需要帮助?以下是您的选择:- 技术支持:[email protected]
- API 状态:监控服务健康和公告
- 文档:探索详细的 API 参考
- 社区:加入我们的开发者社区获取提示和示例
