KL

klingai-video-extension

Automates the process of extending existing videos by appending new footage through the Kling AI API.

Install

mkdir -p .claude/skills/klingai-video-extension && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/8791" && unzip -o skill.zip -d .claude/skills/klingai-video-extension && rm skill.zip

Installs to .claude/skills/klingai-video-extension

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Extend video duration using Kling AI continuation. Use when creating
68 chars✓ has a “when” trigger
Intermediate

Key capabilities

  • Extend existing Kling AI video clips
  • Chain multiple video extensions together
  • Specify motion/scene descriptions for extensions
  • Set duration and mode for extended segments
  • Poll for completion of video extension tasks

How it works

The skill sends a POST request to the Kling AI video-extend endpoint with the task ID of a completed video and new parameters. It then polls the API until the extension task succeeds, providing the URL of the new video.

Inputs & outputs

You give it
Task ID of a completed Kling AI video, optional prompt, duration, mode, and model name
You get back
Task ID of the video extension and, upon completion, the URL of the extended video

When to use klingai-video-extension

  • Extend video duration from existing clips
  • Build seamless video sequences
  • Automate motion generation for longer segments
  • Integrate Kling AI video continuation into workflows

About this skill

Kling AI Video Extension

Overview

Extend an existing video by appending additional seconds. The extension endpoint takes the task_id of a completed video and generates a seamless continuation.

Endpoint: POST https://api.klingai.com/v1/videos/video-extend

Request Parameters

ParameterTypeRequiredDescription
task_idstringYesTask ID of the completed source video
promptstringNoMotion/scene description for extension
durationstringNoExtension length: "5" (default)
modestringNo"standard" or "professional"
model_namestringNoDefault: "kling-v2-master"
callback_urlstringNoWebhook for completion

Basic Extension

import jwt, time, os, requests

BASE = "https://api.klingai.com/v1"

def get_headers():
    ak, sk = os.environ["KLING_ACCESS_KEY"], os.environ["KLING_SECRET_KEY"]
    token = jwt.encode(
        {"iss": ak, "exp": int(time.time()) + 1800, "nbf": int(time.time()) - 5},
        sk, algorithm="HS256", headers={"alg": "HS256", "typ": "JWT"}
    )
    return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}

# Step 1: Generate the initial 5s video
initial = requests.post(f"{BASE}/videos/text2video", headers=get_headers(), json={
    "model_name": "kling-v2-master",
    "prompt": "A rocket launching from a desert landscape, cinematic",
    "duration": "5",
    "mode": "standard",
}).json()
initial_task_id = initial["data"]["task_id"]

# Wait for completion...
# (poll until task_status == "succeed")

# Step 2: Extend by 5 more seconds
extension = requests.post(f"{BASE}/videos/video-extend", headers=get_headers(), json={
    "task_id": initial_task_id,
    "prompt": "The rocket ascends through clouds into the stratosphere",
    "duration": "5",
    "mode": "standard",
}).json()
ext_task_id = extension["data"]["task_id"]

# Step 3: Poll extension task
while True:
    time.sleep(15)
    result = requests.get(
        f"{BASE}/videos/video-extend/{ext_task_id}", headers=get_headers()
    ).json()
    if result["data"]["task_status"] == "succeed":
        extended_url = result["data"]["task_result"]["videos"][0]["url"]
        print(f"Extended video: {extended_url}")
        break
    elif result["data"]["task_status"] == "failed":
        print(f"Failed: {result['data']['task_status_msg']}")
        break

Chain Multiple Extensions

