agentleFS
roedyrustamroedyrustam/vibes-plug/.cursor/skills/ai-media-generation-expert/SKILL.md

ai-media-generation-expert

Skill129 starsChanged 14 days agoMITView on GitHub

AI media generation: Flux, Sora, Runway, ElevenLabs TTS, and Whisper / Generasi media AI: Flux, Sora, Runway, ElevenLabs TTS, dan Whisper.

  • Reads credentials
  • Sends data out

The file

We split this skill into the rules it gives an agent

6 rules. About 0 are common, 5 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Recommendation: Use Flux 1.1 Pro via Replicate for production quality.

    line 54
  2. Distinctive:

    Recommendation: Use ElevenLabs eleven_v3 for expressive content.

    line 93
  3. Distinctive:

    Async Processing: Always use background jobs (BullMQ, Inngest) for generation tasks >2s.

    line 153
  4. Distinctive:

    Webhook Architecture: Use webhooks for Replicate predictions instead of polling.

    line 154
  5. Very specific:

    Asynchronous Queue Processing Invariant: All media generation requests (image synthesis, video, long-form TTS) with runtime duration $> …

    line 160
  6. Distinctive:

    Dual-Layer Content Safety Gate: Every generation prompt MUST undergo automated safety/NSFW screening before model dispatch, and resulting …

    line 161

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

AI Media Generation Expert (2026 Edition)

English | Bahasa Indonesia


<a name="english"></a>

English

Orchestration & Integration

  • Upstream Orchestrators: Works under brainstorming and zero-to-prod-orchestrator (Phase 5 - Core Feature Development & Media Generation) to integrate multimodal generative pipelines.
  • Downstream Cooperating Skills:
    • ai-llm-integration-expert — Prompt engineering, reasoning model selection, and orchestration chains.
    • file-upload-media-expert — Persistent storage (R2/S3), CDN distribution, and media pipeline handling.
    • sse-websocket-streaming-expert — Progressive image generation streaming and real-time audio playback.
    • async-queue-temporal-expert — Durable background queue execution for long-running video/audio generation.
    • zero-trust-secret-vault — Secure API key rotation and credential vault for Replicate, OpenAI, and ElevenLabs.
    • session-memory-manager — Store generation task metadata, prompt history, and asset references.
  • Cross-Domain Synergy & Subagent Swarm Integration: app-promo-media-expert, voice-ai-realtime-agent, svg-animation-motion-expert

Description

Production-grade guide for integrating AI-powered media generation into web and mobile applications. Covers image generation (Flux 1.1 Pro, SDXL, DALL-E 3), video generation (Sora, Runway Gen-3), text-to-speech (ElevenLabs v3, OpenAI TTS), speech-to-text (Whisper large-v3, Deepgram Nova-3), and voice cloning. Includes async processing patterns, cost optimization, and content safety filtering.

Trigger Conditions

  • Integrating AI image generation (Flux, DALL-E, Stable Diffusion, Midjourney API).
  • Building text-to-speech or speech-to-text features.
  • Implementing voice cloning or AI avatar generation.
  • Adding AI video generation or editing capabilities.
  • Building media processing pipelines with AI models.

Core Architecture

1. Image Generation

Provider Selection Matrix:

ProviderModelSpeedQualityCostBest For
ReplicateFlux 1.1 Pro~3s★★★★★$0.04/imgPhotorealism, text rendering
ReplicateFlux Schnell~1s★★★★$0.003/imgHigh-volume, previews
OpenAIDALL-E 3~5s★★★★$0.04/imgCreative, prompt following
StabilitySDXL Turbo~2s★★★★$0.002/imgSelf-hosted, customization

Recommendation: Use Flux 1.1 Pro via Replicate for production quality. Use Flux Schnell for previews/drafts.

// Image generation with Replicate (Flux)
import Replicate from 'replicate';

const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN });

async function generateImage(prompt: string, options?: {
  width?: number;
  height?: number;
  model?: 'flux-1.1-pro' | 'flux-schnell';
}) {
  const model = options?.model ?? 'flux-1.1-pro';
  const output = await replicate.run(
    `black-forest-labs/${model}`,
    {
      input: {
        prompt,
        width: options?.width ?? 1024,
        height: options?.height ?? 1024,
        num_inference_steps: model === 'flux-schnell' ? 4 : 28,
      },
    }
  );
  return output; // URL to generated image
}

2. Text-to-Speech (TTS)

Provider Selection:

ProviderModelLatencyExpressivenessCost
ElevenLabseleven_v3~500ms★★★★★$0.30/1K chars
ElevenLabseleven_flash_v2_5~200ms★★★★$0.15/1K chars
OpenAItts-1-hd~300ms★★★$0.030/1K chars

