nextjs-chatbot
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNext.js Chatbot
Next.js 聊天机器人
Opinionated blueprint for production chatbots. Focuses on patterns not covered by , , or — use those skills for general SDK, component, and framework questions.
/ai-sdk-6/ai-elements/nextjs-shadcnReference implementation:
c:\hh-tyo\fair\helpdesk-chatbot面向生产级聊天机器人的专属蓝图。专注于、或未涵盖的模式——若有通用SDK、组件和框架相关问题,请参考这些技能。
/ai-sdk-6/ai-elements/nextjs-shadcn参考实现:
c:\hh-tyo\fair\helpdesk-chatbotStack defaults
默认技术栈
- Runtime: bun
- Model: with
gpt-5.4reasoningEffort: "none" - AI SDK: —
ai@6,ToolLoopAgentcreateAgentUIStreamResponse - UI: shadcn/ui + ai-elements (see for component docs)
/ai-elements - ORM: Drizzle + PostgreSQL
- State: Zustand for client-side chat state (consent, session, suggestions)
- Attachments: See Attachments component for file upload
/ai-elements - Deploy: CSC Rahti 2 / OpenShift (see for FAIR-specific deploy)
/fair-helpdesk
- 运行时: bun
- 模型: (配置
gpt-5.4)reasoningEffort: "none" - AI SDK: — 包含
ai@6、ToolLoopAgentcreateAgentUIStreamResponse - UI: shadcn/ui + ai-elements(组件文档请查看)
/ai-elements - ORM: Drizzle + PostgreSQL
- 状态管理: 使用Zustand管理客户端聊天状态(同意信息、会话、建议)
- 附件: 文件上传功能请查看的Attachments组件
/ai-elements - 部署: CSC Rahti 2 / OpenShift(FAIR专属部署请查看)
/fair-helpdesk
Recommended MCP servers
推荐的MCP服务器
Add to your or IDE MCP config for better dev experience:
.claude/settings.jsonjson
{
"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
添加到你的或IDE的MCP配置中,以获得更好的开发体验:
.claude/settings.jsonjson
{
"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 from in development.
devToolsMiddleware()@ai-sdk/devtoolsExport a factory () in addition to the singleton — needed for benchmarks with different models.
createAgentts
// 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/devtoolsdevToolsMiddleware()除单例外,还需导出工厂函数()——这是使用不同模型进行基准测试的必要条件。
createAgentRoute 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
添加新工具
- Create with
lib/ai/tools/my-tool.tsfromtool()ai - Export from
lib/ai/tools/index.ts - Add to object in the agent file
tools - Document in the agent's string
instructions - Add UI renderer in (handle
chat-message.tsxpart type)tool-myTool
- 使用库的
ai创建tool()lib/ai/tools/my-tool.ts - 从导出
lib/ai/tools/index.ts - 添加到Agent文件的对象中
tools - 在Agent的字符串中添加文档说明
instructions - 在中添加UI渲染器(处理
chat-message.tsx类型的消息段)tool-myTool
Building a new chatbot — checklist
构建新聊天机器人——检查清单
- Scaffold with or
/ai-appbunx --bun shadcn@latest create - Install:
bun add ai @ai-sdk/react @ai-sdk/openai zod drizzle-orm postgres - Install ai-elements: → Conversation, Message, PromptInput, Loader, Shimmer
bunx --bun ai-elements@latest - Create agent: with ToolLoopAgent
lib/ai/agent.ts - Create route: with createAgentUIStreamResponse
app/api/chat/route.ts - 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:→ 包含Conversation、Message、PromptInput、Loader、Shimmer组件
bunx --bun ai-elements@latest - 创建Agent:在中使用ToolLoopAgent
lib/ai/agent.ts - 创建路由:在中使用createAgentUIStreamResponse
app/api/chat/route.ts - 使用ai-elements组件创建聊天页面
- 添加工具:逐个添加,并为每个工具配置UI渲染器
- 添加持久化:数据库表结构 → 会话插入或更新 → 流结束后保存 → 加载历史记录
- 添加同意校验(若需要):隐私墙 → 路由中校验同意信息
- 添加反馈功能(若需要):点赞/点踩 → 202重试模式
- 添加人工介入(HITL)审批(若需要):配置工具 → 审批UI
needsApproval - 添加后续建议(若需要):POST /api/suggestions → 响应后展示
Verification
验证步骤
After each milestone, verify:
- — app starts without errors
bun dev - Send a message → assistant responds with streaming text
- Tool calls → correct UI renders per tool state
- DB check: /
SELECT * FROM chat_sessionshas rowschat_messages - Feedback: click thumbs up → DB row updated (may need retry)
- Reload page → chat history restores from DB
完成每个里程碑后,请进行以下验证:
- — 应用启动无错误
bun dev - 发送消息 → 助手以流式文本响应
- 调用工具 → 根据工具状态渲染正确的UI
- 数据库检查:/
SELECT * FROM chat_sessions存在数据行chat_messages - 反馈功能:点击点赞 → 数据库行更新(可能需要重试)
- 刷新页面 → 从数据库恢复聊天历史
Key patterns (reference files)
核心模式(参考文件)
- HITL approval — tool with , 5-state render machine → hitl.md
needsApproval: true - Session persistence + feedback retry — stable IDs, onFinish, race window → persistence.md
- SQL-first search — FTS + trigram vs RAG decision → search.md
- Tool UI rendering — factory, per-tool components → tool-rendering.md
renderToolState<T> - Follow-up suggestions — generateText + Output.object after each response → suggestions.md
- 人工介入(HITL)审批 — 配置的工具、5状态渲染机 → hitl.md
needsApproval: true - 会话持久化 + 反馈重试 — 稳定ID、onFinish回调、竞争窗口 → persistence.md
- SQL优先搜索 — 全文搜索(FTS)+ trigram与RAG的选择 → search.md
- 工具UI渲染 — 工厂函数、按工具划分的组件 → tool-rendering.md
renderToolState<T> - 后续建议 — 每次响应后调用generateText + Output.object → suggestions.md
When to use vs other skills
与其他技能的适用场景对比
| Skill | Use for |
|---|---|
| HITL approval, session DB, feedback retry, SQL search, per-tool UI |
| General SDK: |
| Chat UI components: |
| Next.js app setup, shadcn components, routing, layouts |
| Advanced search: hybrid FTS+vector, BM25, reranking, HNSW tuning |
| 技能 | 适用场景 |
|---|---|
| 人工介入(HITL)审批、会话数据库、反馈重试、SQL搜索、按工具渲染UI |
| 通用SDK操作: |
| 聊天UI组件: |
| Next.js应用搭建、shadcn组件、路由、布局 |
| 高级搜索:混合全文搜索+向量检索、BM25、重排序、HNSW调优 |