Skip to content

🎥 Make videos programmatically with React

Further guardrails to ensure better LLM responses

ASchwadf5c351f2840f
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.ts
index 19c9a81672..0016794f02 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
@@ -597,6 +597,13 @@ RESERVED NAMES (CRITICAL):
- ALWAYS set backgroundColor on AbsoluteFill from frame 0 - never fade in backgrounds
- NEVER NEVER NEVER use fade-in for the AbsoluteFill container - always have it fully visible from frame 0
+OUTPUT FORMAT (CRITICAL):
+- Output ONLY the code. No explanations, no questions, no commentary.
+- Do NOT ask follow-up questions like "Do you want X or Y?"
+- Do NOT add text before or after the code block
+- The response must start with "import" and end with "};", nothing else
+- If the prompt is ambiguous, make a reasonable choice and implement it - do not ask for clarification
+
`;
export async function POST(req: Request) {
diff --git a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx
index 680d73ec6e..0017dcd179 100644
--- a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx
+++ b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx
@@ -21,7 +21,10 @@ import {
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { examplePrompts } from "@/examples/prompts";
-import { validateGptResponse } from "@/helpers/validate-response";
+import {
+ validateGptResponse,
+ extractComponentCode,
+} from "@/helpers/sanitize-response";
const iconMap: Record<string, LucideIcon> = {
Type,
@@ -171,10 +174,14 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(
}
}
- // Sanitize the final response (strip markdown code block wrappers)
+ // Sanitize the final response (strip markdown code block wrappers and trailing text)
let finalCode = accumulatedText;
finalCode = finalCode.replace(/^```(?:tsx?|jsx?)?\n?/, "");
finalCode = finalCode.replace(/\n?```\s*$/, "");
+ finalCode = extractComponentCode(finalCode);
+
+ // Update the editor with the cleaned code
+ onCodeGenerated?.(finalCode);
const validation = validateGptResponse(finalCode);
if (!validation.isValid && validation.error) {
diff --git a/packages/template-prompt-to-motion-graphics/src/helpers/sanitize-response.ts b/packages/template-prompt-to-motion-graphics/src/helpers/sanitize-response.ts
new file mode 100644
index 0000000000..479dc1b630
--- /dev/null
+++ b/packages/template-prompt-to-motion-graphics/src/helpers/sanitize-response.ts
@@ -0,0 +1,74 @@
+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,
+ };
+}
+
+/**
+ * Extract only the component code, removing any trailing text/commentary.
+ * Uses brace counting to find the end of the component.
+ */
+export function extractComponentCode(code: string): string {
+ // Find the component declaration start
+ const exportMatch = code.match(
+ /export\s+const\s+\w+\s*=\s*\(\s*\)\s*=>\s*\{/,
+ );
+
+ if (exportMatch && exportMatch.index !== undefined) {
+ const declarationStart = exportMatch.index;
+ const bodyStart = declarationStart + exportMatch[0].length;
+
+ // Count braces to find the matching closing brace
+ let braceCount = 1;
+ let endIndex = bodyStart;
+
+ for (let i = bodyStart; i < code.length; i++) {
+ const char = code[i];
+ if (char === "{") {
+ braceCount++;
+ } else if (char === "}") {
+ braceCount--;
+ if (braceCount === 0) {
+ endIndex = i;
+ break;
+ }
+ }
+ }
+
+ if (braceCount === 0) {
+ // Return everything from start of code to end of component (including closing brace and semicolon)
+ let result = code.slice(0, endIndex + 1);
+ // Add semicolon if not present
+ if (!result.trim().endsWith(";")) {
+ result = result.trimEnd() + ";";
+ }
+ return result.trim();
+ }
+ }
+
+ // Fallback: return as-is
+ return code;
+}
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.ts
deleted file mode 100644
index 0ca1af2b27..0000000000
--- a/packages/template-prompt-to-motion-graphics/src/helpers/validate-response.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-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,
- };
-}