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

张开发
2026/4/17 19:15:09 15 分钟阅读

分享文章

Sora-2  Sora-2-pro 视频生成 API 对接指南(附 Python/Node.js 完整源码)
随着 AI 视频生成技术的爆发越来越多的开发者希望将高质量的视频生成能力集成到自己的项目中。本文将详细介绍如何对接基于6ai.chat提供的Sora-2及Sora-2-pro视频生成 API并提供完整的 Python 和 Node.js 封装代码帮助大家实现开箱即用。⚠️ 郑重声明本文仅供技术交流与学习API 接口需合法合规使用生成内容必须严格遵守国家相关法律法规禁止用于任何非法用途。在 AI 视频生成领域sora-2模型凭借出色的动画效果成为热门选择。本文将通过**“准备工作 - 参数配置 - 代码调用”**三步带您快速完成sora-2模型对接。同时推荐使用稳定高效的 AI 服务平台小鲸 AI 开放平台支持多模型一键切换注册即送 0.2 刀提供实时 API 监控。一、 核心基础信息在开始敲代码之前我们需要先了解接口的基础配置基础 URLhttps://open.xiaojingai.com/v1请求方式所有接口均采用POST方法鉴权方式Bearer Token通用 Header 参数参数名类型示例值说明Content-Typestringapplication/json必填请求体格式Acceptstringapplication/json必填响应体格式AuthorizationstringBearer {{YOUR_API_KEY}}强烈建议携带提升请求优先级和权限二、 视频生成接口异步接口地址/v1/video/create核心功能支持图生视频、文生视频支持调整视频分辨率和横竖屏。1. 模型差异与参数说明该接口支持sora-2和升级版的sora-2-pro参数要求略有不同参数名必填说明模型差异images是图片链接数组。文生视频传空数组[]无model是模型名称sora-2或sora-2-proorientation是视频方向portrait(竖屏) /landscape(横屏)prompt是提示词如make animate无size是视频分辨率sora-2支持small(默认720p)/largesora-2-pro仅支持large(1080p)duration是视频时长sora-2枚举值10sora-2-pro支持152. cURL 请求示例示例 A使用 Sora-2 生成竖屏动画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 生成横屏高清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状态{ id: sora-2:task_01k6x15vhrff09dkkqjrzwhm60, status: pending, status_update_time: 1759763427208 }开发建议拿到任务id后业务层需要通过轮询任务查询接口或 Webhook 回调机制等待状态变为complete后再提取实际的视频播放地址。三、 Chat 对话生成接口如果您希望通过类似 ChatGPT 的对话方式Tool Calling来触发视频生成可以使用标准的 Completions 接口。接口地址/v1/chat/completions{ 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 requestsimport 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: fBearer {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, headersself.headers, jsonpayload) 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, headersself.headers, jsonpayload, streamstream) 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_keyYOUR_API_KEY) # 1. 提交 Sora-2-pro 视频任务 res client.create_video( promptmake animate, modelsora-2-pro, orientationlandscape, sizelarge, duration15 ) print(视频任务返回:, json.dumps(res, indent2, ensure_asciiFalse))☕ Node.js (JavaScript) 版本实现推荐在 Node 18 环境下使用原生fetchclass 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

更多文章