better-chatbot
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesebetter-chatbot Contribution & Standards Skill
better-chatbot 贡献与标准技能
Status: Production Ready
Version: 3.0.0 (Optimized with progressive disclosure)
Last Updated: 2025-12-17
Dependencies: None (references better-chatbot project)
Latest Versions: Next.js 16.0.3, Vercel AI SDK 5.0.98, Better Auth 1.3.34, Drizzle ORM 0.41.0
状态: 已就绪可用于生产环境
版本: 3.0.0(采用渐进式披露优化)
最后更新: 2025-12-17
依赖: 无(引用better-chatbot项目)
最新版本: Next.js 16.0.3, Vercel AI SDK 5.0.98, Better Auth 1.3.34, Drizzle ORM 0.41.0
Overview
概述
better-chatbot is an open-source AI chatbot platform for individuals and teams, built with Next.js 15 and Vercel AI SDK v5. It combines multi-model AI support (OpenAI, Anthropic, Google, xAI, Ollama, OpenRouter) with advanced features like MCP (Model Context Protocol) tool integration, visual workflow builder, realtime voice assistant, and team collaboration.
This skill teaches Claude the project-specific conventions and patterns used in better-chatbot to ensure contributions follow established standards and avoid common pitfalls.
better-chatbot是一款面向个人和团队的开源AI聊天机器人平台,基于Next.js 15和Vercel AI SDK v5构建。它结合了多模型AI支持(OpenAI、Anthropic、Google、xAI、Ollama、OpenRouter)以及高级功能,如MCP(Model Context Protocol)工具集成、可视化流程构建器、实时语音助手和团队协作功能。
本技能旨在向Claude传授better-chatbot项目特有的规范与模式,以确保贡献符合既定标准并避免常见陷阱。
Quick Start
快速开始
Setup Development Environment
搭建开发环境
bash
undefinedbash
undefinedClone and install
克隆并安装依赖
git clone https://github.com/cgoinglove/better-chatbot.git
cd better-chatbot
pnpm install
git clone https://github.com/cgoinglove/better-chatbot.git
cd better-chatbot
pnpm install
Configure environment
配置环境变量
cp .env.example .env
cp .env.example .env
Add your API keys: OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.
添加你的API密钥:OPENAI_API_KEY、ANTHROPIC_API_KEY等
Add database URL: DATABASE_URL="postgresql://..."
添加数据库URL:DATABASE_URL="postgresql://..."
Add auth secret: BETTER_AUTH_SECRET="your-secret"
添加认证密钥:BETTER_AUTH_SECRET="your-secret"
Run development server
启动开发服务器
pnpm dev
undefinedpnpm dev
undefinedCore Commands
核心命令
- - Start development server
pnpm dev - - Production build
pnpm build - - Run unit tests
pnpm test - - Run E2E tests (requires DB + API keys)
pnpm test:e2e - - Lint + type check + tests (run before PR)
pnpm check
- - 启动开发服务器
pnpm dev - - 生产环境构建
pnpm build - - 运行单元测试
pnpm test - - 运行端到端测试(需要数据库和API密钥)
pnpm test:e2e - - 代码检查+类型检查+测试(提交PR前运行)
pnpm check
Repository Structure
仓库结构
better-chatbot/
├── src/
│ ├── app/ # Next.js routes + API
│ ├── components/ # UI components by domain
│ ├── lib/ # Core logic (ai, db, validations)
│ ├── hooks/ # React hooks
│ └── types/ # TypeScript types
├── tests/ # E2E Playwright tests
└── drizzle/ # Database migrationsbetter-chatbot/
├── src/
│ ├── app/ # Next.js路由与API
│ ├── components/ # 按领域划分的UI组件
│ ├── lib/ # 核心逻辑(AI、数据库、验证)
│ ├── hooks/ # React hooks
│ └── types/ # TypeScript类型定义
├── tests/ # Playwright端到端测试
└── drizzle/ # 数据库迁移文件Core Architecture
核心架构
Three-Tier Tool System
三层工具系统
Better-chatbot uses a three-tier tool architecture for AI capabilities:
- MCP Tools - External tools via Model Context Protocol
- Workflow Tools - Visual DAG-based workflows
- Default Tools - Built-in app tools (web search, image generation, etc.)
For details: Load when implementing tools or understanding tool execution.
references/tool-system.mdbetter-chatbot采用三层工具架构实现AI能力:
- MCP工具 - 通过Model Context Protocol接入的外部工具
- 流程工具 - 基于可视化DAG的工作流工具
- 默认工具 - 内置应用工具(网页搜索、图片生成等)
详细信息: 在实现工具或理解工具执行逻辑时,加载。
references/tool-system.mdAPI Patterns
API模式
Routes follow RESTful conventions with streaming-first architecture and defensive programming using wrapper.
safe()For details: Load when building API routes or implementing streaming.
references/api-architecture.md路由遵循RESTful规范,采用流式优先架构,并使用包装器实现防御式编程。
safe()详细信息: 在构建API路由或实现流式响应时,加载。
references/api-architecture.mdComponent Philosophy
组件设计理念
Components organized by feature using compound component pattern. Tools execution separated from rendering.
For details: Load when building UI components.
references/component-patterns.md组件按功能划分,采用复合组件模式。工具执行逻辑与渲染逻辑分离。
详细信息: 在构建UI组件时,加载。
references/component-patterns.mdDatabase & Repository Pattern
数据库与仓库模式
All database access abstracted through repository classes using Drizzle ORM.
For details: Load when implementing database queries.
references/database-patterns.md所有数据库访问通过基于Drizzle ORM的仓库类进行抽象。
详细信息: 在实现数据库查询时,加载。
references/database-patterns.mdTop 5 Errors (Must Know)
五大常见错误(必须掌握)
Error #1: Forgetting Auth Checks in Server Actions
错误1:服务器操作中遗漏权限校验
Error: Unauthorized users accessing protected actions
Why: Manual auth implementation is inconsistent
Prevention: Use or
validatedActionWithUservalidatedActionWithAdminPermissiontypescript
// ❌ BAD: Manual auth check
export async function updateProfile(data: ProfileData) {
const session = await getSession()
if (!session) throw new Error("Unauthorized")
// ... rest of logic
}
// ✅ GOOD: Use validator
export const updateProfile = validatedActionWithUser(
profileSchema,
async (data, formData, user) => {
// user is guaranteed to exist, auto-error handling
}
)错误: 未授权用户访问受保护操作
原因: 手动实现权限校验存在不一致性
预防方案: 使用或
validatedActionWithUservalidatedActionWithAdminPermissiontypescript
// ❌ 错误示例:手动权限校验
export async function updateProfile(data: ProfileData) {
const session = await getSession()
if (!session) throw new Error("Unauthorized")
// ... 其余逻辑
}
// ✅ 正确示例:使用校验器
export const updateProfile = validatedActionWithUser(
profileSchema,
async (data, formData, user) => {
// user已确保存在,自动处理错误
}
)Error #2: Tool Type Mismatches
错误2:工具类型不匹配
Error: Runtime type errors when executing tools
Why: Not checking tool type before execution
Prevention: Use branded type tags for runtime narrowing
typescript
// ❌ BAD: Assuming tool type
const result = await executeMcpTool(tool)
// ✅ GOOD: Check tool type
if (VercelAIMcpToolTag.isMaybe(tool)) {
const result = await executeMcpTool(tool)
} else if (VercelAIWorkflowToolTag.isMaybe(tool)) {
const result = await executeWorkflowTool(tool)
}错误: 执行工具时出现运行时类型错误
原因: 未在执行前检查工具类型
预防方案: 使用品牌类型标签进行运行时类型收窄
typescript
// ❌ 错误示例:假设工具类型
const result = await executeMcpTool(tool)
// ✅ 正确示例:检查工具类型
if (VercelAIMcpToolTag.isMaybe(tool)) {
const result = await executeMcpTool(tool)
} else if (VercelAIWorkflowToolTag.isMaybe(tool)) {
const result = await executeWorkflowTool(tool)
}Error #3: FormData Parsing Errors
错误3:FormData解析错误
Error: Inconsistent error handling for form submissions
Why: Manual FormData parsing with ad-hoc validation
Prevention: Validators handle parsing automatically
typescript
// ❌ BAD: Manual parsing
const name = formData.get("name") as string
if (!name) throw new Error("Name required")
// ✅ GOOD: Validator with Zod
const schema = z.object({ name: z.string().min(1) })
export const action = validatedAction(schema, async (data) => {
// data.name is validated and typed
})错误: 表单提交的错误处理不一致
原因: 手动解析FormData并使用临时校验逻辑
预防方案: 校验器会自动处理解析逻辑
typescript
// ❌ 错误示例:手动解析
const name = formData.get("name") as string
if (!name) throw new Error("Name required")
// ✅ 正确示例:使用Zod校验器
const schema = z.object({ name: z.string().min(1) })
export const action = validatedAction(schema, async (data) => {
// data.name已完成校验并带有类型定义
})Error #4: Cross-Field Validation Issues
错误4:跨字段校验问题
Error: Password mismatch validation not working
Why: Separate validation for related fields
Prevention: Use Zod
superRefinetypescript
// ❌ BAD: Separate checks
if (data.password !== data.confirmPassword) { /* error */ }
// ✅ GOOD: Zod superRefine
const schema = z.object({
password: z.string(),
confirmPassword: z.string()
}).superRefine((data, ctx) => {
if (data.password !== data.confirmPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Passwords don't match",
path: ["confirmPassword"]
})
}
})错误: 密码匹配校验失效
原因: 对关联字段单独进行校验
预防方案: 使用Zod的方法
superRefinetypescript
// ❌ 错误示例:单独校验
if (data.password !== data.confirmPassword) { /* 错误处理 */ }
// ✅ 正确示例:Zod superRefine
const schema = z.object({
password: z.string(),
confirmPassword: z.string()
}).superRefine((data, ctx) => {
if (data.password !== data.confirmPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Passwords don't match",
path: ["confirmPassword"]
})
}
})Error #5: Zustand State Mutation
错误5:Zustand状态直接修改
Error: State updates not triggering re-renders
Why: Mutating state directly instead of creating new objects
Prevention: Use shallow updates with spread operator
typescript
// ❌ BAD: Direct mutation
set((state) => {
state.user.name = "New Name" // Mutation!
})
// ✅ GOOD: Shallow update
set((state) => ({
user: { ...state.user, name: "New Name" }
}))For all errors: Load when debugging issues beyond the top 5.
references/common-errors.md错误: 状态更新未触发重渲染
原因: 直接修改状态而非创建新对象
预防方案: 使用扩展运算符进行浅更新
typescript
// ❌ 错误示例:直接修改
set((state) => {
state.user.name = "New Name" // 直接修改!
})
// ✅ 正确示例:浅更新
set((state) => ({
user: { ...state.user, name: "New Name" }
}))所有错误详情: 在调试超出上述五大错误的问题时,加载。
references/common-errors.mdCritical Rules
关键规则
Always Do
必须执行
✅ Use or for server actions
✅ Check tool types with branded type tags before execution
✅ Use Zod for cross-field validation
✅ Add unit tests (happy path + one failure mode)
✅ Run before PR submission
✅ Include visual documentation for UI changes
✅ Use Conventional Commit format for PR titles
✅ Run E2E tests when touching critical flows
validatedActionWithUservalidatedActionWithAdminPermissionsuperRefinepnpm check✅ 对服务器操作使用或
✅ 在执行工具前使用品牌类型标签检查工具类型
✅ 使用Zod的进行跨字段校验
✅ 添加单元测试(正常流程+至少一种错误场景)
✅ 提交PR前运行
✅ 对UI变更提供可视化文档
✅ PR标题使用约定式提交格式
✅ 修改关键流程时运行端到端测试
validatedActionWithUservalidatedActionWithAdminPermissionsuperRefinepnpm checkNever Do
严禁操作
❌ Implement server actions without auth validators
❌ Assume tool type without runtime check
❌ Parse FormData manually (use validators)
❌ Mutate Zustand state directly (use shallow updates)
❌ Skip first-user tests on clean database
❌ Commit without running
❌ Submit PR without visual docs (if UI change)
❌ Use non-conventional commit format
pnpm check❌ 未添加权限校验器就实现服务器操作
❌ 未做运行时检查就假设工具类型
❌ 手动解析FormData(使用校验器)
❌ 直接修改Zustand状态(使用浅更新)
❌ 在全新数据库上跳过首次用户测试
❌ 未运行就提交代码
❌ 提交UI变更的PR时未提供可视化文档
❌ 使用非约定式提交格式
pnpm checkWhen to Load References
何时加载参考文档
Load reference files when working on specific aspects of better-chatbot:
在处理better-chatbot的特定模块时加载对应参考文件:
API Architecture (references/api-architecture.md
)
references/api-architecture.mdAPI架构 (references/api-architecture.md
)
references/api-architecture.mdLoad when:
- Implementing new API routes or endpoints
- Understanding route handler patterns
- Working with streaming responses
- Implementing defensive programming with safe()
- Troubleshooting API-related issues
- Building shared business logic
在以下场景加载:
- 实现新的API路由或端点
- 理解路由处理器模式
- 处理流式响应
- 使用safe()实现防御式编程
- 排查API相关问题
- 构建共享业务逻辑
Tool System (references/tool-system.md
)
references/tool-system.md工具系统 (references/tool-system.md
)
references/tool-system.mdLoad when:
- Adding new MCP tools
- Creating workflow tools
- Understanding tool lifecycle
- Debugging tool execution
- Implementing tool filtering or mentions
- Working with the three-tier tool architecture
在以下场景加载:
- 添加新的MCP工具
- 创建流程工具
- 理解工具生命周期
- 调试工具执行逻辑
- 实现工具过滤或提及功能
- 处理三层工具架构相关内容
Component Patterns (references/component-patterns.md
)
references/component-patterns.md组件模式 (references/component-patterns.md
)
references/component-patterns.mdLoad when:
- Building new UI components
- Understanding compound component pattern
- Implementing state management
- Working with Zustand stores
- Designing component APIs
- Separating tool execution from rendering
在以下场景加载:
- 构建新的UI组件
- 理解复合组件模式
- 实现状态管理
- 处理Zustand存储
- 设计组件API
- 分离工具执行与渲染逻辑
Database Patterns (references/database-patterns.md
)
references/database-patterns.md数据库模式 (references/database-patterns.md
)
references/database-patterns.mdLoad when:
- Creating new repository classes
- Writing complex database queries
- Implementing transactions
- Understanding the repository pattern
- Troubleshooting database issues
- Working with Drizzle ORM
在以下场景加载:
- 创建新的仓库类
- 编写复杂数据库查询
- 实现事务
- 理解仓库模式
- 排查数据库问题
- 使用Drizzle ORM
Architectural Principles (references/architectural-principles.md
)
references/architectural-principles.md架构原则 (references/architectural-principles.md
)
references/architectural-principles.mdLoad when:
- Making architectural decisions
- Understanding design philosophy
- Implementing progressive enhancement
- Following streaming-first patterns
- Ensuring defensive programming
- Understanding DRY principle application
在以下场景加载:
- 做出架构决策
- 理解设计理念
- 实现渐进式增强
- 遵循流式优先模式
- 确保防御式编程
- 理解DRY原则的应用
Extension Points (references/extension-points.md
)
references/extension-points.md扩展点 (references/extension-points.md
)
references/extension-points.mdLoad when:
- Extending the chatbot with custom features
- Adding new tool types
- Customizing existing behavior
- Understanding plugin architecture
- Integrating external services
在以下场景加载:
- 为聊天机器人扩展自定义功能
- 添加新的工具类型
- 定制现有行为
- 理解插件架构
- 集成外部服务
UX Patterns (references/ux-patterns.md
)
references/ux-patterns.mdUX模式 (references/ux-patterns.md
)
references/ux-patterns.mdLoad when:
- Implementing @mention functionality
- Understanding UX patterns
- Working with multi-model support
- Designing interaction flows
- Building chat UI components
在以下场景加载:
- 实现@提及功能
- 理解UX模式
- 处理多模型支持
- 设计交互流程
- 构建聊天UI组件
Templates (references/templates.md
)
references/templates.md模板 (references/templates.md
)
references/templates.mdLoad when:
- Adding new routes, tools, or components
- Following code templates
- Understanding complete implementation examples
- Starting new features from scratch
- Implementing standard patterns
在以下场景加载:
- 添加新的路由、工具或组件
- 遵循代码模板
- 理解完整实现示例
- 从零开始开发新功能
- 实现标准模式
Server Actions (references/server-actions.md
)
references/server-actions.md服务器操作 (references/server-actions.md
)
references/server-actions.mdLoad when:
- Implementing server actions
- Understanding action validators
- Following server-side validation patterns
- Troubleshooting server action issues
- Working with FormData
在以下场景加载:
- 实现服务器操作
- 理解操作校验器
- 遵循服务端校验模式
- 排查服务器操作问题
- 处理FormData
Common Errors (references/common-errors.md
)
references/common-errors.md常见错误 (references/common-errors.md
)
references/common-errors.mdLoad when:
- Debugging issues beyond the top 5 errors
- Encountering specific error messages
- Understanding error patterns
- Looking for solutions to common problems
- Preventing known issues
在以下场景加载:
- 调试超出五大错误的问题
- 遇到特定错误信息
- 理解错误模式
- 寻找常见问题的解决方案
- 预防已知问题
Repository Guidelines (references/AGENTS.md
)
references/AGENTS.md仓库指南 (references/AGENTS.md
)
references/AGENTS.mdLoad when:
- Understanding project structure
- Following coding conventions
- Setting up development environment
- Running tests or builds
- Understanding commit/PR guidelines
在以下场景加载:
- 理解项目结构
- 遵循编码规范
- 搭建开发环境
- 运行测试或构建
- 理解提交/PR指南
Contributing (references/CONTRIBUTING.md
)
references/CONTRIBUTING.md贡献指南 (references/CONTRIBUTING.md
)
references/CONTRIBUTING.mdLoad when:
- Preparing to contribute
- Understanding PR process
- Following commit message conventions
- Submitting pull requests
- Adding visual documentation
在以下场景加载:
- 准备贡献代码
- 理解PR流程
- 遵循提交信息规范
- 提交拉取请求
- 添加可视化文档
Using Bundled Resources
使用捆绑资源
This skill includes 12 reference files:
Technical References (10 files):
- - API patterns and route handlers
api-architecture.md - - Three-tier tool architecture
tool-system.md - - UI component design
component-patterns.md - - Repository pattern and Drizzle ORM
database-patterns.md - - Design philosophy
architectural-principles.md - - How to extend the system
extension-points.md - - UX patterns and @mentions
ux-patterns.md - - Code templates for routes/tools/components
templates.md - - Server action validators
server-actions.md - - Complete error catalog
common-errors.md
Repository References (2 files):
- - Repository structure and development commands
AGENTS.md - - Contribution workflow and PR guidelines
CONTRIBUTING.md
Load references on-demand when specific knowledge is needed. See "When to Load References" section for triggers.
本技能包含12个参考文件:
技术参考(10个文件):
- - API模式与路由处理器
api-architecture.md - - 三层工具架构
tool-system.md - - UI组件设计
component-patterns.md - - 仓库模式与Drizzle ORM
database-patterns.md - - 设计理念
architectural-principles.md - - 系统扩展方法
extension-points.md - - UX模式与@提及
ux-patterns.md - - 路由/工具/组件的代码模板
templates.md - - 服务器操作校验器
server-actions.md - - 完整错误目录
common-errors.md
仓库参考(2个文件):
- - 仓库结构与开发命令
AGENTS.md - - 贡献流程与PR指南
CONTRIBUTING.md
在需要特定知识时按需加载参考文档。请查看「何时加载参考文档」部分了解触发条件。
Dependencies
依赖
Core:
- Next.js 15+ (App Router)
- Vercel AI SDK 5+
- Better Auth 1.3+
- Drizzle ORM 0.40+
- PostgreSQL
Testing:
- Vitest (unit tests)
- Playwright (E2E tests)
Tools:
- TypeScript 5+
- Biome (formatting + linting)
- pnpm 8+
核心依赖:
- Next.js 15+(App Router)
- Vercel AI SDK 5+
- Better Auth 1.3+
- Drizzle ORM 0.40+
- PostgreSQL
测试依赖:
- Vitest(单元测试)
- Playwright(端到端测试)
工具依赖:
- TypeScript 5+
- Biome(格式化+代码检查)
- pnpm 8+
Official Documentation
官方文档
- Repository: https://github.com/cgoinglove/better-chatbot
- Vercel AI SDK: https://sdk.vercel.ai/docs
- Better Auth: https://www.better-auth.com/docs
- Drizzle ORM: https://orm.drizzle.team/docs/overview
- MCP Spec: https://modelcontextprotocol.io/introduction
- 仓库: https://github.com/cgoinglove/better-chatbot
- Vercel AI SDK: https://sdk.vercel.ai/docs
- Better Auth: https://www.better-auth.com/docs
- Drizzle ORM: https://orm.drizzle.team/docs/overview
- MCP规范: https://modelcontextprotocol.io/introduction
Production Example
生产环境示例
This skill is based on the production better-chatbot repository with 48 E2E tests covering core functionality, active development, and growing community contributions.
Last verified: 2025-12-17 | Version: 3.0.0
本技能基于生产环境中的better-chatbot仓库,该仓库包含48个端到端测试覆盖核心功能,处于活跃开发状态,且社区贡献持续增长。
最后验证: 2025-12-17 | 版本: 3.0.0