The Concept
The 14+ model problem
Model Categories
| Category | Models | Latency | Failure Mode |
|---|
| LLM | GPT-4, Claude, Llama | 2-30s | Token limit, rate limit |
| Image | FLUX, SDXL, DALL-E | 5-30s | Content policy, NSFW filter |
| Video | Runway, Kling, Veo | 30-180s | Timeout, GPU OOM |
| Audio (TTS) | ElevenLabs | 2-10s | Rate limit, voice not found |
| Music | Suno, Stable Audio | 15-60s | Content policy |
| SFX | Stable Audio Open | 5-15s | Timeout |
| 3D | Tripo, Rodin | 30-180s | Timeout, mesh quality |
| Post-processing | FFmpeg, rembg | 1-10s | File format, memory |
| Quality | CLIP score, FID | 1-5s | Model loading |
| Delivery | S3, CDN | 1-5s | Network, permissions |
The Challenge
Each model has:
- Different API patterns: sync (OpenAI), async polling (fal.ai), WebSocket (ComfyUI)
- Different latencies: 2s (TTS) to 180s (video, 3D)
- Different failure modes: timeout, content policy, rate limit, GPU OOM, quality
- Different costs: $0.001 (TTS) to $0.50 (video)
- Different rate limits: 10 RPM (Suno) to 5000 RPM (OpenAI)
Dependency graphs
Sequential vs Parallel
# Sequential: each step depends on the previous
LLM → Image → Video → Audio → Post-production → Delivery
# Total time: sum of all step times (30s + 10s + 60s + 5s + 10s = 115s)
# Parallel: independent steps run simultaneously
LLM → ┌─ Image → Video ─┐
├─ Audio (TTS) ─┤→ Post-production → Delivery
├─ Music ─┤
└─ SFX ─┘
# Total time: max(parallel branches) + sequential parts
# = max(10+60, 5, 30, 10) + 10 = 70s + 10s = 80s (35% faster)
Building a Dependency Graph
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class PipelineStep:
"""A single step in a generative media pipeline."""
step_id: str
name: str
model: str
category: str # "llm", "image", "video", "audio", etc.
depends_on: list[str] = field(default_factory=list) # Step IDs this depends on
latency_estimate: float = 30.0 # seconds
cost_estimate: float = 0.10 # dollars
can_parallel: bool = True
# Define the pipeline
steps = [
PipelineStep("1", "Generate copy", "GPT-4", "llm", [], 10, 0.05),
PipelineStep("2", "Generate image", "FLUX", "image", ["1"], 15, 0.04),
PipelineStep("3", "Generate video", "Runway", "video", ["2"], 60, 0.50),
PipelineStep("4", "Generate voiceover", "ElevenLabs", "audio", ["1"], 5, 0.01),
PipelineStep("5", "Generate music", "Suno", "music", ["1"], 30, 0.10),
PipelineStep("6", "Generate SFX", "Stable Audio", "sfx", ["2"], 10, 0.02),
PipelineStep("7", "Post-production", "FFmpeg", "post", ["3", "4", "5", "6"], 10, 0.0),
PipelineStep("8", "Quality check", "CLIP", "quality", ["7"], 5, 0.0),
PipelineStep("9", "CDN upload", "S3", "delivery", ["8"], 5, 0.0),
]
Topological Sort (Execution Order)
from collections import defaultdict, deque
def topological_sort(steps: list[PipelineStep]) -> list[str]:
"""Sort steps by dependencies — returns execution order."""
graph = defaultdict(list)
in_degree = defaultdict(int)
for step in steps:
in_degree[step.step_id] = len(step.depends_on)
for dep in step.depends_on:
graph[dep].append(step.step_id)
queue = deque([sid for sid in in_degree if in_degree[sid] == 0])
order = []
while queue:
sid = queue.popleft()
order.append(sid)
for next_sid in graph[sid]:
in_degree[next_sid] -= 1
if in_degree[next_sid] == 0:
queue.append(next_sid)
return order
In a generative media pipeline, which steps can run in parallel?
Steps that don't depend on each other's outputs can run in parallel. Example: after the LLM generates copy (step 1), image generation (step 2, depends on 1), TTS (step 4, depends on 1), music (step 5, depends on 1), and SFX (step 6, depends on 2) can be analyzed: TTS, music, and SFX don't depend on each other → parallel. Video (step 3) depends on image (step 2) → sequential after image. Post-production (step 7) depends on all → after everything. Parallel execution reduces total time by 30-50%.
State management
Tracking Intermediate Outputs
@dataclass
class PipelineState:
"""Track state across pipeline steps."""
pipeline_id: str
steps_completed: dict = field(default_factory=dict) # step_id → output_url
steps_failed: dict = field(default_factory=dict) # step_id → error
current_step: Optional[str] = None
total_cost: float = 0.0
start_time: float = 0.0
def is_step_done(self, step_id: str) -> bool:
return step_id in self.steps_completed
def get_output(self, step_id: str) -> Optional[str]:
return self.steps_completed.get(step_id)
def mark_complete(self, step_id: str, output_url: str, cost: float):
self.steps_completed[step_id] = output_url
self.total_cost += cost
def mark_failed(self, step_id: str, error: str):
self.steps_failed[step_id] = error
Checkpointing
import json
def save_checkpoint(state: PipelineState, path: str = "pipeline_checkpoint.json"):
"""Save pipeline state to disk for resume capability."""
with open(path, "w") as f:
json.dump({
"pipeline_id": state.pipeline_id,
"steps_completed": state.steps_completed,
"steps_failed": state.steps_failed,
"total_cost": state.total_cost,
}, f, indent=2)
def load_checkpoint(path: str = "pipeline_checkpoint.json") -> PipelineState:
"""Load pipeline state from disk."""
with open(path) as f:
data = json.load(f)
return PipelineState(**data)
Failure mode classification
| Failure Type | Example | Action |
|---|
| Transient | API timeout, rate limit | Retry with backoff |
| Content policy | NSFW filter, copyright | Route to alt provider |
| Quality | Low CLIP score, blurry | Regenerate with different params |
| GPU OOM | Out of memory | Reduce batch size, use smaller GPU |
| Fatal | Invalid API key, model deprecated | Alert human, stop pipeline |
def classify_error(error: Exception) -> str:
"""Classify an error to determine the response."""
error_str = str(error).lower()
if "timeout" in error_str or "rate limit" in error_str:
return "transient" # Retry with backoff
elif "content policy" in error_str or "nsfw" in error_str:
return "content_policy" # Route to alt provider
elif "quality" in error_str or "low score" in error_str:
return "quality" # Regenerate with different params
elif "oom" in error_str or "out of memory" in error_str:
return "gpu_oom" # Reduce batch size
else:
return "fatal" # Alert human