nextjs-chatbot

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Next.js Chatbot

Next.js 聊天机器人

Opinionated blueprint for production chatbots. Focuses on patterns not covered by
/ai-sdk-6
,
/ai-elements
, or
/nextjs-shadcn
— use those skills for general SDK, component, and framework questions.
Reference implementation:
c:\hh-tyo\fair\helpdesk-chatbot
面向生产级聊天机器人的专属蓝图。专注于
/ai-sdk-6
/ai-elements
/nextjs-shadcn
未涵盖的模式——若有通用SDK、组件和框架相关问题,请参考这些技能。
参考实现:
c:\hh-tyo\fair\helpdesk-chatbot

Stack defaults

默认技术栈

  • Runtime: bun
  • Model:
    gpt-5.4
    with
    reasoningEffort: "none"
  • AI SDK:
    ai@6
    ToolLoopAgent
    ,
    createAgentUIStreamResponse
  • UI: shadcn/ui + ai-elements (see
    /ai-elements
    for component docs)
  • ORM: Drizzle + PostgreSQL
  • State: Zustand for client-side chat state (consent, session, suggestions)
  • Attachments: See
    /ai-elements
    Attachments component for file upload
  • Deploy: CSC Rahti 2 / OpenShift (see
    /fair-helpdesk
    for FAIR-specific deploy)
  • 运行时: bun
  • 模型:
    gpt-5.4
    (配置
    reasoningEffort: "none"
  • AI SDK:
    ai@6
    — 包含
    ToolLoopAgent
    createAgentUIStreamResponse
  • UI: shadcn/ui + ai-elements(组件文档请查看
    /ai-elements
  • ORM: Drizzle + PostgreSQL
  • 状态管理: 使用Zustand管理客户端聊天状态(同意信息、会话、建议)
  • 附件: 文件上传功能请查看
    /ai-elements
    的Attachments组件
  • 部署: CSC Rahti 2 / OpenShift(FAIR专属部署请查看
    /fair-helpdesk

Recommended MCP servers

推荐的MCP服务器

Add to your
.claude/settings.json
or IDE MCP config for better dev experience:
json
{
  "mcpServers": {
    "next-devtools": {
      "command": "npx",
      "args": ["-y", "next-devtools-mcp@latest"]
    },
    "ai-elements": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "https://registry.ai-sdk.dev/api/mcp"]
    }
  }
}
  • next-devtools — Next.js route inspection, build diagnostics, config validation. See nextjs.org/docs/app/guides/mcp
  • ai-elements — Browse and search ai-elements component registry with up-to-date docs and examples
添加到你的
.claude/settings.json
或IDE的MCP配置中,以获得更好的开发体验:
json
{
  "mcpServers": {
    "next-devtools": {
      "command": "npx",
      "args": ["-y", "next-devtools-mcp@latest"]
    },
    "ai-elements": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "https://registry.ai-sdk.dev/api/mcp"]
    }
  }
}
  • next-devtools — Next.js路由检查、构建诊断、配置验证。详情请见nextjs.org/docs/app/guides/mcp
  • ai-elements — 浏览和搜索ai-elements组件注册表,获取最新文档和示例

Agent setup

Agent配置

ts
// lib/ai/my-agent.ts
import { openai } from "@ai-sdk/openai";
import { ToolLoopAgent, InferAgentUIMessage, stepCountIs } from "ai";

export function createAgent(opts?: { model?: LanguageModel }) {
  return new ToolLoopAgent({
    model: opts?.model ?? openai("gpt-5.4"),
    instructions,          // system prompt string
    providerOptions: { openai: { reasoningEffort: "none" } },
    tools,                 // { toolName: tool(...) }
    stopWhen: stepCountIs(10),
  });
}

export const agent = createAgent();
export type AgentUIMessage = InferAgentUIMessage<typeof agent>;
Wrap model with
devToolsMiddleware()
from
@ai-sdk/devtools
in development.
Export a factory (
createAgent
) in addition to the singleton — needed for benchmarks with different models.
ts
// lib/ai/my-agent.ts
import { openai } from "@ai-sdk/openai";
import { ToolLoopAgent, InferAgentUIMessage, stepCountIs } from "ai";

