🎥 Make videos programmatically with React
Add validation step in generate route, also add minimal JSX validation check
ASchwad2ad9d0da96b7
diff --git a/packages/template-prompt-to-motion-graphics/src/app/api/generate/route.ts b/packages/template-prompt-to-motion-graphics/src/app/api/generate/route.tsindex 8cc053d80a..be08c80175 100644--- a/packages/template-prompt-to-motion-graphics/src/app/api/generate/route.ts+++ b/packages/template-prompt-to-motion-graphics/src/app/api/generate/route.ts@@ -1,5 +1,35 @@-import { streamText } from "ai";+import { streamText, generateObject } from "ai";import { createOpenAI } from "@ai-sdk/openai";+import { z } from "zod";++const VALIDATION_PROMPT = `You are a prompt classifier for a motion graphics generation tool.++Determine if the user's prompt is asking for motion graphics/animation content that can be created as a React/Remotion component.++VALID prompts include requests for:+- Animated text, titles, or typography+- Data visualizations (charts, graphs, progress bars)+- UI animations (buttons, cards, transitions)+- Logo animations or brand intros+- Social media content (stories, reels, posts)+- Explainer animations+- Kinetic typography+- Abstract motion graphics+- Animated illustrations+- Product showcases+- Countdown timers+- Loading animations+- Any visual/animated content++INVALID prompts include:+- Questions (e.g., "What is 2+2?", "How do I...")+- Requests for text/written content (poems, essays, stories, code explanations)+- Conversations or chat+- Non-visual tasks (calculations, translations, summaries)+- Requests completely unrelated to visual content++Return true if the prompt is valid for motion graphics generation, false otherwise.`;+const SYSTEM_PROMPT = `You are an expert in generating React components for Remotion animations.@@ -587,6 +617,30 @@ export async function POST(req: Request) {const openai = createOpenAI({ apiKey });+ // Validate the prompt first+ try {+ const validationResult = await generateObject({+ model: openai("gpt-5.2"),+ system: VALIDATION_PROMPT,+ prompt: `User prompt: "${prompt}"`,+ schema: z.object({ valid: z.boolean() }),+ });++ if (!validationResult.object.valid) {+ return new Response(+ JSON.stringify({+ error:+ "No valid motion graphics prompt. Please describe an animation or visual content you'd like to create.",+ type: "validation",+ }),+ { status: 400, headers: { "Content-Type": "application/json" } },+ );+ }+ } catch (validationError) {+ // On validation error, allow through rather than blocking+ console.error("Validation error:", validationError);+ }+try {const result = streamText({model: openai(modelName),diff --git a/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx b/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsxindex 33b7974f22..fddbe411e8 100644--- a/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx+++ b/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx@@ -11,6 +11,7 @@ import {PromptInput,type StreamPhase,type PromptInputRef,+ type GenerationErrorType,} from "../../components/PromptInput";import { examples } from "../../examples/code";import { useAnimationState } from "../../hooks/useAnimationState";@@ -34,7 +35,10 @@ function GeneratePageContent() {const [prompt, setPrompt] = useState(initialPrompt);const [hasAutoStarted, setHasAutoStarted] = useState(false);const [hasGeneratedOnce, setHasGeneratedOnce] = useState(false);- const [apiError, setApiError] = useState<string | null>(null);+ const [generationError, setGenerationError] = useState<{+ message: string;+ type: GenerationErrorType;+ } | null>(null);const { code, Component, error, isCompiling, setCode, compileCode } =useAnimationState(examples[0]?.code || "");@@ -93,15 +97,18 @@ function GeneratePageContent() {const handleStreamingChange = useCallback((streaming: boolean) => {setIsStreaming(streaming);- // Clear API error when starting a new generation+ // Clear errors when starting a new generationif (streaming) {- setApiError(null);+ setGenerationError(null);}}, []);- const handleApiError = useCallback((errorMessage: string) => {- setApiError(errorMessage);- }, []);+ const handleError = useCallback(+ (message: string, type: GenerationErrorType) => {+ setGenerationError({ message, type });+ },+ [],+ );// Auto-trigger generation if prompt came from URLconst promptInputRef = useRef<PromptInputRef>(null);@@ -121,22 +128,22 @@ function GeneratePageContent() {<div className="flex-1 flex flex-col min-w-0 px-12 pb-8 gap-8 overflow-hidden"><div className="flex-1 flex flex-col lg:flex-row overflow-auto lg:overflow-hidden gap-8"><CodeEditor- code={hasGeneratedOnce ? code : ""}+ code={hasGeneratedOnce && !generationError ? code : ""}onChange={handleCodeChange}isStreaming={isStreaming}streamPhase={streamPhase}/><div className="shrink-0 lg:shrink lg:flex-[2.5] lg:min-w-0 lg:h-full"><AnimationPlayer- Component={Component}+ Component={generationError ? null : Component}durationInFrames={durationInFrames}fps={fps}onDurationChange={setDurationInFrames}onFpsChange={setFps}isCompiling={isCompiling}isStreaming={isStreaming}- error={apiError || error}- errorType={apiError ? "api" : "compilation"}+ error={generationError?.message || error}+ errorType={generationError?.type || "compilation"}code={code}/></div>@@ -147,7 +154,7 @@ function GeneratePageContent() {onCodeGenerated={handleCodeChange}onStreamingChange={handleStreamingChange}onStreamPhaseChange={setStreamPhase}- onError={handleApiError}+ onError={handleError}prompt={prompt}onPromptChange={setPrompt}/>diff --git a/packages/template-prompt-to-motion-graphics/src/components/AnimationPlayer/index.tsx b/packages/template-prompt-to-motion-graphics/src/components/AnimationPlayer/index.tsxindex db136cef48..fab6af7409 100644--- a/packages/template-prompt-to-motion-graphics/src/components/AnimationPlayer/index.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/AnimationPlayer/index.tsx@@ -29,7 +29,7 @@ interface AnimationPlayerProps {isCompiling: boolean;isStreaming: boolean;error: string | null;- errorType?: "compilation" | "api";+ errorType?: "compilation" | "api" | "validation";code: string;}@@ -66,7 +66,12 @@ export const AnimationPlayer: React.FC<AnimationPlayerProps> = ({}if (error) {- const errorTitle = errorType === "api" ? "API Error" : "Compilation Error";+ const errorTitle =+ errorType === "validation"+ ? "Invalid Prompt"+ : errorType === "api"+ ? "API Error"+ : "Compilation Error";return (<div className="w-full aspect-video max-h-[calc(100%-80px)] flex justify-center items-center bg-background-error rounded-lg overflow-hidden shadow-[0_0_60px_rgba(0,0,0,0.5)] border border-destructive"><div className="text-center max-w-[80%]">diff --git a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsxindex ed53a064a4..680d73ec6e 100644--- a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx@@ -21,6 +21,7 @@ import {} from "@/components/ui/select";import { Button } from "@/components/ui/button";import { examplePrompts } from "@/examples/prompts";+import { validateGptResponse } from "@/helpers/validate-response";const iconMap: Record<string, LucideIcon> = {Type,@@ -44,6 +45,8 @@ export type ModelId = (typeof MODELS)[number]["id"];export type StreamPhase = "idle" | "reasoning" | "generating";+export type GenerationErrorType = "validation" | "api";+export interface PromptInputRef {triggerGeneration: () => void;}@@ -52,7 +55,7 @@ interface PromptInputProps {onCodeGenerated?: (code: string) => void;onStreamingChange?: (isStreaming: boolean) => void;onStreamPhaseChange?: (phase: StreamPhase) => void;- onError?: (error: string) => void;+ onError?: (error: string, type: GenerationErrorType) => void;variant?: "landing" | "editor";prompt?: string;onPromptChange?: (prompt: string) => void;@@ -106,6 +109,11 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(const errorData = await response.json().catch(() => ({}));const errorMessage =errorData.error || `API error: ${response.status}`;+ // Check if this is a validation error from the API+ if (errorData.type === "validation") {+ onError?.(errorMessage, "validation");+ return;+ }throw new Error(errorMessage);}@@ -151,19 +159,34 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(codeToShow = codeToShow.replace(/\n?```\s*$/, "");onCodeGenerated?.(codeToShow.trim());+ } else if (event.type === "error") {+ throw new Error(event.error);+ }+ } catch (parseError) {+ // Only re-throw if it's an actual Error we created, not a JSON parse error+ if (parseError instanceof Error && parseError.message !== "Unexpected token") {+ throw parseError;}- } catch {- // Ignore parse errors for malformed JSON}}}++ // Sanitize the final response (strip markdown code block wrappers)+ let finalCode = accumulatedText;+ finalCode = finalCode.replace(/^```(?:tsx?|jsx?)?\n?/, "");+ finalCode = finalCode.replace(/\n?```\s*$/, "");++ const validation = validateGptResponse(finalCode);+ if (!validation.isValid && validation.error) {+ onError?.(validation.error, "validation");+ }} catch (error) {console.error("Error generating code:", error);const errorMessage =error instanceof Error? error.message: "An unexpected error occurred";- onError?.(errorMessage);+ onError?.(errorMessage, "api");} finally {setIsLoading(false);onStreamingChange?.(false);diff --git a/packages/template-prompt-to-motion-graphics/src/helpers/validate-response.ts b/packages/template-prompt-to-motion-graphics/src/helpers/validate-response.tsnew file mode 100644index 0000000000..0ca1af2b27--- /dev/null+++ b/packages/template-prompt-to-motion-graphics/src/helpers/validate-response.ts@@ -0,0 +1,28 @@+export interface ValidationResult {+ isValid: boolean;+ error: string | null;+}++/**+ * Lightweight validation to check if GPT response contains JSX content.+ * This is a fallback check after the LLM pre-validation.+ */+export function validateGptResponse(response: string): ValidationResult {+ const trimmed = response.trim();++ // Check for JSX-like content (at least one opening tag)+ // Matches: <ComponentName, <div, <span, etc.+ const hasJsx = /<[A-Z][a-zA-Z]*|<[a-z]+[^>]*>/.test(trimmed);+ if (!hasJsx) {+ return {+ isValid: false,+ error:+ "The response was not a valid motion graphics component. Please try a different prompt.",+ };+ }++ return {+ isValid: true,+ error: null,+ };+}