Communitygithub.com

evalix098/tiktoklive

Llama a la API de xAI (Grok) desde el código del servidor de esta aplicación usando la `XAI_API_KEY` inyectada: funciones de chat/LLM, generación de imágenes y video (Imagine), y voz (texto a voz). Úsalo cuando la aplicación necesite cualquier funcionalidad de 'IA'/'asistente'/'chatbot'/'Grok', generación de imágenes/video en tiempo real o síntesis de voz.

¿Qué es tiktoklive?

Esta habilidad proporciona acceso directo a la API de xAI (Grok) para aplicaciones que se ejecutan en entornos donde la variable de entorno `XAI_API_KEY` está inyectada. Está diseñada para desarrolladores que construyen aplicaciones con funcionalidades de IA, permitiendo usar chat/LLM (modelo grok-4.5), generación de imágenes y video (Imagine), y síntesis de voz (TTS) desde el código del servidor. La API es compatible con OpenAI, por lo que se puede usar con cualquier cliente estándar de OpenAI cambiando la URL base y la clave. La habilidad enfatiza el uso responsable de los recursos, ya que cada llamada consume la cuota y los créditos personales del propietario de la aplicación. Soporta plataformas como TanStack Start (React) y cualquier framework que ejecute código de servidor con Node.js/Deno, y recomienda usar `fetch` simple sin SDKs adicionales, siguiendo la documentación oficial en docs.x.ai para streaming, salidas estructuradas, visión y la lista completa de modelos.

Compatible con~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/evalix098/tiktoklive/tree/HEAD/.grok/skills/xai-api

Preguntar en tu IA favorita

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

Documentación

API de xAI (Grok)

Cuando XAI_API_KEY está presente en el entorno, esta aplicación tiene acceso real a la API de xAI — úsala para funcionalidades de IA en lugar de simular respuestas o recurrir a otro proveedor. La misma variable se inyecta en la aplicación desplegada al publicar, por lo que el código construido con ella funciona de manera idéntica en vista previa y en producción.

La clave es la clave personal del propietario de la aplicación: cada llamada consume su cuota y créditos. Sé deliberado con el uso — consulta Gastar responsablemente antes de conectar llamadas de IA a cualquier cosa que se ejecute automáticamente o esté abierta a visitantes.

La clave desbloquea toda la superficie de la API, no solo el chat:

  • Chat / LLM — modelo más reciente: grok-4.5; usa este por defecto a menos que el usuario pida otro.
  • Imagine (imágenes y video) — genera y edita imágenes, genera video, en tiempo real dentro de la aplicación.
  • Voz — texto a voz con voces expresivas (y transcripción).
  • Documentación oficial: docs.x.ai — endpoints, modelos, parámetros, streaming, uso de herramientas. No adivines las formas de la API; consulta la documentación.
  • La API es compatible con OpenAI (https://api.x.ai/v1), por lo que cualquier cliente estilo OpenAI funciona cambiando la URL base y la clave.

Variables de entorno — no crees un archivo .env

VariableDóndePropósito
XAI_API_KEYservidorInyectada por la plataforma (vista previa y despliegue). Nunca la escribas, la hardcodees o se la pidas al usuario.

La clave es solo del servidor: léela con process.env.XAI_API_KEY dentro de los manejadores createServerFn / código del servidor, nunca en componentes cliente, y nunca la expongas mediante una variable con prefijo VITE_ o en una respuesta de API.

Puede estar ausente (controlada por despliegue gradual). Degrada con elegancia — compruébala y muestra un estado amigable como 'Las funciones de IA no están disponibles' en lugar de fallar:

const apiKey = process.env.XAI_API_KEY;
if (!apiKey) throw new Error("AI no está disponible en este entorno");

Llamar a la API (solo servidor)

No se necesita SDK — usa fetch simple desde una función del servidor:

import { createServerFn } from "@tanstack/react-start";

export const askGrok = createServerFn({ method: "POST" })
  .validator((input: { prompt: string }) => input)
  .handler(async ({ data }) => {
    const apiKey = process.env.XAI_API_KEY;
    if (!apiKey) return { ok: false as const, error: "AI no está disponible" };

    const res = await fetch("https://api.x.ai/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        model: "grok-4.5",
        messages: [{ role: "user", content: data.prompt }],
      }),
    });
    if (!res.ok) {
      return { ok: false as const, error: `Error de API xAI ${res.status}` };
    }
    const body = (await res.json()) as {
      choices: { message: { content: string } }[];
    };
    return { ok: true as const, text: body.choices[0]?.message.content ?? "" };
  });

