随着 AI 视频生成技术的爆发,越来越多的开发者希望将高质量的视频生成能力集成到自己的项目中。本文将详细介绍如何对接基于 6ai.chat 提供的 Sora-2 及 Sora-2-pro 视频生成 API,并提供完整的 Python 和 Node.js 封装代码,帮助大家实现开箱即用。
⚠️ 郑重声明: 本文仅供技术交流与学习,API 接口需合法合规使用,生成内容必须严格遵守国家相关法律法规,禁止用于任何非法用途。
在 AI 视频生成领域,sora-2 模型凭借出色的动画效果成为热门选择。本文将通过**"准备工作 - 参数配置 - 代码调用"**三步,带您快速完成 sora-2 模型对接。
同时推荐使用稳定高效的 AI 服务平台:小鲸 AI 开放平台(支持多模型一键切换,注册即送 0.2 刀,提供实时 API 监控)。
一、 核心基础信息
在开始敲代码之前,我们需要先了解接口的基础配置:
- 基础 URL :https://open.xiaojingai.com/v1
- 请求方式 :所有接口均采用
POST方法 - 鉴权方式:Bearer Token
通用 Header 参数:
| 参数名 | 类型 | 示例值 | 说明 |
|---|---|---|---|
Content-Type |
string | application/json |
必填,请求体格式 |
Accept |
string | application/json |
必填,响应体格式 |
Authorization |
string | Bearer {``{YOUR_API_KEY}} |
强烈建议携带,提升请求优先级和权限 |
二、 视频生成接口(异步)
接口地址 :/v1/video/create
核心功能:支持图生视频、文生视频,支持调整视频分辨率和横竖屏。
1. 模型差异与参数说明
该接口支持 sora-2 和升级版的 sora-2-pro,参数要求略有不同:
| 参数名 | 必填 | 说明 | 模型差异 |
|---|---|---|---|
images |
是 | 图片链接数组。文生视频传空数组 [] |
无 |
model |
是 | 模型名称 | sora-2 或 sora-2-pro |
orientation |
是 | 视频方向 | portrait(竖屏) / landscape(横屏) |
prompt |
是 | 提示词,如 make animate |
无 |
size |
是 | 视频分辨率 | sora-2 支持 small(默认720p)/large; sora-2-pro 仅支持 large(1080p) |
duration |
是 | 视频时长 | sora-2 枚举值 10;sora-2-pro 支持 15 |
2. cURL 请求示例
示例 A:使用 Sora-2 生成竖屏动画
python
curl --location --request POST 'https://open.xiaojingai.com/v1/video/create' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {{YOUR_API_KEY}}' \
--header 'Content-Type: application/json' \
--data-raw '{
"images": ["https://filesystem.site/cdn/20250612/VfgB5ubjInVt8sG6rzMppxnu7gEfde.png"],
"model": "sora-2",
"orientation": "portrait",
"prompt": "make animate",
"size": "small",
"duration": 10
}'
示例 B:使用 Sora-2-pro 生成横屏高清
python
curl --location --request POST 'https://open.xiaojingai.com/v1/video/create' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {{YOUR_API_KEY}}' \
--header 'Content-Type: application/json' \
--data-raw '{
"images": [],
"model": "sora-2-pro",
"orientation": "landscape",
"prompt": "make animate",
"size": "large",
"duration": 15
}'
3. 异步响应说明 💡
注意:视频生成是耗时任务,接口为异步返回! 请求成功后,系统会返回类似如下结构(包含任务 id 和 pending 状态):
python
{
"id": "sora-2:task_01k6x15vhrff09dkkqjrzwhm60",
"status": "pending",
"status_update_time": 1759763427208
}
开发建议:拿到任务 id 后,业务层需要通过轮询任务查询接口或 Webhook 回调机制,等待状态变为 complete 后再提取实际的视频播放地址。
三、 Chat 对话生成接口
如果您希望通过类似 ChatGPT 的对话方式(Tool Calling)来触发视频生成,可以使用标准的 Completions 接口。
接口地址 :/v1/chat/completions
python
{
"model": "sora-2",
"max_tokens": 1000,
"messages": [
{
"role": "user",
"content": "an astronaut golden retriever named Sora levitates around an intergalactic pup-themed space station"
}
],
"tools": ["function:generate_animate"],
"tool_choice": {"type":"function","function":{"name":"generate_animate"}},
"stream": true
}
四、 实战:一键接入 SDK 源码 🚀
为了避免大家重复造轮子,这里直接提供封装好的客户端代码。
🐍 Python 版本实现
依赖库:pip install requests
python
import requests
import json
from typing import List, Dict
class SoraAPIClient:
def __init__(self, api_key: str):
self.base_url = "https://open.xiaojingai.com/v1"
self.headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {api_key}"
}
def create_video(self, prompt: str, model: str = "sora-2",
images: List[str] = None, orientation: str = "portrait",
size: str = "small", duration: int = 10) -> dict:
"""异步生成视频请求"""
url = f"{self.base_url}/video/create"
payload = {
"images": images if images else [],
"model": model,
"orientation": orientation,
"prompt": prompt,
"size": size,
"duration": duration
}
try:
response = requests.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}
def chat_completion(self, messages: List[Dict], tools: List[str] = None,
tool_choice: Dict = None, stream: bool = False,
max_tokens: int = 1000) -> dict:
"""Chat 格式对话生成"""
url = f"{self.base_url}/chat/completions"
payload = {
"model": "sora-2",
"messages": messages,
"stream": stream,
"max_tokens": max_tokens
}
if tools: payload["tools"] = tools
if tool_choice: payload["tool_choice"] = tool_choice
try:
response = requests.post(url, headers=self.headers, json=payload, stream=stream)
response.raise_for_status()
if stream:
for line in response.iter_lines():
if line: print(line.decode('utf-8')) # 流式打印处理
return {"status": "stream_completed"}
return response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}
# ================= 测试调用 =================
if __name__ == "__main__":
client = SoraAPIClient(api_key="YOUR_API_KEY")
# 1. 提交 Sora-2-pro 视频任务
res = client.create_video(
prompt="make animate", model="sora-2-pro",
orientation="landscape", size="large", duration=15
)
print("视频任务返回:", json.dumps(res, indent=2, ensure_ascii=False))
☕ Node.js (JavaScript) 版本实现
推荐在 Node 18+ 环境下使用原生 fetch:
python
class SoraAPIClient {
constructor(apiKey) {
this.baseUrl = "https://open.xiaojingai.com/v1";
this.headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": `Bearer ${apiKey}`
};
}
async createVideo({ prompt, model = "sora-2", images = [], orientation = "portrait", size = "small", duration = 10 }) {
const payload = { images, model, orientation, prompt, size, duration };
try {
const response = await fetch(`${this.baseUrl}/video/create`, {
method: "POST", headers: this.headers, body: JSON.stringify(payload)
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
} catch (error) {
console.error("Video creation failed:", error);
throw error;
}
}
// 省略 Chat 方法(可参考上文逻辑,结构类似)
}
// ================= 测试调用 =================
(async () => {
const client = new SoraAPIClient("YOUR_API_KEY");
const videoRes = await client.createVideo({
prompt: "make animate",
images: ["https://filesystem.site/cdn/20250612/VfgB5ubjInVt8sG6rzMppxnu7gEfde.png"],
orientation: "portrait",
size: "small",
duration: 10
});
console.log("视频任务结果:", videoRes);
})();
五、 总结与排坑指南
- 严格校验参数必填项 :文档中标记为"必填"的字段一个都不能少,否则极其容易触发 400 Bad Request。尤其是
images字段,即使是文生视频,也要老老实实传个空数组[]。 - 分辨率与模型绑定 :
sora-2-pro不要尝试传small,它只接large高清局! - 闭环任务查询 :再次强调,
create接口只返回任务 ID。对接时切记向接口服务商要到查询进度/结果 的接口(如/v1/video/status),通过定时器(如每 10 秒查询一次)来获取最终的视频 URL。
希望这篇文章能帮大家在 AIGC 的开发路上少走弯路!如果有任何对接上的疑问,欢迎在评论区留言讨论。👇
标签:#AIGC #API对接 #Python #NodeJS #Sora