route.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import { readFile } from "fs/promises";
  2. import { join } from "path";
  3. import { convertToModelMessages, stepCountIs, streamText } from "ai";
  4. import type { ModelMessage, UIMessage } from "ai";
  5. import { createBashTool } from "bash-tool";
  6. import { headers } from "next/headers";
  7. import { allDocsPages } from "@/lib/docs-navigation";
  8. import { mdxToCleanMarkdown } from "@/lib/mdx-to-markdown";
  9. import { minuteRateLimit, dailyRateLimit } from "@/lib/rate-limit";
  10. export const maxDuration = 60;
  11. const DEFAULT_MODEL = "anthropic/claude-haiku-4.5";
  12. const SYSTEM_PROMPT = `You are a helpful documentation assistant for json-render, a library for AI-generated UI with guardrails.
  13. GitHub repository: https://github.com/vercel-labs/json-render
  14. Documentation: https://json-render.dev/docs
  15. npm packages: @json-render/core, @json-render/react, @json-render/remotion, @json-render/codegen
  16. You have access to the full json-render documentation via the bash and readFile tools. The docs are available as markdown files in the /workspace/docs/ directory.
  17. When answering questions:
  18. - Use the bash tool to list files (ls /workspace/docs/) or search for content (grep -r "keyword" /workspace/docs/)
  19. - Use the readFile tool to read specific documentation pages (e.g. readFile with path "/workspace/docs/index.md")
  20. - Always base your answers on the actual documentation content
  21. - Be concise and accurate
  22. - If the docs don't cover a topic, say so honestly
  23. - Do NOT include source references or file paths in your response`;
  24. async function loadDocsFiles(): Promise<Record<string, string>> {
  25. const files: Record<string, string> = {};
  26. const results = await Promise.allSettled(
  27. allDocsPages.map(async (page) => {
  28. const slug =
  29. page.href === "/docs" ? "" : page.href.replace(/^\/docs\/?/, "");
  30. const filePath = slug
  31. ? join(
  32. process.cwd(),
  33. "app",
  34. "(main)",
  35. "docs",
  36. ...slug.split("/"),
  37. "page.mdx",
  38. )
  39. : join(process.cwd(), "app", "(main)", "docs", "page.mdx");
  40. const raw = await readFile(filePath, "utf-8");
  41. const md = mdxToCleanMarkdown(raw);
  42. const fileName = slug ? `/docs/${slug}.md` : "/docs/index.md";
  43. return { fileName, md };
  44. }),
  45. );
  46. for (const result of results) {
  47. if (result.status === "fulfilled") {
  48. files[result.value.fileName] = result.value.md;
  49. }
  50. }
  51. return files;
  52. }
  53. function addCacheControl(messages: ModelMessage[]): ModelMessage[] {
  54. if (messages.length === 0) return messages;
  55. return messages.map((message, index) => {
  56. if (index === messages.length - 1) {
  57. return {
  58. ...message,
  59. providerOptions: {
  60. ...message.providerOptions,
  61. anthropic: { cacheControl: { type: "ephemeral" } },
  62. },
  63. };
  64. }
  65. return message;
  66. });
  67. }
  68. export async function POST(req: Request) {
  69. const headersList = await headers();
  70. const ip = headersList.get("x-forwarded-for")?.split(",")[0] ?? "anonymous";
  71. const [minuteResult, dailyResult] = await Promise.all([
  72. minuteRateLimit.limit(ip),
  73. dailyRateLimit.limit(ip),
  74. ]);
  75. if (!minuteResult.success || !dailyResult.success) {
  76. const isMinuteLimit = !minuteResult.success;
  77. return new Response(
  78. JSON.stringify({
  79. error: "Rate limit exceeded",
  80. message: isMinuteLimit
  81. ? "Too many requests. Please wait a moment before trying again."
  82. : "Daily limit reached. Please try again tomorrow.",
  83. }),
  84. {
  85. status: 429,
  86. headers: { "Content-Type": "application/json" },
  87. },
  88. );
  89. }
  90. const { messages }: { messages: UIMessage[] } = await req.json();
  91. const docsFiles = await loadDocsFiles();
  92. const { tools } = await createBashTool({ files: docsFiles });
  93. const result = streamText({
  94. model: DEFAULT_MODEL,
  95. system: SYSTEM_PROMPT,
  96. messages: await convertToModelMessages(messages),
  97. stopWhen: stepCountIs(5),
  98. tools,
  99. prepareStep: ({ messages: stepMessages }) => ({
  100. messages: addCacheControl(stepMessages),
  101. }),
  102. });
  103. return result.toUIMessageStreamResponse();
  104. }