Para streaming, salidas estructuradas, visión o la lista completa de modelos, consulta docs.x.ai — las formas son compatibles con OpenAI.

Imagine — generación de imágenes y video (solo servidor)

La misma clave impulsa las funciones de imagen/video en tiempo real en la aplicación (avatares de usuario, arte de escenas, contenido generado). Es diferente de tus herramientas en tiempo de compilación imagine_text_to_image / imagine_image_to_image / imagine_image_to_video (la habilidad imagine-grok-build): usa la API cuando la aplicación en ejecución genera medios, y las herramientas cuando tú creas activos estáticos durante la compilación.

// POST https://api.x.ai/v1/images/generations — mismo encabezado de autenticación que el chat
body: JSON.stringify({
  model: "grok-imagine-image-quality", // o "grok-imagine-image" (más barato)
  prompt: data.prompt,
  // n (≤10), resolución ("1k"|"2k"), response_format ("url"|"b64_json")
})
// → body.data[0].url
  • Edición de imágenes: POST /v1/images/edits — ediciones en lenguaje natural, hasta 3 imágenes de referencia.
  • Video: grok-imagine-video a través de los endpoints de video asíncronos (inicia, luego consulta el ID de solicitud devuelto; clips de hasta ~15s).
  • Parámetros completos y ejemplos: docs.x.ai → API de Imagine.

Voz — texto a voz (solo servidor)

POST https://api.x.ai/v1/tts convierte texto en audio hablado — narración, accesibilidad, voces de personajes:

// Mismo encabezado Authorization; devuelve bytes de audio (ej. MP3)
body: JSON.stringify({ text: data.text, voice_id: "eve" }) // eve = voz predeterminada

Enumera las voces en GET /v1/tts/voices (se admiten voces personalizadas); la transcripción (voz a texto) también está disponible. Detalles: docs.x.ai → API de Voz. Sirve el audio al cliente desde tu función del servidor — nunca llames a la API desde el navegador (eso expondría la clave).

Gastar responsablemente

La clave pertenece al propietario de la aplicación (el usuario para el que construyes): cada llamada — incluyendo las activadas por visitantes anónimos de la aplicación desplegada — consume su cuota y créditos personales. Gastarla en llamadas innecesarias degrada o rompe todos los demás usos de su clave. Sé cuidadoso con el uso:

  • Limita la salida (max_tokens) y mantén los mensajes pequeños para funciones orientadas a visitantes. La generación de imágenes, y especialmente de video, cuesta mucho más por llamada que el chat.
  • Nunca llames a la API en un bucle, con cada pulsación de tecla o al cargar la página — haz que las llamadas sean iniciadas por el usuario (pulsación de botón, envío de formulario) y aplica debounce.
  • Almacena en caché o persiste los resultados (consulta la habilidad neon) en lugar de regenerar el mismo contenido por visitante o por renderizado.
  • Protege los flujos costosos — especialmente la generación de medios. En una aplicación que ya tiene inicio de sesión, colócalos detrás de authMiddleware (consulta la habilidad auth). El inicio de sesión está desactivado por defecto, y agregar el middleware sin él rompe la aplicación desplegada (AGENTS.md §0.5) — así que en una aplicación sin cuentas, limita el uso: llamadas iniciadas por el usuario, límites pequeños, resultados en caché.
  • No agregues tormentas de reintentos: ante un error de API, muéstralo; reintenta como máximo una vez.

