Sora-2 & Sora-2-pro 视频生成 API 对接指南(附 Python/Node.js 完整源码)

随着 AI 视频生成技术的爆发,越来越多的开发者希望将高质量的视频生成能力集成到自己的项目中。本文将详细介绍如何对接基于 6ai.chat 提供的 Sora-2Sora-2-pro 视频生成 API,并提供完整的 Python 和 Node.js 封装代码,帮助大家实现开箱即用。

⚠️ 郑重声明: 本文仅供技术交流与学习,API 接口需合法合规使用,生成内容必须严格遵守国家相关法律法规,禁止用于任何非法用途。

在 AI 视频生成领域,sora-2 模型凭借出色的动画效果成为热门选择。本文将通过**"准备工作 - 参数配置 - 代码调用"**三步,带您快速完成 sora-2 模型对接。

同时推荐使用稳定高效的 AI 服务平台:小鲸 AI 开放平台(支持多模型一键切换,注册即送 0.2 刀,提供实时 API 监控)。

一、 核心基础信息

在开始敲代码之前,我们需要先了解接口的基础配置:

通用 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-2sora-2-pro
orientation 视频方向 portrait(竖屏) / landscape(横屏)
prompt 提示词,如 make animate
size 视频分辨率 sora-2 支持 small(默认720p)/largesora-2-pro 仅支持 large(1080p)
duration 视频时长 sora-2 枚举值 10sora-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. 异步响应说明 💡

注意:视频生成是耗时任务,接口为异步返回! 请求成功后,系统会返回类似如下结构(包含任务 idpending 状态):

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);
})();

五、 总结与排坑指南

  1. 严格校验参数必填项 :文档中标记为"必填"的字段一个都不能少,否则极其容易触发 400 Bad Request。尤其是 images 字段,即使是文生视频,也要老老实实传个空数组 []
  2. 分辨率与模型绑定sora-2-pro 不要尝试传 small,它只接 large 高清局!
  3. 闭环任务查询 :再次强调,create 接口只返回任务 ID。对接时切记向接口服务商要到查询进度/结果 的接口(如 /v1/video/status),通过定时器(如每 10 秒查询一次)来获取最终的视频 URL。

希望这篇文章能帮大家在 AIGC 的开发路上少走弯路!如果有任何对接上的疑问,欢迎在评论区留言讨论。👇


标签:#AIGC #API对接 #Python #NodeJS #Sora

相关推荐
Hoper.J1 小时前
目前 Claude / GPT 的订阅建议与反代避坑
gpt·claude·反代
FreeBuf_2 小时前
OpenAI发布GPT-5.4-Cyber强化网安防御,与Anthropic展开AI攻防竞赛
人工智能·gpt
weitingfu21 小时前
从 BERT 到 GPT 再到 Mamba:LLM 架构的“三国演义“
人工智能·gpt·大模型·bert·mamba·上下文·实战指南
AI周红伟21 小时前
《智能体应用交付实操:OpenClaw+Skills+RAG+Agent智能体应用案例实操和智能体交付的方案设计》
大数据·数据库·人工智能·科技·gpt·深度学习·openclaw
AIBox3651 天前
vscode api 配置怎么做:第三方大模型接入 VS Code 的完整方法
ide·人工智能·vscode·gpt·语言模型·编辑器
xixixi777771 天前
智算中心建设新范式:GPT-6/Rubin架构+1.6T光模块+量子安全网关+AI安全沙箱,算力·效率·安全·成本的最优平衡
人工智能·gpt·安全·机器学习·架构·大模型·通信
人道领域1 天前
GPT-5架构泄露?Kubernetes 1.31发布与Rust重构浪潮下的云原生之变
gpt·云原生·架构
Aaron_Chou3131 天前
保姆级codex配置教程
gpt·ai·agent·ai编程·codex
ofoxcoding2 天前
GPT-5.4 mini API 实测:和 Claude 4.6、DeepSeek V3、Qwen 3 打了一圈,结果出乎意料
gpt·ai