route.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { streamText } from "ai";
  2. import { getVideoPrompt } from "@/lib/catalog";
  3. import { minuteRateLimit, dailyRateLimit } from "@/lib/rate-limit";
  4. import { headers } from "next/headers";
  5. export const maxDuration = 30;
  6. // Generate prompt from catalog - uses Remotion schema's prompt template with custom rules
  7. const SYSTEM_PROMPT = getVideoPrompt();
  8. const MAX_PROMPT_LENGTH = 500;
  9. const DEFAULT_MODEL = "anthropic/claude-haiku-4.5";
  10. export async function POST(req: Request) {
  11. const headersList = await headers();
  12. const ip = headersList.get("x-forwarded-for")?.split(",")[0] ?? "anonymous";
  13. const [minuteResult, dailyResult] = await Promise.all([
  14. minuteRateLimit.limit(ip),
  15. dailyRateLimit.limit(ip),
  16. ]);
  17. if (!minuteResult.success || !dailyResult.success) {
  18. const isMinuteLimit = !minuteResult.success;
  19. return new Response(
  20. JSON.stringify({
  21. error: "Rate limit exceeded",
  22. message: isMinuteLimit
  23. ? "Too many requests. Please wait a moment before trying again."
  24. : "Daily limit reached. Please try again tomorrow.",
  25. }),
  26. {
  27. status: 429,
  28. headers: { "Content-Type": "application/json" },
  29. },
  30. );
  31. }
  32. const { prompt } = await req.json();
  33. const sanitizedPrompt = String(prompt || "").slice(0, MAX_PROMPT_LENGTH);
  34. const result = streamText({
  35. model: process.env.AI_GATEWAY_MODEL || DEFAULT_MODEL,
  36. system: SYSTEM_PROMPT,
  37. prompt: sanitizedPrompt,
  38. temperature: 0.7,
  39. });
  40. return result.toTextStreamResponse();
  41. }