route.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. - Do NOT use bash to write, create, modify, or delete files (no tee, cat >, sed -i, echo >, cp, mv, rm, mkdir, touch, etc.) — you are read-only
  21. - Always base your answers on the actual documentation content
  22. - Be concise and accurate
  23. - If the docs don't cover a topic, say so honestly
  24. - Do NOT include source references or file paths in your response
  25. - Do NOT use emojis in your responses`;
  26. async function loadDocsFiles(): Promise<Record<string, string>> {
  27. const files: Record<string, string> = {};
  28. const results = await Promise.allSettled(
  29. allDocsPages.map(async (page) => {
  30. const slug =
  31. page.href === "/docs" ? "" : page.href.replace(/^\/docs\/?/, "");
  32. const filePath = slug
  33. ? join(
  34. process.cwd(),
  35. "app",
  36. "(main)",
  37. "docs",
  38. ...slug.split("/"),
  39. "page.mdx",
  40. )
  41. : join(process.cwd(), "app", "(main)", "docs", "page.mdx");
  42. const raw = await readFile(filePath, "utf-8");
  43. const md = mdxToCleanMarkdown(raw);
  44. const fileName = slug ? `/docs/${slug}.md` : "/docs/index.md";
  45. return { fileName, md };
  46. }),
  47. );
  48. for (const result of results) {
  49. if (result.status === "fulfilled") {
  50. files[result.value.fileName] = result.value.md;
  51. }
  52. }
  53. return files;
  54. }
  55. function addCacheControl(messages: ModelMessage[]): ModelMessage[] {
  56. if (messages.length === 0) return messages;
  57. return messages.map((message, index) => {
  58. if (index === messages.length - 1) {
  59. return {
  60. ...message,
  61. providerOptions: {
  62. ...message.providerOptions,
  63. anthropic: { cacheControl: { type: "ephemeral" } },
  64. },
  65. };
  66. }
  67. return message;
  68. });
  69. }
  70. export async function POST(req: Request) {
  71. const headersList = await headers();
  72. const ip = headersList.get("x-forwarded-for")?.split(",")[0] ?? "anonymous";
  73. const [minuteResult, dailyResult] = await Promise.all([
  74. minuteRateLimit.limit(ip),
  75. dailyRateLimit.limit(ip),
  76. ]);
  77. if (!minuteResult.success || !dailyResult.success) {
  78. const isMinuteLimit = !minuteResult.success;
  79. return new Response(
  80. JSON.stringify({
  81. error: "Rate limit exceeded",
  82. message: isMinuteLimit
  83. ? "Too many requests. Please wait a moment before trying again."
  84. : "Daily limit reached. Please try again tomorrow.",
  85. }),
  86. {
  87. status: 429,
  88. headers: { "Content-Type": "application/json" },
  89. },
  90. );
  91. }
  92. const { messages }: { messages: UIMessage[] } = await req.json();
  93. const docsFiles = await loadDocsFiles();
  94. const {
  95. tools: { bash, readFile },
  96. } = await createBashTool({ files: docsFiles });
  97. const result = streamText({
  98. model: DEFAULT_MODEL,
  99. system: SYSTEM_PROMPT,
  100. messages: await convertToModelMessages(messages),
  101. stopWhen: stepCountIs(5),
  102. tools: {
  103. bash,
  104. readFile,
  105. },
  106. prepareStep: ({ messages: stepMessages }) => ({
  107. messages: addCacheControl(stepMessages),
  108. }),
  109. });
  110. return result.toUIMessageStreamResponse();
  111. }