Communitygithub.com

API de Runway ML

API de Runway ML para generación y edición de video con IA — Gen-3 Alpha Turbo, imagen a video y video a video. Úsalo para generar video a partir de texto o imágenes, aplicar efectos de video con IA o automatizar flujos de producción creativa de video.

¿Qué es API de Runway ML?

Esta skill permite a agentes de IA y desarrolladores integrar la API de Runway ML para generar y editar videos de alta calidad usando el modelo Gen-3 Alpha Turbo. Soporta dos modos principales: texto a video (crear clips cinematográficos desde descripciones textuales) e imagen a video (animar imágenes estáticas). La API sigue un patrón asíncrono de tareas: se crea una tarea que devuelve un ID, se consulta periódicamente hasta que finaliza y luego se descarga el resultado. Es útil para automatizar la producción de contenido de video, crear prototipos rápidos de anuncios, generar videos promocionales o integrar capacidades de video en aplicaciones creativas. Funciona con cualquier lenguaje que pueda hacer peticiones HTTP y es compatible con plataformas como Claude Code, Cursor y otras herramientas de IA. Para usarla se necesita una clave API, que se configura mediante la variable de entorno RUNWAY_API_KEY.

Compatible con✓Claude Code✓Codex CLI✓Cursor✓Gemini CLI
npx skills add https://github.com/TerminalSkills/skills/tree/HEAD/skills/runway-ml

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

¿Qué hace API de Runway ML?

Resumen

El modelo Gen-3 Alpha Turbo de Runway genera video de alta calidad a partir de indicaciones de texto o imágenes. La API REST sigue un patrón de tareas asíncronas: crear una tarea, consultar hasta que finalice y luego descargar el resultado. Úsalo para producir clips cinematográficos, animar imágenes o construir pipelines automatizados de contenido de video.

Configuración

pip install requests python-dotenv
export RUNWAY_API_KEY="tu_clave_api_aqui"

URL base: https://api.dev.runwayml.com/v1
Documentación de la API: https://docs.runwayml.com

Conceptos clave

  • Tarea: Un trabajo de generación de video asíncrono. Devuelve inmediatamente un task_id.
  • Gen-3 Alpha Turbo: El modelo Gen-3 más rápido, ideal para pipelines de producción.
  • imagen-a-video (gen3a_turbo): Animar una imagen fija para crear movimiento.
  • texto-a-video: Generar video únicamente a partir de un prompt de texto.
  • Duración: 5 o 10 segundos.
  • Relación de aspecto: 1280:720 (apaisado), 720:1280 (retrato), 1104:832, 832:1104, 960:960 (cuadrado).

Instrucciones

Paso 1: Configurar el cliente

import os
import time
import requests

API_KEY = os.environ["RUNWAY_API_KEY"]
BASE_URL = "https://api.dev.runwayml.com/v1"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    "X-Runway-Version": "2024-11-06"
}

Paso 2: Generación de texto a video

def text_to_video(
    prompt_text: str,
    duration: int = 5,
    ratio: str = "1280:720",
    seed: int = None
) -> str:
    """Envía una tarea de texto a video y devuelve el task_id."""
    payload = {
        "model": "gen3a_turbo",
        "promptText": prompt_text,
        "duration": duration,
        "ratio": ratio
    }
    if seed is not None:
        payload["seed"] = seed

    r = requests.post(f"{BASE_URL}/image_to_video", json=payload, headers=HEADERS)
    r.raise_for_status()
    return r.json()["id"]

task_id = text_to_video(
    prompt_text="Un dron volando sobre un valle montañoso brumoso durante la hora dorada, cinematográfico, cámara lenta",
    duration=5,
    ratio="1280:720"
)
print(f"Tarea enviada: {task_id}")

Paso 3: Generación de imagen a video

import base64
from pathlib import Path

def image_to_video(
    image_path: str,
    prompt_text: str = "",
    duration: int = 5,
    ratio: str = "1280:720",
    seed: int = None
) -> str:
    """Anima una imagen para convertirla en video. image_path puede ser un archivo local o una URL."""

    if image_path.startswith("http"):
        prompt_image = image_path
    else:
        # Codificar archivo local como data URI
        img_bytes = Path(image_path).read_bytes()
        ext = Path(image_path).suffix.lstrip(".").lower()
        mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp"}.get(ext, "image/png")
        b64 = base64.b64encode(img_bytes).decode()
        prompt_image = f"data:{mime};base64,{b64}"

    payload = {
        "model": "gen3a_turbo",
        "promptImage": prompt_image,
        "promptText": prompt_text,
        "duration": duration,
        "ratio": ratio
    }
    if seed is not None:
        payload["seed"] = seed

    r = requests.post(f"{BASE_URL}/image_to_video", json=payload, headers=HEADERS)
    r.raise_for_status()
    return r.json()["id"]

