chatbot-template README

The project's README from github.com/shadcn-ui/chatbot-template. As one markdown file: README.md.

chatbot-template

A minimal chatbot template built with Next.js, the AI SDK, shadcn/ui, shadcn/react, shadcn/typeset and the Vercel AI Gateway.

GitHub stars GitHub forks License

Features

Deploy

Deploy with Vercel

That's it — no configuration needed. Vercel deployments authenticate to the AI Gateway automatically via OIDC, and usage runs on your team's AI Gateway credits.

Local development

pnpm install

Then give the app a gateway credential, either by pulling an OIDC token from your linked Vercel project:

vercel link
vercel env pull

or by creating an API key in the Vercel dashboard (AI Gateway → API Keys) and adding it to .env.local:

cp .env.example .env.local
# then set AI_GATEWAY_API_KEY=...

Start the dev server:

pnpm dev

Configuration

Env var Required Description
AI_GATEWAY_API_KEY Local dev only AI Gateway API key. Not needed on Vercel deployments (OIDC).

The model list lives in lib/models.ts — the first entry is the default model.

Security

The /api/chat route is public and unauthenticated — every request spends your AI Gateway credits. That's fine for a personal demo, but before putting it in front of real traffic you should:

The route already validates the request body, restricts models to lib/models.ts, caps output tokens and step count, and aborts generation on client disconnect — but those bound a single request, not overall volume.

How it works

Tool parts

Assistant messages are a list of typed parts. components/chat-message.tsx switches on part.type and delegates each one to a component in components/parts/:

Part type Component Renders
text text-part.tsx Markdown via react-markdown and shadcn/typeset.
tool-github_repo github-repo-part.tsx A spinner while the lookup runs, then a linked stat line (stars, forks, language).
tool-web_search web-search-part.tsx A "Searching the web…" status while the search runs, then a persistent "Searched the web" line per search.
tool-ask_user ask-user-part.tsx The answered questions inline. Pending questions render in question-card.tsx, pinned to the scroller bottom.
source-url sources-part.tsx Web search citations, deduped into a "Searched N websites" drawer once the message finishes streaming.

Tool parts move through states as the stream progresses — input-streaming → input-available → output-available (or output-error) — and each component switches on part.state to show progress, results, and failures.

Adding your own tool

  1. Create tools/<name>.ts (the filename is the model-facing tool name) exporting a tool() with a description, an inputSchema, and an execute function (omit execute for tools the user answers in the UI, like ask_user), then register it in tools/index.ts.
  2. Add a part component in components/parts/ and a case "tool-<name>" in chat-message.tsx.

Message types are inferred from the tool definitions via InferUITools, so part.input and part.output are fully typed in your part component — renaming a tool field is a build error, not a silent undefined.

Adding components

npx shadcn@latest add button

License

MIT — see LICENSE.

chatbot-template (shadcn-ui/chatbot-template)

Searching Database…

Что это?Минималистичный шаблон чат-бота на Next.js, AI SDK и shadcn/ui, подключённый к работе через Vercel AI Gateway.
Это готовое приложение или стартовый шаблон, на котором я строю своё?Это стартовый шаблон Next.js, который предполагается клонировать или развернуть и расширять своими инструментами и UI, а не устанавливаемая библиотека или пакет.
Как его запустить?Разверните прямо на Vercel без всякой конфигурации — Vercel сама авторизуется в AI Gateway через OIDC, — либо склонируйте репозиторий и запустите dev-сервер Next.js локально, добавив учётные данные шлюза.
Нужен ли ключ AI Gateway для локальной разработки?Да — для локальной разработки нужен либо OIDC-токен из привязанного проекта Vercel, либо API-ключ AI Gateway, заданный как AIGATEWAYAPIKEY в .env.local; на самой Vercel это не требуется.
Безопасно ли выставлять чат-эндпоинт в публичный доступ как есть?Нет — /api/chat по умолчанию публичный и без аутентификации, так что любой, кто его дёргает, сжигает ваши кредиты AI Gateway; в README рекомендуется добавить rate limiting, лимит расходов или аутентификацию до реального трафика.
Можно развернуть где угодно или это привязано к Vercel?Он спроектирован вокруг AI Gateway от Vercel с развёртыванием в один клик и автоматической OIDC-авторизацией; запустить его в другом месте тоже можно, но API-ключ шлюза придётся подставить вручную.
Что делает встроенный пример вызова инструментов?Там есть выполняемый на сервере инструмент поиска GitHub-репозиториев, который модель может вызвать; во время работы он рисует кликабельную строку статистики со звёздами, форками и языком.
Что такое функция анкеты с участием человека (human-in-the-loop)?Модель может задавать уточняющие вопросы через интерактивный инструмент «askuser», на которые пользователь отвечает с помощью shadcn-компонента анкеты, показываемого прямо в чате.
Как добавить свой инструмент в чат-бота?Создайте файл в tools/ с экспортом tool() с описанием, inputSchema и функцией execute, зарегистрируйте его в tools/index.ts, затем добавьте соответствующий part-компонент в components/parts/ для отрисовки.
Каких AI-провайдеров может использовать чат-бот?Из коробки идут адаптеры Anthropic, OpenAI и Vercel AI Gateway из AI SDK, а список выбираемых моделей настраивается в lib/models.ts.
Creator
shadcn-ui
Size
0.1 MB
Stars
1.2K
Updated
CommitOct 15
Age
2mo
Commits · 90 Days