def chain_extensions(initial_task_id: str, prompts: list[str],
                     duration: str = "5", mode: str = "standard") -> list[str]:
    """Chain multiple extensions to build a longer video."""
    current_task_id = initial_task_id
    video_urls = []

    for i, prompt in enumerate(prompts):
        print(f"Extension {i + 1}/{len(prompts)}: submitting...")

        # Submit extension
        r = requests.post(f"{BASE}/videos/video-extend", headers=get_headers(), json={
            "task_id": current_task_id,
            "prompt": prompt,
            "duration": duration,
            "mode": mode,
        }).json()
        ext_task_id = r["data"]["task_id"]

        # Poll for completion
        while True:
            time.sleep(15)
            result = requests.get(
                f"{BASE}/videos/video-extend/{ext_task_id}", headers=get_headers()
            ).json()
            status = result["data"]["task_status"]

            if status == "succeed":
                url = result["data"]["task_result"]["videos"][0]["url"]
                video_urls.append(url)
                current_task_id = ext_task_id  # next extension chains from this
                print(f"Extension {i + 1} complete: {url}")
                break
            elif status == "failed":
                raise RuntimeError(f"Extension {i + 1} failed: {result['data']['task_status_msg']}")

    return video_urls

Usage: Build a 20-Second Video

# Generate initial 5s
initial_r = requests.post(f"{BASE}/videos/text2video", headers=get_headers(), json={
    "model_name": "kling-v2-master",
    "prompt": "Morning sunrise over a mountain lake, mist rising",
    "duration": "5",
    "mode": "standard",
}).json()
initial_id = initial_r["data"]["task_id"]
# ... poll until complete ...

# Chain 3 more extensions = 5 + 5 + 5 + 5 = 20 seconds total
extensions = chain_extensions(initial_id, [
    "Sun rises higher, birds begin flying across the lake",
    "A deer approaches the water's edge to drink",
    "Wide shot pulling back to reveal the full mountain range",
])

Cost

Each extension costs the same as a new generation:

Extension DurationStandardProfessional
5 seconds10 credits35 credits

A 20-second video (initial + 3 extensions) costs 40 credits in standard mode.

Error Handling

ErrorCauseFix
Invalid task_idSource task doesn't existVerify task_id is from a completed generation
Source not completeExtending a task still processingWait for source task to reach succeed status
Extension failedPrompt conflict with sourceAlign extension prompt with original scene

Resources

When not to use it

  • When video continuation is not required
  • When the initial video task has not yet succeeded

Limitations

  • Each extension costs credits, similar to a new generation
  • The source task ID must be from a completed video generation
  • Extension prompts should align with the original scene to avoid failure

How it compares

This skill programmatically extends video duration by chaining API calls, which automates the process of creating longer videos from shorter clips compared to manual generation.

Compared to similar skills

klingai-video-extension side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
klingai-video-extension (this skill)027dCautionIntermediate
motion-canvas586moReviewAdvanced
jianying-editor382moReviewAdvanced
manim296moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

motion-canvas

davila7

Complete production-ready guide for Motion Canvas with ESM/CommonJS workarounds, full setup templates, and troubleshooting for programmatic video creation using TypeScript

58202

jianying-editor

luoluoluo22

剪映 (JianYing) AI自动化剪辑的高级封装 API (JyWrapper)。提供开箱即用的 Python 接口,支持录屏、素材导入、字幕生成、Web 动效合成及项目导出。

38110

manim

davila7

Comprehensive guide for Manim Community - Python framework for creating mathematical animations and educational videos with programmatic control

29113

vectcut-api

sun-guannan

VectCutAPI is a powerful cloud-based video editing API tool that provides programmatic control over CapCut/JianYing (剪映) for professional video editing. Use this skill when users need to: (1) Create video draft projects programmatically, (2) Add video/audio/image materials with precise control, (3) Add text, subtitles, and captions, (4) Apply effects, transitions, and animations, (5) Add keyframe animations, (6) Process videos in batch, (7) Generate AI-powered videos, (8) Integrate with n8n workflows, (9) Build MCP video editing agents. The API supports HTTP REST and MCP protocols, works with both CapCut (international) and JianYing (China), and provides web preview without downloading.

1173

remotion

davila7

Best practices and comprehensive guide for Remotion - programmatic video creation in React with animations, compositions, and media handling

2952

heygen-best-practices

davila7

Best practices for HeyGen - AI avatar video creation API

348

Search skills

Search the agent skills registry