task_id = image_to_video(
    image_path="product_shot.png",
    prompt_text="El producto gira lentamente, partículas brillantes flotan a su alrededor, sensación de lujo",
    duration=5,
    ratio="1280:720"
)
print(f"Tarea enviada: {task_id}")

Paso 4: Consultar el estado de la tarea

def get_task(task_id: str) -> dict:
    r = requests.get(f"{BASE_URL}/tasks/{task_id}", headers=HEADERS)
    r.raise_for_status()
    return r.json()

def wait_for_task(task_id: str, poll_interval: int = 5, timeout: int = 600) -> list[str]:
    """Consulta hasta que la tarea se complete; devuelve una lista de URLs de video de salida."""
    start = time.time()
    while True:
        task = get_task(task_id)
        status = task["status"]
        progress = task.get("progress", 0)
        print(f"[{int(time.time()-start)}s] Estado: {status} ({int(progress*100)}%)")

        if status == "SUCCEEDED":
            return task["output"]  # lista de URLs de video
        elif status in ("FAILED", "CANCELLED"):
            raise RuntimeError(f"Tarea {status}: {task.get('failure', '')}")
        elif time.time() - start > timeout:
            raise TimeoutError(f"La tarea no ha finalizado después de {timeout}s")

        time.sleep(poll_interval)

output_urls = wait_for_task(task_id)
print(f"Video(s) listo(s): {output_urls}")

Paso 5: Descargar el resultado