export function createAgent(opts?: { model?: LanguageModel }) {
  return new ToolLoopAgent({
    model: opts?.model ?? openai("gpt-5.4"),
    instructions,          // system prompt string
    providerOptions: { openai: { reasoningEffort: "none" } },
    tools,                 // { toolName: tool(...) }
    stopWhen: stepCountIs(10),
  });
}

export const agent = createAgent();
export type AgentUIMessage = InferAgentUIMessage<typeof agent>;
开发环境中,使用
@ai-sdk/devtools
devToolsMiddleware()
包装模型。
除单例外,还需导出工厂函数(
createAgent
)——这是使用不同模型进行基准测试的必要条件。

Route handler

路由处理器

ts
// app/api/chat/route.ts
export const maxDuration = 60;

export async function POST(request: Request) {
  const { messages, chatId, ...consentData } = await request.json();

  // 1. Validate consent — block if missing
  if (!consentData.consentAccepted) {
    return new Response(JSON.stringify({ error: "Consent required" }), { status: 403 });
  }

  // 2. Upsert session — MUST be awaited before streaming starts
  await db.insert(chatSessions).values({ id: chatId, ... })
    .onConflictDoUpdate({ target: chatSessions.id, set: { updatedAt: sql`now()` } });

  // 3. Stream
  return createAgentUIStreamResponse({
    agent,
    uiMessages: messages,
    generateMessageId: createIdGenerator({ prefix: "msg", size: 16 }),
    consumeSseStream: ({ stream }) => consumeStream({ stream }),
    experimental_transform: smoothStream({ delayInMs: 15, chunking: "word" }),
    onFinish: async ({ messages: finished }) => {
      // Save to DB after stream — see persistence.md
    },
  });
}
ts
// app/api/chat/route.ts
export const maxDuration = 60;

export async function POST(request: Request) {
  const { messages, chatId, ...consentData } = await request.json();

  // 1. 验证同意信息——若未同意则拦截
  if (!consentData.consentAccepted) {
    return new Response(JSON.stringify({ error: "Consent required" }), { status: 403 });
  }

  // 2. 插入或更新会话——必须在流开始前等待该操作完成
  await db.insert(chatSessions).values({ id: chatId, ... })
    .onConflictDoUpdate({ target: chatSessions.id, set: { updatedAt: sql`now()` } });

  // 3. 流式传输
  return createAgentUIStreamResponse({
    agent,
    uiMessages: messages,
    generateMessageId: createIdGenerator({ prefix: "msg", size: 16 }),
    consumeSseStream: ({ stream }) => consumeStream({ stream }),
    experimental_transform: smoothStream({ delayInMs: 15, chunking: "word" }),
    onFinish: async ({ messages: finished }) => {
      // 流结束后保存到数据库——请查看persistence.md
    },
  });
}

Adding a new tool

添加新工具

  1. Create
    lib/ai/tools/my-tool.ts
    with
    tool()
    from
    ai
  2. Export from
    lib/ai/tools/index.ts
  3. Add to
    tools
    object in the agent file
  4. Document in the agent's
    instructions
    string
  5. Add UI renderer in
    chat-message.tsx
    (handle
    tool-myTool
    part type)
  1. 使用
    ai
    库的
    tool()
    创建
    lib/ai/tools/my-tool.ts
  2. lib/ai/tools/index.ts
    导出
  3. 添加到Agent文件的
    tools
    对象中
  4. 在Agent的
    instructions
    字符串中添加文档说明
  5. chat-message.tsx
    中添加UI渲染器(处理
    tool-myTool
    类型的消息段)

Building a new chatbot — checklist