Individual skills in this repo

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

evalix098/tiktoklive

Add user accounts and sign-in to this TanStack Start app. Use when the app needs authentication, sign-in, user accounts, protected routes, or per-user data. Triggers on "auth", "login", "log in", "sign in", "sign up", "account", "users", "authentication", "protected", "who is logged in", "current user", "per-user".

evalix098/tiktoklive

Build browser games and interactive/canvas/3D experiences in this TanStack Start + React app. Use for any game, simulation, or WebGL/Canvas experience — 2D or 3D, single-player. Covers the game loop & timing, 3D orientation/camera conventions, collision, performance, assets, audio, save, game feel, and per-genre playbooks. For WASD / vehicle / flight **input signs and inverted A/D**, open the **`controls`** skill — do not rely on this file or racing-kart alone. Triggers on "game", "minecraft", "fps", "platformer", "racing", "tetris", "snake", "shooter", "3d", "three.js", "canvas", "voxel", "physics".

evalix098/tiktoklive

Player-facing input signs for browser games: WASD, vehicles, flight, FPS mouse-look, and the #1 failure mode (inverted A/D). Mandatory control self-tests and a tiny test interface so you can verify A turns left before shipping. Load for ANY game with movement, steering, flying, driving, tanks, boats, mechs, drones, planes, karts, third-person follow cams — not only racing. Triggers on "controls", "WASD", "inverted", "steer", "flight", "airplane", "kart", "vehicle", "yaw", "roll", "pitch", "mouse look", "A/D".

evalix098/tiktoklive

Design and build polished, non-generic UI for this TanStack Start + React + Tailwind v4 + shadcn/Radix app. Use whenever you create or restyle any interface surface — pages, landing pages, dashboards, forms, modals, nav, and game overlays (start screens, HUD, menus). Covers design tokens, layout, typography, color, spacing, motion, and the anti-"AI-slop" rules that keep output from looking generic. Triggers on "design", "UI", "make it look good", "polish", "landing page", "theme", "style", "redesign", "ugly", "clean up".

evalix098/tiktoklive

Deep guide for game ANIMATION assets: motion cycles, action keyframes, effect sequences, and animation sprite sheets — built around a video-first pipeline. In this app-builder sandbox, execute via the video2dsprite / generate2dsprite skills (magenta + scripts), not ad-hoc ffmpeg. Use whenever generating anything that moves: walk/run cycles, attacks, idles, FX, flags, fire, animation sheets. Complements game-asset-core.

evalix098/tiktoklive

Core discipline for ANY game-asset generation with Imagine tools: the engine-ready defaults users don't state, spec checklists, style anchoring, read-back verification, honest defect flagging. Use whenever generating any game art (sprites, sheets, animations, tiles, UI, FX) — then ALSO load the matching specialist skill: game-animation-frames for anything that moves, game-tilesets for tiles/terrain, game-character-consistency for recurring characters, game-ui-icons for UI and icons.

evalix098/tiktoklive

Deep guide for CHARACTER IDENTITY across images: turnarounds (front/side/ back), state and damage variants, palette swaps, equipment changes, and same-character-in-context sets. Use whenever generating character turnarounds, character sheets, variants of an existing sprite, or any same-subject multi-image set. Complements game-asset-core.

evalix098/tiktoklive

Deep guide for game TILE assets: seamless tileable textures, terrain transition tilesets, autotiles, and ground/platform tiles. Use whenever generating tileable textures, tilesets, terrain transitions, or seamless patterns. Complements game-asset-core.

evalix098/tiktoklive

Deep guide for game UI assets: buttons with interaction states, panels, bars, wordmark logos, and icon sets. Use whenever generating game UI elements, HUD assets, inventory icons, icon sets, buttons, or title logos. Complements game-asset-core.

evalix098/tiktoklive

