{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-chat-openrouter",
  "title": "AI chat (OpenRouter)",
  "description": "Ask AI for your docs: the AI chat wired into DocsLayout, with a chat route that searches your pages and answers through OpenRouter.",
  "dependencies": [
    "@ai-sdk/react@^4.0.0",
    "ai@^7.0.0",
    "@openrouter/ai-sdk-provider@^3.1.0",
    "flexsearch@^0.8.212",
    "fumadocs-core@^16.17.8",
    "zod@^4.6.6"
  ],
  "registryDependencies": [
    "@docscn/ai-chat",
    "@docscn/docs-layout"
  ],
  "files": [
    {
      "path": "registry/base/ai/search.tsx",
      "content": "// Adapted from the Fumadocs CLI's ai/openrouter component (https://github.com/fuma-nama/fumadocs)\n// Copyright (c) 2023 Fuma, MIT License\n\"use client\";\nimport type { ReactNode } from \"react\";\nimport { useChat } from \"@ai-sdk/react\";\nimport {\n  DefaultChatTransport,\n  type InferUITool,\n  type Tool,\n  type UIMessage,\n} from \"ai\";\nimport { type AIChatClientData, AIChatProvider, AIChatSearch } from \"./chat\";\n\nexport { AIChatPanel, AIChatTrigger, useAIChat } from \"./chat\";\n\nexport type SearchTool = Tool<\n  { query: string; limit: number },\n  { doc?: { url: string; title: string } | null }[]\n>;\n\nexport type ChatUIMessage = UIMessage<\n  never,\n  { client: AIChatClientData },\n  { search: InferUITool<SearchTool> }\n>;\n\nexport function AIChat({ children }: { children: ReactNode }) {\n  const chat = useChat<ChatUIMessage>({\n    id: \"search\",\n    throttle: 40,\n    transport: new DefaultChatTransport({\n      api: \"/api/chat\",\n    }),\n  });\n\n  return (\n    <AIChatProvider chat={chat} renderPart={renderPart}>\n      {children}\n    </AIChatProvider>\n  );\n}\n\nfunction renderPart(part: ChatUIMessage[\"parts\"][number], live: boolean) {\n  if (part.type === \"tool-search\")\n    return <AIChatSearch part={part} live={live} />;\n}\n",
      "type": "registry:component",
      "target": "components/ai/search.tsx"
    },
    {
      "path": "registry/base/ai/layout.tsx",
      "content": "// Adapted from the Fumadocs CLI's ai/openrouter component (https://github.com/fuma-nama/fumadocs)\n// Copyright (c) 2023 Fuma, MIT License\n\"use client\";\nimport {\n  DocsLayout as Layout,\n  type DocsLayoutProps,\n} from \"@/components/docs/layouts/docs\";\nimport { AIChat, AIChatPanel, AIChatTrigger, useAIChat } from \"./search\";\n\nexport function DocsLayout(props: DocsLayoutProps) {\n  return (\n    <AIChat>\n      <ChatLayout {...props} />\n      <AIChatTrigger />\n    </AIChat>\n  );\n}\n\nfunction ChatLayout(props: DocsLayoutProps) {\n  const { open, setOpen } = useAIChat();\n\n  return (\n    <Layout\n      {...props}\n      aiChat={{ open, onOpenChange: setOpen, panel: <AIChatPanel /> }}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/ai/layout.tsx"
    },
    {
      "path": "registry/base/blocks/ai-chat-openrouter/app/api/chat/route.ts",
      "content": "// Adapted from the Fumadocs CLI's ai/openrouter component (https://github.com/fuma-nama/fumadocs)\n// Copyright (c) 2023 Fuma, MIT License\nimport { createOpenRouter } from \"@openrouter/ai-sdk-provider\";\nimport {\n  convertToModelMessages,\n  createUIMessageStreamResponse,\n  stepCountIs,\n  streamText,\n  tool,\n  toUIMessageStream,\n  type InferToolOutput,\n} from \"ai\";\nimport { z } from \"zod\";\nimport { source } from \"@/lib/source\";\nimport { Document, type DocumentData } from \"flexsearch\";\nimport type { ChatUIMessage, SearchTool } from \"@/components/ai/search\";\n\ninterface CustomDocument extends DocumentData {\n  url: string;\n  title: string;\n  description: string;\n  content: string;\n}\nconst searchServer = createSearchServer();\n\nasync function createSearchServer() {\n  const search = new Document<CustomDocument>({\n    document: {\n      id: \"url\",\n      index: [\"title\", \"description\", \"content\"],\n      store: true,\n    },\n  });\n\n  const docs = await chunkedAll(\n    source.getPages().map(async (page) => {\n      if (!(\"getText\" in page.data)) return null;\n\n      return {\n        title: page.data.title,\n        description: page.data.description,\n        url: page.url,\n        content: await page.data.getText(\"processed\"),\n      } as CustomDocument;\n    }),\n  );\n\n  for (const doc of docs) {\n    if (doc) search.add(doc);\n  }\n\n  return search;\n}\n\nasync function chunkedAll<O>(promises: Promise<O>[]): Promise<O[]> {\n  const SIZE = 50;\n  const out: O[] = [];\n  for (let i = 0; i < promises.length; i += SIZE) {\n    out.push(...(await Promise.all(promises.slice(i, i + SIZE))));\n  }\n  return out;\n}\n\nconst openrouter = createOpenRouter({\n  apiKey: process.env.OPENROUTER_API_KEY,\n});\n\n/** System prompt, you can update it to provide more specific information */\nconst systemPrompt = [\n  \"You are an AI assistant for a documentation site.\",\n  \"Use the `search` tool to retrieve relevant docs context before answering when needed.\",\n  'A user message may begin with [Client Context], the page they are reading. For questions about \"this page\", search its title.',\n  \"The `search` tool returns raw JSON results from documentation. Use those results to ground your answer and cite sources as markdown links using the document `url` field when available.\",\n  \"If you cannot find the answer in search results, say you do not know and suggest a better search query.\",\n].join(\"\\n\");\n\nexport async function POST(req: Request) {\n  const reqJson = await req.json();\n\n  const result = streamText({\n    model: openrouter.chat(\n      process.env.OPENROUTER_MODEL ?? \"anthropic/claude-sonnet-5.5\",\n    ),\n    stopWhen: stepCountIs(5),\n    tools: {\n      search: searchTool,\n    },\n    messages: [\n      { role: \"system\", content: systemPrompt },\n      ...(await convertToModelMessages<ChatUIMessage>(reqJson.messages ?? [], {\n        convertDataPart(part) {\n          if (part.type === \"data-client\")\n            return {\n              type: \"text\",\n              text: `[Client Context: ${JSON.stringify(part.data)}]`,\n            };\n        },\n      })),\n    ],\n    toolChoice: \"auto\",\n  });\n\n  return createUIMessageStreamResponse({\n    stream: toUIMessageStream({ stream: result.stream }),\n  });\n}\n\nconst searchTool = tool({\n  description: \"Search the docs content and return raw JSON results.\",\n  inputSchema: z.object({\n    query: z.string(),\n    limit: z.number().int().min(1).max(100).default(10),\n  }),\n  async execute({ query, limit }): Promise<InferToolOutput<SearchTool>> {\n    const search = await searchServer;\n    return await search.searchAsync(query, {\n      limit,\n      merge: true,\n      enrich: true,\n    });\n  },\n}) satisfies SearchTool;\n",
      "type": "registry:page",
      "target": "app/api/chat/route.ts"
    }
  ],
  "docs": "Finish the setup with two edits. 1) In app/docs/layout.tsx, import DocsLayout from \"@/components/ai/layout\" instead of \"@/components/docs/layouts/docs\". 2) Set OPENROUTER_API_KEY in .env.local (and optionally OPENROUTER_MODEL, which defaults to anthropic/claude-sonnet-5.5). The chat route reads each page's processed Markdown, so lib/source.ts needs postprocess: { includeProcessedMarkdown: true } in its docs options, as the docs block sets it. See https://docscn.dev/docs/components/ai-chat.",
  "type": "registry:block"
}