构建新聊天机器人——检查清单

  • Scaffold with
    /ai-app
    or
    bunx --bun shadcn@latest create
  • Install:
    bun add ai @ai-sdk/react @ai-sdk/openai zod drizzle-orm postgres
  • Install ai-elements:
    bunx --bun ai-elements@latest
    → Conversation, Message, PromptInput, Loader, Shimmer
  • Create agent:
    lib/ai/agent.ts
    with ToolLoopAgent
  • Create route:
    app/api/chat/route.ts
    with createAgentUIStreamResponse
  • Create chat page using ai-elements components
  • Add tools: one tool at a time, with UI renderer per tool
  • Add persistence: DB schema → session upsert → onFinish save → history load
  • Add consent gating (if needed): privacy wall → consent check in route
  • Add feedback (if needed): thumbs up/down → 202 retry pattern
  • Add HITL approval (if needed): needsApproval tool → approval UI
  • Add suggestions (if needed): POST /api/suggestions → display after response
  • 使用
    /ai-app
    bunx --bun shadcn@latest create
    搭建项目骨架
  • 安装依赖:
    bun add ai @ai-sdk/react @ai-sdk/openai zod drizzle-orm postgres
  • 安装ai-elements:
    bunx --bun ai-elements@latest
    → 包含Conversation、Message、PromptInput、Loader、Shimmer组件
  • 创建Agent:在
    lib/ai/agent.ts
    中使用ToolLoopAgent
  • 创建路由:在
    app/api/chat/route.ts
    中使用createAgentUIStreamResponse
  • 使用ai-elements组件创建聊天页面
  • 添加工具:逐个添加,并为每个工具配置UI渲染器
  • 添加持久化:数据库表结构 → 会话插入或更新 → 流结束后保存 → 加载历史记录
  • 添加同意校验(若需要):隐私墙 → 路由中校验同意信息
  • 添加反馈功能(若需要):点赞/点踩 → 202重试模式
  • 添加人工介入(HITL)审批(若需要):配置
    needsApproval
    工具 → 审批UI
  • 添加后续建议(若需要):POST /api/suggestions → 响应后展示

Verification

验证步骤

After each milestone, verify:
  1. bun dev
    — app starts without errors
  2. Send a message → assistant responds with streaming text
  3. Tool calls → correct UI renders per tool state
  4. DB check:
    SELECT * FROM chat_sessions
    /
    chat_messages
    has rows
  5. Feedback: click thumbs up → DB row updated (may need retry)
  6. Reload page → chat history restores from DB
完成每个里程碑后,请进行以下验证:
  1. bun dev
    — 应用启动无错误
  2. 发送消息 → 助手以流式文本响应
  3. 调用工具 → 根据工具状态渲染正确的UI
  4. 数据库检查:
    SELECT * FROM chat_sessions
    /
    chat_messages
    存在数据行
  5. 反馈功能:点击点赞 → 数据库行更新(可能需要重试)
  6. 刷新页面 → 从数据库恢复聊天历史

Key patterns (reference files)

核心模式(参考文件)

  • HITL approval — tool with
    needsApproval: true
    , 5-state render machine → hitl.md
  • Session persistence + feedback retry — stable IDs, onFinish, race window → persistence.md
  • SQL-first search — FTS + trigram vs RAG decision → search.md
  • Tool UI rendering
    renderToolState<T>
    factory, per-tool components → tool-rendering.md
  • Follow-up suggestions — generateText + Output.object after each response → suggestions.md
  • 人工介入(HITL)审批 — 配置
    needsApproval: true
    的工具、5状态渲染机 → hitl.md
  • 会话持久化 + 反馈重试 — 稳定ID、onFinish回调、竞争窗口 → persistence.md
  • SQL优先搜索 — 全文搜索(FTS)+ trigram与RAG的选择 → search.md
  • 工具UI渲染
    renderToolState<T>
    工厂函数、按工具划分的组件 → tool-rendering.md
  • 后续建议 — 每次响应后调用generateText + Output.object → suggestions.md

When to use vs other skills

与其他技能的适用场景对比

SkillUse for
/nextjs-chatbot
HITL approval, session DB, feedback retry, SQL search, per-tool UI
/ai-sdk-6
General SDK:
generateText
,
streamText
, tool definitions, structured output
/ai-elements
Chat UI components:
Message
,
Shimmer
,
Sources
,
MessageAction
/nextjs-shadcn
Next.js app setup, shadcn components, routing, layouts
/postgres-semantic-search
Advanced search: hybrid FTS+vector, BM25, reranking, HNSW tuning
技能适用场景
/nextjs-chatbot
人工介入(HITL)审批、会话数据库、反馈重试、SQL搜索、按工具渲染UI
/ai-sdk-6
通用SDK操作:
generateText
streamText
、工具定义、结构化输出
/ai-elements
聊天UI组件:
Message
Shimmer
Sources
MessageAction
/nextjs-shadcn
Next.js应用搭建、shadcn组件、路由、布局
/postgres-semantic-search
高级搜索:混合全文搜索+向量检索、BM25、重排序、HNSW调优