Generate production-oriented 2D game maps with `imagine_text_to_image`: RPG/top-down maps, side-scroller parallax stages, tilemaps, layered raster maps, prop packs, collision zones, and walkable areas. Use when building browser games that need real map art (not pure code-drawn tiles), layered props, or map collision metadata. Triggers on "map", "level", "stage", "tilemap", "overworld", "dungeon", "side scroller background", "prop pack", "2D map".

evalix098/tiktoklive

Generate and postprocess 2D game sprites and animation sheets: pixel-art characters, NPCs, creatures, spells, projectiles, impacts, props, summons, and transparent PNG/GIF exports. Use when building browser games that need real sprite sheets (not code-drawn placeholders), matching a map art style, or producing magenta-background sheets for chroma-key cleanup. Triggers on "sprite", "sprite sheet", "animation sheet", "pixel art character", "walk cycle", "attack animation", "projectile sprite", "2D game asset".

evalix098/tiktoklive

How to use the Imagine tools in Grok Build: imagine_text_to_image, imagine_image_to_image, imagine_reference_to_image, imagine_text_to_video, imagine_image_to_video, imagine_reference_to_video, and render_file for chat previews. When to build a visual with code instead of generating it, prompt-craft, reference-first handling of real people, factual grounding, and asset-consistency. Load this whenever generating or editing an image or video is on the table. Tool-usage-driven, not triggered by a user merely mentioning images.

evalix098/tiktoklive

Peer-to-peer realtime multiplayer over WebRTC data channels: every user of the deployed app connects directly to every other user (full mesh), the server only brokers the handshake at /api/rtc. Lowest possible latency, zero per-message server cost. Use for 2-8 player co-op/casual realtime: shared cursors, drawing, party games, casual action. Triggers: p2p, peer to peer, webrtc, low latency multiplayer, direct connection.

evalix098/tiktoklive

Use Neon Postgres (the database) in this TanStack Start app. Use when the app needs to store or query data, persist state, or keep per-user data. Triggers on "database", "Postgres", "Neon", "save data", "store data", "persist", "tables", "SQL", "query", "migrations".

evalix098/tiktoklive

Share-link previews and app identity for apps on *.grok.me: the injector-owned og:image card, the SVG favicon, and PWA icons for installable apps. Use when scaffolding, renaming, or restyling the app — and for share / unfurl / OG / Twitter card questions. A custom 1200×630 card from the app's own art is the default — games of every kind (DOM board/word games included), whimsical apps, creative tools, and brand-forward pages; only plain utilities keep the placeholder. Always run the brand-asset pass as a `task` subagent and never wait for it. Triggers on "share", "rename", "app name", "OG", "Open Graph", "twitter card", "unfurl", "og:image", "og:type", "x:game:image", "x-banner", "link preview", "social card", "thumbnail", "preview image", "favicon", "app icon", "PWA", "manifest", "installable", "home screen", "SEO", "meta description".

evalix098/tiktoklive

Official Three.js API and TSL (Three.js Shading Language) reference for LLM code generation. Load when writing or debugging three.js / WebGL / WebGPU / custom materials / shaders / GLTF / advanced three APIs beyond basic game loop/controls. Prefer building-games for game correctness (loop, WASD, camera, orientation); use this skill for full API/TSL depth. Triggers on "three.js", "threejs", "WebGPU", "TSL", "NodeMaterial", "shader", "GLTF", "MeshStandard", "OrbitControls", "WebGLRenderer".

evalix098/tiktoklive

Grok Build only. Turn a 2D character still into denser animation sprites via imagine_text_to_image base → imagine_image_to_video (6s/10s run-in-place) → ffmpeg frames → magenta chroma-key → dense sampled strips/grids/GIFs. Use when the user wants video-to-sprite, smoother run/walk cycles, or denser intermediate poses. Prefer generate2dsprite for crisp production pixel sheets. Triggers on "video to sprite", "imagine_image_to_video sprite", "dense walk cycle", "smooth run animation from video".

Skills relacionados