> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pictory.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Extend Video with AI

> Continue an existing video with AI-generated content using the Pictory AI Studio API

This guide shows you how to extend an existing video by generating new content that continues from the end of the original. By providing a video URL and a text prompt, the AI model produces a new video segment that picks up where the original left off. This is useful for building longer narratives, adding follow-up scenes, or expanding short clips.

## What You Will Build

> [card] Video Extension
>
> Continue an existing video with new AI-generated content

> [card] Narrative Building
>
> Add follow-up scenes to develop a story over multiple segments

> [card] Seamless Transitions
>
> The AI model maintains visual continuity from the source video

> [card] Iterative Creation
>
> Extend videos repeatedly to build longer sequences

## Before You Begin

Make sure you have:

* A [Pictory API key](https://app.pictory.ai/api-access)
* Node.js or Python installed on your machine
* The required packages installed
* A publicly accessible URL of the video you want to extend

```bash npm theme={null}
npm install axios
```

```bash pip theme={null}
pip install requests
```

## Step-by-Step Guide

### Step 1: Set Up Your Request

Prepare your API credentials, the source video URL, and a prompt that describes what should happen next in the video.

```javascript Node.js theme={null}
import axios from "axios";

const API_BASE_URL = "https://api.pictory.ai/pictoryapis";
const API_KEY = "YOUR_API_KEY"; // Replace with your actual API key

// Video extension configuration
const videoRequest = {
  prompt: "The woman sits down on the grass as children run and play around her in a wide shot",
  extendVideoUrl: "https://example.com/videos/woman-walking-in-park.mp4",
  model: "pixverse6",
  aspectRatio: "9:16",
  duration: "8s"
};
```

```python Python theme={null}
import requests
import time

API_BASE_URL = "https://api.pictory.ai/pictoryapis"
API_KEY = "YOUR_API_KEY"  # Replace with your actual API key

# Video extension configuration
video_request = {
    "prompt": "The woman sits down on the grass as children run and play around her in a wide shot",
    "extendVideoUrl": "https://example.com/videos/woman-walking-in-park.mp4",
    "model": "pixverse6",
    "aspectRatio": "9:16",
    "duration": "8s"
}
```

> [!NOTE]
>
> The `extendVideoUrl` must point to a publicly accessible video file. This parameter cannot be used together with `firstFrameImageUrl`, `endFrameImageUrl`, or `referenceImageUrls`. Extension is supported by `pixverse6` and `veo3.1`; when you omit `model` on an extension request, `pixverse6` is used.

### Step 2: Submit the Video Extension Request

Send the request to the AI Studio video generation endpoint. The API processes the source video and generates a new segment that continues from it.

```javascript Node.js theme={null}
async function extendVideo() {
  try {
    console.log("Submitting video extension request...");

    const response = await axios.post(
      `${API_BASE_URL}/v1/aistudio/videos`,
      videoRequest,
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: API_KEY,
        },
      }
    );

    const jobId = response.data.data.jobId;
    console.log("Video extension started.");
    console.log("Job ID:", jobId);

    return jobId;
  } catch (error) {
    console.error("Error submitting request:", error.response?.data || error.message);
    throw error;
  }
}
```

```python Python theme={null}
def extend_video():
    try:
        print("Submitting video extension request...")

        response = requests.post(
            f"{API_BASE_URL}/v1/aistudio/videos",
            json=video_request,
            headers={
                "Content-Type": "application/json",
                "Authorization": API_KEY
            }
        )
        response.raise_for_status()

        job_id = response.json()["data"]["jobId"]
        print("Video extension started.")
        print(f"Job ID: {job_id}")

        return job_id

    except requests.exceptions.RequestException as error:
        print(f"Error submitting request: {error}")
        raise
```

### Step 3: Poll for the Result

Check the job status at regular intervals until the extended video is ready.

```javascript Node.js theme={null}
async function waitForVideo(jobId) {
  console.log("\nPolling for video extension result...");

  while (true) {
    const response = await axios.get(
      `${API_BASE_URL}/v1/jobs/${jobId}`,
      {
        headers: { Authorization: API_KEY },
      }
    );

    const data = response.data;
    const status = data.data.status;
    console.log("Status:", status);

    if (status === "completed") {
      console.log("\nVideo extended successfully!");
      console.log("Video URL:", data.data.url);
      console.log("Duration:", data.data.duration);
      console.log("Dimensions:", data.data.width, "x", data.data.height);
      console.log("AI Credits Used:", data.data.aiCreditsUsed);
      return data;
    }

    if (status === "failed") {
      throw new Error("Video extension failed: " + JSON.stringify(data));
    }

    // Wait 15 seconds before polling again
    await new Promise(resolve => setTimeout(resolve, 15000));
  }
}

// Run the complete workflow
extendVideo()
  .then(jobId => waitForVideo(jobId))
  .then(result => console.log("\nDone!"))
  .catch(error => console.error("Error:", error));
```

```python Python theme={null}
def wait_for_video(job_id):
    print("\nPolling for video extension result...")

    while True:
        response = requests.get(
            f"{API_BASE_URL}/v1/jobs/{job_id}",
            headers={"Authorization": API_KEY}
        )
        response.raise_for_status()

        data = response.json()
        status = data["data"]["status"]
        print(f"Status: {status}")

        if status == "completed":
            print("\nVideo extended successfully!")
            print(f"Video URL: {data['data']['url']}")
            print(f"Duration: {data['data']['duration']}")
            print(f"Dimensions: {data['data']['width']} x {data['data']['height']}")
            print(f"AI Credits Used: {data['data']['aiCreditsUsed']}")
            return data

        if status == "failed":
            raise Exception(f"Video extension failed: {data}")

        # Wait 15 seconds before polling again
        time.sleep(15)

# Run the complete workflow
if __name__ == "__main__":
    job_id = extend_video()
    result = wait_for_video(job_id)
    print("\nDone!")
```

## Understanding the Parameters

| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `prompt` | string | Yes | - | A text description of what should happen next in the video. Must be between 5 and 5,000 characters. |
| `extendVideoUrl` | string | No | - | A publicly accessible `http` or `https` URL of the video to extend. Cannot be used together with `firstFrameImageUrl`, `endFrameImageUrl`, or `referenceImageUrls`. |
| `model` | string | No | `pixverse6` | The model to extend with. Only `pixverse6` and `veo3.1` can extend; any other model is rejected with a `400`. See [Generate Video API](https://docs.pictory.ai/api-reference/ai-studio/generate-video.md) for model capabilities and pricing. |
| `aspectRatio` | string | No | `16:9` | Validated against the model's list, but an extension always follows the source video's ratio, so the value has no effect on the output. |
| `duration` | string | No | First supported duration of the selected model | The duration of the new segment. On `pixverse6` any of `5s`, `8s`, `10s`, `15s`. On `veo3.1` the continuation is a fixed `7s`, which is the only accepted value and the default. |
| `audio` | boolean | No | `false` | Generate synchronized audio with the video. Billed at the model's with-audio rate. Always on for `omni-flash`. See [Generate Video with Audio](https://docs.pictory.ai/guides/ai-studio/video-with-audio.md). |
| `trainingPreset` | string | No | - | `sales-training`, `product-training`, or `soft-skills-training`. Steers prompt enhancement and always turns it on, even when `enhancePrompt` is `false`. |
| `enhancePrompt` | boolean | No | `false` | Set to `true` to rewrite the prompt with the AI enhancer before generation. Off by default: the prompt is sent verbatim. |
| `webhook` | string | No | - | A URL to receive a POST notification when the job completes. Must be a valid URI. |

## Building Multi-Segment Videos

You can extend videos iteratively to build longer sequences. Each extension generates a new video segment that continues from the previous one.

**Example workflow:**

1. Generate the first video segment using a text prompt.
2. Retrieve the video URL from the completed job.
3. Use that URL as the `extendVideoUrl` in a new request with a prompt for the next scene.
4. Repeat to build a multi-segment video.

> [!NOTE]
>
> The delivered file contains the source video followed by the new segment, on every model. On `pixverse6` the output is rendered at 720p in the source video's aspect ratio; on `veo3.1` the continuation is a fixed 7 seconds. Billing is for the requested `duration` only, not the combined length.

## Tips for Extending Videos

* **Describe the transition naturally.** Write your prompt as a continuation of the action. For example, if the source video shows someone walking, your prompt might say "She stops and turns to look at the sunset."
* **Maintain consistency.** Use the same `model` as the original video for the best visual continuity between segments. The aspect ratio follows the source automatically.
* **Keep prompts grounded.** Reference what is happening at the end of the source video. Abrupt changes in subject or setting may produce less coherent results.
* **Plan your narrative.** When building multi-segment sequences, outline the full story before generating. This helps you write prompts that flow naturally from one segment to the next.

## Next Steps

* [Generate Video from Text Prompt](https://docs.pictory.ai/guides/ai-studio/text-to-video.md) to create videos from scratch
* [Generate Video from First Frame](https://docs.pictory.ai/guides/ai-studio/video-from-first-frame.md) to animate from a specific starting image
* [Generate Video from Reference Images](https://docs.pictory.ai/guides/ai-studio/video-from-reference-images.md) to guide generation with reference visuals
* [Generate Video API Reference](https://docs.pictory.ai/api-reference/ai-studio/generate-video.md) for the complete parameter documentation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.