def download_video(url: str, output_path: str = "output.mp4") -> str:
    r = requests.get(url, stream=True)
    r.raise_for_status()
    with open(output_path, "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)
    size_mb = os.path.getsize(output_path) / 1024 / 1024
    print(f"Guardado: {output_path} ({size_mb:.1f} MB)")
    return output_path

download_video(output_urls[0], "mountain_valley.mp4")

Ejemplo de pipeline completo

def generate_and_download(prompt: str, output_path: str = "output.mp4", **kwargs) -> str:
    """Un solo paso: generar video desde texto y descargarlo."""
    print(f"Generando: {prompt[:80]}...")
    task_id = text_to_video(prompt, **kwargs)
    urls = wait_for_task(task_id)
    return download_video(urls[0], output_path)

# Generar un clip de anuncio de producto
generate_and_download(
    prompt="Primer plano de un teléfono inteligente elegante sobre un escritorio blanco, la pantalla se ilumina, suave alejamiento de cámara",
    output_path="product_ad.mp4",
    duration=5,
    ratio="1280:720"
)

Referencia de parámetros

ParámetroValoresDescripción
modelgen3a_turboUsa Gen-3 Alpha Turbo (el más rápido)
duration5, 10Duración del video en segundos
ratio1280:720, 720:1280, 1104:832, 832:1104, 960:960Relación de aspecto de resolución
seedenteroSemilla de reproducibilidad para salidas deterministas
promptTextcadenaPrompt de texto que describe el video deseado
promptImageURL o data URIImagen de inicio para imagen a video

Directrices

  • Las tareas de Runway tardan entre 30 y 120 segundos dependiendo de la duración y la carga.
  • Las URLs de salida caducan después de un tiempo; descarga los videos inmediatamente después de la generación.
  • Mantén los prompts descriptivos y cinematográficos: incluye movimiento de cámara, iluminación, ambiente.
  • Usa seed para reproducir el mismo resultado al iterar sobre prompts.
  • Para generación por lotes, encola las tareas en paralelo pero respeta los límites de velocidad (verifica HTTP 429 y reintenta después del valor del encabezado Retry-After).
  • Almacena las claves API en variables de entorno, nunca las codifiques en el código.
  • Consulta https://docs.runwayml.com para ver los nombres y endpoints de modelos más recientes, ya que evolucionan rápidamente.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

TerminalSkills/skills

>- Run GitHub Actions locally with act. Use when a user asks to test GitHub Actions workflows locally, debug CI pipelines without pushing, or run workflows offline.

TerminalSkills/skills

>- You are an expert in AG2 (formerly AutoGen), the open-source multi-agent conversation framework. You help developers build systems where multiple AI agents collaborate through structured conversations — with tool use, human-in-the-loop, code execution, group chat orchestration, and nested conversations — for complex tasks like software development, research, and data analysis.

TerminalSkills/skills

>- Generate short-form videos with AI — script writing, text-to-speech narration, stock footage selection, subtitle generation, and video assembly. Use when: creating TikTok/YouTube Shorts/Reels content, automating video production, building content pipelines.

TerminalSkills/skills

>- Animate 3D objects and characters in Blender with Python. Use when the user wants to keyframe properties, create armatures and rigs, set up IK/FK chains, animate shape keys for facial animation, edit F-Curves, use the NLA editor to blend actions, add drivers for expression-based animation, or script any animation workflow in Blender.

TerminalSkills/skills

>- Automate motion capture and tracking workflows in Blender with Python. Use when the user wants to import BVH or FBX mocap data, retarget motion to armatures, track camera or object motion from video, solve camera motion, clean up motion capture data, or script any tracking pipeline in Blender.

TerminalSkills/skills

>- You are an expert in Bolt.new by StackBlitz, the AI-powered full-stack development environment that runs entirely in the browser. You help developers go from idea to deployed app in minutes using natural language prompts — Bolt generates complete applications with frontend, backend, database, and deployment, all running in a WebContainer without local setup.

TerminalSkills/skills

>- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime.

TerminalSkills/skills

>- Self-host customer support with Chatwoot. Use when a user asks to set up open-source customer support, add live chat without SaaS costs, build a multi-channel inbox, or deploy a free Intercom alternative.

TerminalSkills/skills

>- You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on `net/http`. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.

TerminalSkills/skills

When the user wants to edit, review, or improve existing marketing copy. Also use when the user mentions 'edit this copy,' 'review my copy,' 'copy feedback,' 'proofread,' 'polish this,' 'make this better,' or 'copy sweep.' This skill provides a systematic approach to editing marketing copy through multiple focused passes.

TerminalSkills/skills

>- Add live chat and customer support with Crisp. Use when a user asks to add a chat widget, implement live customer support, set up a help desk, create a knowledge base, or add a chatbot to a website.

TerminalSkills/skills

>- Assists with building custom interactive data visualizations using D3.js. Use when creating charts, graphs, maps, force layouts, or hierarchical diagrams that require fine-grained control beyond what charting libraries provide. Trigger words: d3, data visualization, chart, svg, scales, force graph, treemap, choropleth.

TerminalSkills/skills

dbt (data build tool) transforms data in your warehouse using SQL SELECT statements. Learn project setup, models, tests, documentation, incremental materializations, and integration with data warehouses like PostgreSQL, BigQuery, and Snowflake.

TerminalSkills/skills

>- You are an expert in dlt, the open-source Python library for building data pipelines. You help developers load data from any API, file, or database into warehouses and lakes using simple Python decorators — with automatic schema inference, incremental loading, and built-in data contracts. dlt is the "requests library for data pipelines.

TerminalSkills/skills

Data Version Control for ML projects. Track large datasets and models alongside Git, build reproducible ML pipelines, and run experiments with metric comparison. Works with any storage backend including S3, GCS, Azure, and local filesystems.

TerminalSkills/skills

>- You are an expert in E2B, the cloud platform for running AI-generated code in secure sandboxes. You help developers give AI agents the ability to execute code, install packages, read/write files, and run long processes in isolated cloud environments — each sandbox is a lightweight VM that boots in ~150ms with full Linux, filesystem, and networking.

TerminalSkills/skills

>- Transcode, convert, edit, and process audio and video with FFmpeg. Use when a user asks to convert video formats (webm to mp4, mkv to mp4), extract audio from video, compress video files, trim or cut clips, concatenate videos, add subtitles, create thumbnails, apply filters, change resolution or bitrate, re-encode media, create GIFs from video, add watermarks, normalize audio, stream media, or build automated media processing pipelines.

TerminalSkills/skills

>- Create advanced animations with GSAP. Use when building complex timelines, scroll-driven animations, SVG morphing, text animations, or high-performance web animations beyond CSS capabilities.

TerminalSkills/skills

>- Generate deterministic MP4 videos from HTML, CSS, media, and seekable animations using HeyGen's HyperFrames framework. Use when someone asks to "render HTML to video", "make a video with HyperFrames", "create a programmatic video", "turn an animation into MP4", "build a launch/product video from HTML", "render GSAP/Lottie/Three.js to video", or set up an agent-driven video pipeline. Covers init/preview/render/add/lint/inspect commands, data-* timing attributes, animation adapters, and the component catalog.

TerminalSkills/skills

When the user wants to perform load testing, stress testing, or performance testing of APIs and websites using k6. Also use when the user mentions "k6," "load test," "performance test," "stress test," "spike test," "soak test," "thresholds," "virtual users," or "VUs." For browser-based testing, see selenium.

Skills relacionados