Recommendation: Use ElevenLabs eleven_v3 for expressive content. Use eleven_flash_v2_5 for real-time chatbots.

// ElevenLabs TTS streaming
async function textToSpeech(text: string, voiceId: string): Promise<ReadableStream> {
  const response = await fetch(
    `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream`,
    {
      method: 'POST',
      headers: {
        'xi-api-key': process.env.ELEVENLABS_API_KEY!,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        text,
        model_id: 'eleven_v3',
        voice_settings: { stability: 0.5, similarity_boost: 0.75 },
      }),
    }
  );
  return response.body!; // Stream audio chunks
}

3. Speech-to-Text (STT)

// OpenAI Whisper transcription
import OpenAI from 'openai';

const openai = new OpenAI();

async function transcribeAudio(audioFile: File) {
  const transcription = await openai.audio.transcriptions.create({
    file: audioFile,
    model: 'whisper-1',
    response_format: 'verbose_json',
    timestamp_granularities: ['word', 'segment'],
  });
  return transcription;
}

4. Video Generation

// Replicate video generation (async with webhook)
async function generateVideo(prompt: string) {
  const prediction = await replicate.predictions.create({
    model: 'minimax/video-01',
    input: { prompt, duration: 5 },
    webhook: `${process.env.APP_URL}/api/webhooks/replicate`,
    webhook_events_filter: ['completed'],
  });
  return prediction.id; // Poll or wait for webhook
}

5. Production Patterns

  • Async Processing: Always use background jobs (BullMQ, Inngest) for generation tasks >2s.
  • Webhook Architecture: Use webhooks for Replicate predictions instead of polling.
  • Content Safety: Implement NSFW filtering (OpenAI Moderation API, Replicate safety checker).
  • Cost Control: Set per-user daily limits. Cache identical prompts. Use cheaper models for drafts.
  • Storage Pipeline: Generate → upload to S3/R2 → serve via CDN → store URL in DB.

Hard Guardrails (Declarative Invariants)

  • Asynchronous Queue Processing Invariant: All media generation requests (image synthesis, video, long-form TTS) with runtime duration $> 2\text{s}$ MUST run via async durable queues (BullMQ/Inngest/Temporal) or webhooks—never block synchronous HTTP handlers.
  • Dual-Layer Content Safety Gate: Every generation prompt MUST undergo automated safety/NSFW screening before model dispatch, and resulting media URLs must be verified prior to client presentation.
  • Permanent Object Storage Invariant: Generated media MUST NOT rely on ephemeral or temporary vendor URLs (e.g., expiring Replicate or OpenAI download links); assets must be streamed to private object storage (S3/R2) and served via authenticated CDN.
  • Rate-Limiting & Quota Throttling Guard: User generation endpoints MUST enforce atomic quota checks (Redis token bucket or database balance decrement) prior to triggering external model APIs.

Non-Functional Requirements (NFR)

  • Async Dispatch Response: Initial job dispatch ack $\le 100\text{ms}$.
  • Storage Compression: WebP/AVIF output quality $\ge 85$ with modern compression.
  • CDN Distribution TTL: Cached media CDN delivery TTL $\ge 7\text{ days}$.

Sovereign Execution, Token Efficiency & Invariants

DimensionSovereign Mandate & Deterministic Contract
Frontier Model CascadeHigh Fast / Medium / High (Gemini 4 Carbon/Hydrogen/Neon/Argon/Pro, Grok 4.7 High Fast, Claude Sonnet/Opus 5.5, GPT-5.6 Sol)
Availability FallbackGemini 4 (Carbon/Hydrogen/Neon/Argon/Pro) -> Gemini 3.8 Flash; Claude Opus 5.5 -> Claude Opus 4.6 (Zero unhandled missing-model errors)
KV-Cache & Token ProtocolPin static instructions & schemas at prompt prefix (kv-cache-prefix-optimizer); pass surgical CONTEXT_MAP.md slices (<250 tokens/call) during Swarm Fan-Out
SaaT CLI & MCP DispatchCLI: vibes skill exec ai-media-generation-expert <audit|eval|verify|generate|blueprint> / MCP: vibes_skill_dispatch, vibes_ast_query, vibes_compile_cache, vibes_optimize_budget, vibes_verify_gate
NFR & Anti-Slop InvariantsP99 API Gateway Latency < 85ms, OpenAPI 3.1 / TypeSpec strict schema parity, RFC 9457 Problem Details error contracts, Idempotency-Key enforcement; 100% complete zero-placeholder output verified via node scripts/check-anti-slop.js --strict


<a name="bahasa-indonesia"></a>

Bahasa Indonesia

