better-chatbot-patterns
Reusable better-chatbot patterns for custom deployments. Use for server action validators, tool abstraction, multi-AI providers, or encountering auth validation, FormData parsing, workflow execution errors.
git clone --depth 1 https://github.com/secondsky/claude-skills /tmp/better-chatbot-patterns && cp -r /tmp/better-chatbot-patterns/plugins/better-chatbot-patterns/skills/better-chatbot-patterns ~/.claude/skills/better-chatbot-patternsSKILL.md
# better-chatbot-patterns
**Status**: Production Ready
**Last Updated**: 2025-11-21
**Dependencies**: None
**Latest Versions**: next@16.0.3, ai@5.0.98, zod@3.24.2, zustand@5.0.8
---
## Overview
This skill extracts reusable patterns from the better-chatbot project for use in custom AI chatbot implementations. Unlike the `better-chatbot` skill (which teaches project conventions), this skill provides **portable templates** you can adapt to any project.
**Patterns included**:
1. Server action validators (auth, validation, FormData)
2. Tool abstraction system (multi-type tool handling)
3. Multi-AI provider setup
4. Workflow execution patterns
5. State management conventions
---
## Pattern 1: Server Action Validators
**For complete implementation**: Load `references/server-action-patterns.md` when implementing server action validators, auth validation, or FormData parsing.
**What it solves**: Inconsistent auth checks, repeated FormData parsing boilerplate, non-standard error handling, and type safety issues in server actions.
**Three validator patterns**:
1. `validatedAction` - Simple validation (no auth)
2. `validatedActionWithUser` - With user context (auth required)
3. `validatedActionWithPermission` - With permission checks (role-based)
**Quick example**:
```typescript
// Server action with automatic auth + validation
export const updateProfile = validatedActionWithUser(
z.object({ name: z.string(), email: z.string().email() }),
async (data, formData, user) => {
// user is authenticated, data is validated
await db.update(users).set(data).where(eq(users.id, user.id))
return { success: true }
}
)
```
**Adapt to your auth**: Better Auth, Clerk, Auth.js, or custom auth system.
---
## Pattern 2: Tool Abstraction System
**For complete implementation**: Load `references/tool-abstraction-patterns.md` when building multi-type tool systems, MCP integration, or extensible tool architectures.
**What it solves**: Type mismatches at runtime, repeated type checking boilerplate, and difficulty adding new tool types (TypeScript can't enforce runtime types).
**How it works**: Branded type tags enable runtime type narrowing with full TypeScript safety.
**Quick example**:
```typescript
// Runtime type checking with branded tags
async function executeTool(tool: unknown) {
if (VercelAIMcpToolTag.isMaybe(tool)) {
return await tool.execute() // TypeScript knows tool is MCPTool
} else if (VercelAIWorkflowToolTag.isMaybe(tool)) {
return await executeWorkflow(tool.nodes) // TypeScript knows tool is WorkflowTool
}
throw new Error("Unknown tool type")
}
// Create tagged tools
const mcpTool = VercelAIMcpToolTag.create({
type: "mcp",
name: "search",
execute: async () => { /* ... */ }
})
```
**Extensible**: Add new tool types without breaking existing code.
---
## Pattern 3: Multi-AI Provider Setup
**For complete implementation**: Load `references/provider-integration-patterns.md` when setting up multi-AI provider support, configuring Vercel AI SDK, or implementing provider fallbacks.
**What it solves**: Different SDK initialization patterns, provider-specific configurations, and unified interface for switching providers at runtime.
**Supported providers**: OpenAI, Anthropic (Claude), Google (Gemini), xAI (Grok), Groq.
**Quick example**:
```typescript
// Provider registry in lib/ai/providers.ts
export const providers = {
openai: createOpenAI({ apiKey: process.env.OPENAI_API_KEY }),
anthropic: createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY }),
google: createGoogleGenerativeAI({ apiKey: process.env.GOOGLE_API_KEY })
}
// API route with user provider selection
export async function POST(req: Request) {
const { messages, provider, model } = await req.json()
const selectedModel = getModel(provider, model)
return streamText({ model: selectedModel, messages }).toDataStreamResponse()
}
```
**Features**: Fallback strategies, health checks, cost-aware selection.
---
## Pattern 4: State Management (Zustand)
**For complete implementation**: Load `references/state-validation-patterns.md` when implementing Zustand stores, workflow state, or complex nested state management.
**What it solves**: Managing complex nested state without mutations, avoiding re-render issues, and preventing state update bugs.
**Quick example**:
```typescript
// Zustand store with shallow update pattern
export const useWorkflowStore = create<WorkflowStore>((set) => ({
workflow: null,
// Shallow update - no deep mutation
updateNodeStatus: (nodeId, status) =>
set(state => ({
workflow: state.workflow ? {
...state.workflow,
nodes: state.workflow.nodes.map(node =>
node.id === nodeId ? { ...node, status } : node
)
} : null
}))
}))
```
**Patterns included**: Multi-store organization, Immer integration, persist middleware.
---
## Pattern 5: Cross-Field Validation (Zod)
**For complete implementation**: Load `references/state-validation-patterns.md` when implementing cross-field validation, password confirmation, or date ranges.
**What it solves**: Validating related fields (password confirmation, date ranges, conditional requirements) with consistent error messages and business rules.
**Quick example**:
```typescript
// Zod superRefine for cross-field validation
const passwordSchema = z.object({
password: z.string().min(8),
confirmPassword: z.string()
}).superRefine((data, ctx) => {
if (data.password !== data.confirmPassword) {
ctx.addIssue({
path: ["confirmPassword"],
code: z.ZodIssueCode.custom,
message: "Passwords must match"
})
}
})
```
**Use cases**: Password match, date ranges, conditional fields, business rules, array validation.
---
## When to Load References
Load reference files when implementing specific chatbot patterns:
### server-action-patterns.md
Load when:
- **Pattern-based**: Implementing server action validators, auth validation, FormData parsing
- **Auth-Role-based access control (RBAC) with permissions and policies. Use for admin dashboards, enterprise access, multi-tenant apps, fine-grained authorization, or encountering permission hierarchies, role inheritance, policy conflicts.
100+ animated React components (Aceternity UI) for Next.js with Tailwind. Use for hero sections, parallax, 3D effects, or encountering animation, shadcn CLI integration errors.
shadcn/ui AI chat components for conversational interfaces. Use for streaming chat, tool/function displays, reasoning visualization, or encountering Next.js App Router setup, Tailwind v4 integration, AI SDK v5 migration errors.
Vercel AI SDK v5 for backend AI (text generation, structured output, tools, agents). Multi-provider. Use for server-side AI or encountering AI_APICallError, AI_NoObjectGeneratedError, streaming failures.
Vercel AI SDK v5 React hooks (useChat, useCompletion, useObject) for AI chat interfaces. Use for React/Next.js AI apps or encountering parse stream errors, no response, streaming issues.
Secure API authentication with JWT, OAuth 2.0, API keys. Use for authentication systems, third-party integrations, service-to-service communication, or encountering token management, security headers, auth flow errors.
Creates comprehensive API changelogs documenting breaking changes, deprecations, and migration strategies for API consumers. Use when managing API versions, communicating breaking changes, or creating upgrade guides.
Verifies API contracts between services using consumer-driven contracts, schema validation, and tools like Pact. Use when testing microservices communication, preventing breaking changes, or validating OpenAPI specifications.