OpenAI Videos API:Sora 2 视频生成 Python 调用指南

Python 调用示例

from openai import OpenAI

client = OpenAI(api_key="YOUR_API_KEY")

# 提交视频生成任务(异步)
job = client.videos.create(
    model="sora-2",
    prompt="""
A cinematic drone shot of Tokyo at night.
Neon lights reflecting on wet streets.
Ultra realistic.
""",
    seconds=8,
    size="1280x720"
)

print(job.id)

视频生成是异步任务,需要轮询状态:

import time

while True:
    result = client.videos.retrieve(job.id)
    print(result.status)

    if result.status == "completed":
        print(result.output_url)
        break
    elif result.status == "failed":
        print("生成失败")
        break

    time.sleep(5)

图片转视频

已有参考图片时,使用 input_reference 保持人物和风格一致:

job = client.videos.create(
    model="sora-2",
    prompt="The girl smiles and walks forward.",
    input_reference=open("girl.png", "rb"),
    seconds=8
)

REST API

curl https://api.openai.com/v1/videos \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "model=sora-2" \
  -F "prompt=A cute panda drinking coffee" \
  -F "seconds=8"

参数说明

参数说明
modelsora-2sora-2-pro
prompt视频内容描述(英文效果更好)
input_reference参考图片(可选,用于图生视频)
seconds视频时长:4、8、12 秒
size分辨率,如 1280x720720x1280(竖屏)、1792x1024

价格

模型价格
Sora 2约 $0.10 / 秒
Sora 2 Pro约 $0.30~$0.70 / 秒(随分辨率变化)

生成 8 秒 1280x720 视频:Sora 2 约 $0.80,Sora 2 Pro 约 $2.40~5.60。

Prompt 写法参考

视频 prompt 建议包含:镜头类型、光线、风格、质量要求。

# 电影风格
A cinematic shot of a samurai walking through a bamboo forest.
Golden sunlight. Slow motion. 35mm film. Ultra realistic.

# 产品广告
A luxury mechanical watch rotating on a black reflective table.
Studio lighting. 8K. Commercial quality.

# 动漫风格
Anime style. Cherry blossoms falling.
Girl running on a school campus. Beautiful sunset. Highly detailed.

英文 prompt 效果稳定,中文可能出现理解偏差。

后端架构(完整平台)

如果需要支持多用户、异步进度追踪,典型架构:

用户请求 → FastAPI → Celery 任务队列 → OpenAI Videos API

                                    Redis 存储 job.id

                              WebSocket 推送进度 → 前端

                                  完成后存储到 OSS/S3