Integrasi Orkestrasi

  • Orkestrator Hulu: Beroperasi di bawah arahan brainstorming dan zero-to-prod-orchestrator (Fase 5 - Pengembangan Fitur Utama & Generasi Media) untuk mengintegrasikan pipeline generatif multimodal.
  • Skill Hilir & Kerja Sama:
    • ai-llm-integration-expert — Rekayasa prompt, pemilihan model penalaran, dan rantai orkestrasi.
    • file-upload-media-expert — Penyimpanan permanen (R2/S3), distribusi CDN, dan pipeline media.
    • sse-websocket-streaming-expert — Streaming generasi gambar progresif dan pemutaran audio real-time.
    • async-queue-temporal-expert — Eksekusi antrean background job untuk generasi video dan audio panjang.
    • zero-trust-secret-vault — Rotasi kunci API aman dan brankas kredensial Replicate, OpenAI, dan ElevenLabs.
    • session-memory-manager — Menyimpan metadata tugas generasi, riwayat prompt, dan referensi aset.
  • Sinergi Lintas Domain & Integrasi Swarm Subagent: app-promo-media-expert, voice-ai-realtime-agent, svg-animation-motion-expert

Deskripsi

Panduan tingkat produksi untuk mengintegrasikan generasi media berbasis AI ke dalam aplikasi web dan mobile modern. Mencakup generasi gambar (Flux 1.1 Pro, SDXL, DALL-E 3), generasi video (Sora, Runway Gen-3, MiniMax), text-to-speech (ElevenLabs v3, OpenAI TTS), speech-to-text (Whisper large-v3, Deepgram Nova-3), dan kloning audio. Dilengkapi pola pemrosesan asinkron via webhook, mitigasi biaya, serta penyaringan keamanan konten (NSFW/moderasi).

Kondisi Pemicu

  • Mengintegrasikan API generasi gambar AI beresolusi tinggi (Flux 1.1 Pro, DALL-E 3, SDXL).
  • Membangun fitur sintesis suara ekspresif (Text-to-Speech) atau transkripsi audio otomatis (Speech-to-Text).
  • Mengembangkan pipeline video AI asinkron berbasis webhook callback.
  • Menerapkan pembatasan kuota generasi dan verifikasi keamanan konten pengguna.

Matriks Pemilihan Model Generasi Media

Tipe MediaProvider & ModelLatensiKualitas Visual/AudioEstimasi BiayaRekomendasi Penggunaan
GambarReplicate (Flux 1.1 Pro)~3 detik★★★★★$0.04 / gambarGambar fotorealistik & tipografi akurat
Gambar (Draft)Replicate (Flux Schnell)~1 detik★★★★$0.003 / gambarPratinjau instan & volume tinggi
GambarOpenAI (DALL-E 3)~5 detik★★★★$0.04 / gambarIlustrasi kreatif & pemahaman prompt deskriptif
Suara (TTS)ElevenLabs (eleven_v3)~500 ms★★★★★$0.30 / 1K karakterNarasi audio buku & karakter ekspresif
Suara (Realtime)ElevenLabs (eleven_flash_v2_5)~200 ms★★★★$0.15 / 1K karakterAgen percakapan AI & voicebot interaktif
TranskripsiOpenAI (Whisper large-v3)Cepat★★★★★$0.006 / menitTranskripsi rapat & subtitling multibahasa

Pola Implementasi Teknis (TypeScript)

1. Generasi Gambar Berkualitas Tinggi dengan Replicate (Flux 1.1 Pro)

import Replicate from 'replicate';

const replicate = new Replicate({
  auth: process.env.REPLICATE_API_TOKEN!,
});

interface ImageGenOptions {
  width?: number;
  height?: number;
  mode?: 'production' | 'preview';
}

export async function hasilkanGambarAI(promptTeks: string, options: ImageGenOptions = {}) {
  const isPreview = options.mode === 'preview';
  const modelIdentifier = isPreview 
    ? 'black-forest-labs/flux-schnell' 
    : 'black-forest-labs/flux-1.1-pro';

  const output = await replicate.run(modelIdentifier, {
    input: {
      prompt: promptTeks,
      width: options.width ?? 1024,
      height: options.height ?? 1024,
      num_inference_steps: isPreview ? 4 : 28,
      output_format: 'webp',
      output_quality: 90,
    },
  });

  return output; // Mengembalikan URL langsung ke aset WebP yang dihasilkan
}

2. Streaming Text-to-Speech (TTS) ElevenLabs

