route.ts 1.5 KB

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