route.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. - Do NOT use emojis in your responses`;
  25. async function loadDocsFiles(): Promise<Record<string, string>> {
  26. const files: Record<string, string> = {};
  27. const results = await Promise.allSettled(
  28. allDocsPages.map(async (page) => {
  29. const slug =
  30. page.href === "/docs" ? "" : page.href.replace(/^\/docs\/?/, "");
  31. const filePath = slug
  32. ? join(
  33. process.cwd(),
  34. "app",
  35. "(main)",
  36. "docs",
  37. ...slug.split("/"),
  38. "page.mdx",
  39. )
  40. : join(process.cwd(), "app", "(main)", "docs", "page.mdx");
  41. const raw = await readFile(filePath, "utf-8");
  42. const md = mdxToCleanMarkdown(raw);
  43. const fileName = slug ? `/docs/${slug}.md` : "/docs/index.md";
  44. return { fileName, md };
  45. }),
  46. );
  47. for (const result of results) {
  48. if (result.status === "fulfilled") {
  49. files[result.value.fileName] = result.value.md;
  50. }
  51. }
  52. return files;
  53. }
  54. function addCacheControl(messages: ModelMessage[]): ModelMessage[] {
  55. if (messages.length === 0) return messages;
  56. return messages.map((message, index) => {
  57. if (index === messages.length - 1) {
  58. return {
  59. ...message,
  60. providerOptions: {
  61. ...message.providerOptions,
  62. anthropic: { cacheControl: { type: "ephemeral" } },
  63. },
  64. };
  65. }
  66. return message;
  67. });
  68. }
  69. export async function POST(req: Request) {
  70. const headersList = await headers();
  71. const ip = headersList.get("x-forwarded-for")?.split(",")[0] ?? "anonymous";
  72. const [minuteResult, dailyResult] = await Promise.all([
  73. minuteRateLimit.limit(ip),
  74. dailyRateLimit.limit(ip),
  75. ]);
  76. if (!minuteResult.success || !dailyResult.success) {
  77. const isMinuteLimit = !minuteResult.success;
  78. return new Response(
  79. JSON.stringify({
  80. error: "Rate limit exceeded",
  81. message: isMinuteLimit
  82. ? "Too many requests. Please wait a moment before trying again."
  83. : "Daily limit reached. Please try again tomorrow.",
  84. }),
  85. {
  86. status: 429,
  87. headers: { "Content-Type": "application/json" },
  88. },
  89. );
  90. }
  91. const { messages }: { messages: UIMessage[] } = await req.json();
  92. const docsFiles = await loadDocsFiles();
  93. const { tools } = await createBashTool({ files: docsFiles });
  94. const result = streamText({
  95. model: DEFAULT_MODEL,
  96. system: SYSTEM_PROMPT,
  97. messages: await convertToModelMessages(messages),
  98. stopWhen: stepCountIs(5),
  99. tools,
  100. prepareStep: ({ messages: stepMessages }) => ({
  101. messages: addCacheControl(stepMessages),
  102. }),
  103. });
  104. return result.toUIMessageStreamResponse();
  105. }