export async function streamSuaraTeks(teks: string, voiceId: string): Promise<ReadableStream<Uint8Array>> {
  const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream`, {
    method: 'POST',
    headers: {
      'xi-api-key': process.env.ELEVENLABS_API_KEY!,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      text: teks,
      model_id: 'eleven_v3',
      voice_settings: {
        stability: 0.5,
        similarity_boost: 0.8,
        style: 0.2,
      },
    }),
  });

  if (!response.ok) {
    throw new Error(`ElevenLabs API error: ${response.statusText}`);
  }

  return response.body as ReadableStream<Uint8Array>;
}

3. Transkripsi Audio Whisper Berpresisi Tinggi

import OpenAI from 'openai';
import fs from 'fs';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export async function transkripsiAudio(fileBuffer: Buffer, namaFile: string) {
  const file = await OpenAI.toFile(fileBuffer, namaFile);
  
  const hasil = await openai.audio.transcriptions.create({
    file,
    model: 'whisper-1',
    response_format: 'verbose_json',
    timestamp_granularities: ['word', 'segment'],
  });

  return hasil;
}

4. Pola Produksi Kritis

  • Arsitektur Asinkron: Wajib menggunakan antrean tugas latar belakang (BullMQ atau Inngest) untuk setiap operasi media yang memerlukan waktu komputasi >2 detik.
  • Penerimaan Callback Webhook: Jangan gunakan polling HTTP terus-menerus; gunakan endpoint webhook yang divalidasi dengan tanda tangan kriptografis untuk menerima hasil generasi dari Replicate.
  • Pencegahan Konten Terlarang (NSFW): Lakukan penyaringan ganda menggunakan OpenAI Moderation API sebelum memproses prompt dan verifikasi gambar hasil sebelum ditampilkan kepada pengguna umum.
  • Penyimpanan Permanen: Jangan bergantung pada URL hosting sementara dari vendor AI. Segera unduh dan simpan aset ke Cloudflare R2 atau AWS S3, lalu sajikan melalui domain CDN kustom.

Hard Guardrails (Invarian Deklaratif)

  • Invarian Pemrosesan Antrean Asinkron: Seluruh permintaan generasi media (gambar, video, TTS berdurasi panjang) dengan waktu eksekusi $> 2\text{ detik}$ WAJIB diproses melalui antrean kerja tahan-gagal (BullMQ/Inngest/Temporal) atau webhook—dilarang memblokir handler HTTP sinkron.
  • Gerbang Keamanan Konten Ganda: Setiap prompt generasi wajib lolos penyaringan otomatis moderasi/NSFW sebelum dikirim ke API vendor, dan URL aset hasil generasi harus divalidasi sebelum ditampilkan ke pengguna.
  • Invarian Penyimpanan Permanen Object Storage: Media hasil generasi DILARANG bergantung pada tautan URL sementara dari vendor AI (seperti URL kedaluwarsa Replicate/OpenAI); aset harus diunduh dan dialirkan ke penyimpanan objek privat (S3/R2) lalu disajikan via CDN terautentikasi.
  • Pengamanan Kuota & Rate-Limiting: Endpoint pengguna wajib memberlakukan pengecekan kuota atomik (Redis token bucket atau pemotongan saldo DB) sebelum memicu panggilan API generasi eksternal.

Non-Functional Requirements (NFR)

  • Respons Dispatch Asinkron: Konfirmasi penerimaan antrean tugas awal $\le 100\text{ms}$.
  • Kompresi Penyimpanan: Kualitas kompresi WebP/AVIF $\ge 85$ untuk efisiensi transfer.
  • Distribusi CDN: TTL cache distribusi CDN media $\ge 7\text{ hari}$.

Matriks Eksekusi Berdaulat, Efisiensi Token & Invarian

DimensiMandat Berdaulat & Kontrak Deterministik
Kaskade Model FrontierHigh Fast / Medium / High (Gemini 4 Carbon/Hydrogen/Neon/Argon/Pro, Grok 4.7 High Fast, Claude Sonnet/Opus 5.5, GPT-5.6 Sol)
Invarian Fallback KetersediaanGemini 4 (Carbon/Hydrogen/Neon/Argon/Pro) -> Gemini 3.8 Flash; Claude Opus 5.5 -> Claude Opus 4.6 (Bebas gagal saat model belum tersedia/kuota penuh)
Protokol Hemat Token & KV-CacheKunci instruksi & skema statis di prefix awal (kv-cache-prefix-optimizer); kirim potongan CONTEXT_MAP.md (<250 token/panggilan) saat Fan-Out
Eksekusi SaaT CLI & MCPCLI: vibes skill exec ai-media-generation-expert <audit|eval|verify|generate|blueprint> / MCP: vibes_skill_dispatch, vibes_ast_query, vibes_compile_cache, vibes_optimize_budget, vibes_verify_gate
Invarian NFR & Anti-SlopLatensi P99 API < 85ms, paritas skema ketat OpenAPI 3.1 / TypeSpec, kontrak error RFC 9457 Problem Details, penegakan Idempotency-Key; kode 100% tuntas tanpa placeholder diverifikasi melalui node scripts/check-anti-slop.js --strict

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.