Back to Skills

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.

deploymentai
By secondsky
17928Updated 1 day agoTypeScriptMIT

Skill Content

# 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-based**: Setting up authentication checks, user context, permission systems
- **Validation-based**: Building form validation, schema validation, error handling
- **Adaptation-based**: Adapting patterns to Better Auth, Clerk, Auth.js, or custom auth

### tool-abstraction-patterns.md
Load when:
- **Tool-based**: Building multi-type tool systems, MCP integration, workflow tools
- **Type-based**: Implementing runtime type checking, branded types, type narrowing
- **Execution-based**: Creating tool executors, tool dispatchers, extensible tool systems
- **Extension-based**: Adding new tool types to existing systems

### provider-integration-patterns.md
Load when:
- **Provider-based**: Setting up multi-AI provider support (OpenAI, Anthropic, Google, xAI, Groq)
- **Integration-based**: Configuring Vercel AI SDK, provider SDKs, model registries
- **Switching-based**: Implementing provider fallbacks, user model selection, dynamic model loading
- **Configuration-based**: Managing API keys, base URLs, provider-specific settings

### state-validation-patterns.md
Load when:
- **State-based**: Implementing Zustand stores, workflow state, complex nested state
- **Update-based**: Building shallow update patterns, mutation-free updates, state synchronization
- **Validation-based**: Creating cross-field validation, password confirmation, date ranges
- **Workflow-based**: Managing workflow execution state, node status tracking, dynamic data updates

---

## Critical Rules

### Always Do

✅ Adapt patterns to your auth system (Better Auth, Clerk, Auth.js, etc.)
✅ Use branded type tags for runtime type checking
✅ Use shallow updates for nested Zustand state
✅ Use Zod `superRefine` for cross-field validation
✅ Type your tool abstractions properly

### Never Do

❌ Copy code without adapting to your auth/role system
❌ Assume tool type without runtime check
❌ Mutate Zustand state directly
❌ Use separate validators for related fields
❌ Skip type branding for extensible systems

---

## Known Issues Prevention

This skill prevents **5** common issues:

### Issue #1: Inconsistent Auth Checks
**Prevention**: Use `validatedActionWithUser` pattern (adapt to your auth)

### Issue #2: Tool Type Mismatches
**Prevention**: Use branded type tags with `.isMaybe()` checks

### Issue #3: State Mutation Bugs
**Prevention**: Use shallow Zustand update pattern

### Issue #4: Cross-Field Validation Failures
**Prevention**: Use Zod `superRefine` for related fields

### Issue #5: Provider Configuration Errors
**Prevention**: Use provider registry with unified interface

---

## Using Bundled Resources

### Templates (templates/)

- `templates/action-utils.ts` - Complete server action validators
- `templates/tool-tags.ts` - Complete tool abstraction system
- `templates/providers.ts` - Multi-AI provider setup
- `templates/workflow-store.ts` - Zustand workflow store

**Copy to your project** and adapt placeholders (`getUser()`, `checkPermission()`, etc.)

---

## Dependencies

**Required**:
- zod@3.24.2 - Validation (all patterns)
- zustand@5.0.3 - State management (Pattern 4)
- ai@5.0.82 - Vercel AI SDK (Pattern 3)

**Optional** (based on patterns used):
- @ai-sdk/openai - OpenAI provider
- @ai-sdk/anthropic - Anthropic provider
- @ai-sdk/google - Google provider

---

## Official Documentation

- **Vercel AI SDK**: https://sdk.vercel.ai/docs
- **Zod**: https://zod.dev
- **Zustand**: https://zustand-demo.pmnd.rs
- **better-chatbot** (source): https://github.com/cgoinglove/better-chatbot

---

## Production Example

These patterns are extracted from **better-chatbot**:
- **Live**: https://betterchatbot.vercel.app
- **Tests**: 48+ E2E tests passing
- **Errors**: 0 (patterns proven in production)
- **Validation**: ✅ Multi-user, multi-provider, workflow execution

---

**Token Efficiency**: ~65% savings | **Errors Prevented**: 5 | **Production Verified**: Yes

How to use

  1. Copy the skill content above
  2. Create a .claude/skills directory in your project
  3. Save as .claude/skills/claude-skills-better-chatbot-patterns.md
  4. Use /claude-skills-better-chatbot-patterns in Claude Code to invoke this skill

Claude Code Skills Collection

170 production-ready skills for Claude Code CLI

Version 3.3.1 | Last Updated: 2026-05-14

<div align="center">

🔌 Platform Support

This repository uses Claude Plugin Patterns — natively supported by:

PlatformStatusNotes
Claude CodeNativeFull marketplace support
Factory DroidNativeFull marketplace support
</div> **For all other Platforms like opencode, codex and others, you can use https://github.com/enulus/OpenPackage **

A curated collection of battle-tested skills for building modern web applications with Cloudflare, AI integrations, React, Tailwind, and more.

PS: if skills.sh warns about any skill: Their scan process is a outdated LLM which flags newest versions pins (like in ZOD) as non existent and by that potentially malicous.


Quick Start

Marketplace Installation (Recommended)

# Add the marketplace
/plugin marketplace add https://github.com/secondsky/claude-skills

# Install individual skills as needed
/plugin install cloudflare-d1@claude-skills
/plugin install tailwind-v4-shadcn@claude-skills
/plugin install ai-sdk-core@claude-skills

See MARKETPLACE.md for complete catalog of all 170 skills.

Bulk Installation (Contributors)

# Clone the repository
git clone https://github.com/secondsky/claude-skills.git
cd claude-skills

# Install all 170 skills at once
./scripts/install-all.sh

# Or install individual skills
./scripts/install-skill.sh cloudflare-d1

Repository Structure

This repository contains 170 production-tested skills for Claude Code, each focused on a specific technology or capability.

Individual Skills: Each skill is a standalone unit with:

  • SKILL.md - Core knowledge and guidance
  • Templates - Working code examples
  • References - Extended documentation
  • Scripts - Helper utilities

Installation Options:

  1. Individual - Install only the skills you need via marketplace
  2. Bulk - Install all 170 skills using ./scripts/install-all.sh

Available Skills (170 Individual Skills)

Each skill is individually installable. Install only the skills you need.

Full Catalog: See MARKETPLACE.md for detailed listings.

Categories

CategorySkillsExamples
tooling29turborepo, plan-interview, code-review
frontend26nuxt-v4, nuxt-v5, tailwind-v4-shadcn, tanstack-query, nuxt-studio, maz-ui, threejs
cloudflare21cloudflare-d1, cloudflare-workers-ai, cloudflare-agents
ai20openai-agents, claude-api, ai-sdk-core
api16api-design-principles, graphql-implementation
web10hono-routing, firecrawl-scraper, web-performance
mobile7swift-best-practices, react-native-app, react-native-skills
database6drizzle-orm-d1, neon-vercel-postgres, supabase-postgres-best-practices
security6csrf-protection, access-control-rbac
auth4better-auth
testing4vitest-testing, playwright-testing
design4design-review, design-system-creation
woocommerce4woocommerce-backend-dev
cms4hugo, sveltia-cms, wordpress-plugin-core
architecture3microservices-patterns, architecture-patterns
data3sql-query-optimization, recommendation-engine
seo2seo-optimizer, seo-keyword-cluster-builder
documentation1technical-specification

How It Works

Auto-Discovery

Claude Code automatically checks ~/.claude/skills/ for relevant skills before planning tasks:

User: "Set up a Cloudflare Worker with D1 database"
           ↓
Claude: [Checks skills automatically]
           ↓
Claude: "Found cloudflare-d1 skills.
         These prevent 12 documented errors. Use them?"
           ↓
User: "Yes"
           ↓
Result: Production-ready setup, zero errors, ~65% token savings

Note: Due to token limits, not all skills may be visible at once. See ⚠️ Important: Token Limits below.

Skill Structure

Each skill includes:

skills/[skill-name]/
├── SKILL.md              # Complete documentation
├── .claude-plugin/
│   └── plugin.json       # Plugin metadata
├── templates/            # Ready-to-copy templates
├── scripts/              # Automation scripts
└── references/           # Extended documentation

Recent Additions

May 2026

Supply Chain Security (cross-cutting):

  • dependency-upgrade expanded with Socket CLI integration — proactive malicious package detection, typosquatting alerts, and CI/CD security gates. New 418-line reference guide, 2 GitHub Actions templates, and expanded supply chain security comparison (3 tools)
  • 31 skills now include "Secure Installation" guidance — contextually-tailored security sections across all high-risk skill categories (scaffolding, MCP/agent SDKs, multi-provider installs, Docker, CI/CD). Covers 8 Bun skills, 5 Nuxt skills, 6 Cloudflare skills, 4 AI/agent skills, and 8 frontend/tooling skills
  • Supply chain security is now a first-class cross-cutting concern woven into the skill collection — not a standalone topic

February - April 2026

Full-Stack Frameworks:

  • nuxt-v5 (v1.0.0) - Full Nuxt 5 support with 4 skills (core, data, server, production), 3 diagnostic agents, and interactive setup wizard
  • supabase-postgres-best-practices - 30 Postgres optimization rules from Supabase across 8 categories
  • threejs (v1.0.0) - 3D web graphics: scenes, geometries, shaders, animations, post-processing

Infrastructure:

  • JSON schema validation - Automated plugin.json validation with CI support
  • GitHub issue templates - Skill-specific issue templates for bug reports, feature requests, and submissions

Plugin Enhancements:

  • mutation-testing - Added Bun native runner support
  • dependency-upgrade - Added supply chain security content

December 2025 - January 2026

Frontend Expansion:

  • nuxt-studio (v1.0.0) - Visual CMS for Nuxt Content with live preview, OAuth auth, and R2 storage integration
  • maz-ui (v1.0.0) - 50+ Vue/Nuxt components with theming, i18n, form generation, and 14 composables

Developer Workflow:

  • plan-interview (v2.0.0) - Adaptive interview-driven spec generation with autonomous quality review
  • turborepo (v2.8.0) - Updated to official Vercel skill with enhanced monorepo build optimization

Mobile Development:

  • react-native-skills (v1.0.0) - React Native & Expo best practices with performance optimization patterns

Enhanced Authentication:

  • better-auth (v2.2.0) - Expanded to 18 framework integrations with 30+ authentication plugins

⚠️ Important: Token Limits

Skill Visibility Constraint

Claude Code has a 15,000 character limit for the total size of skill descriptions in the system prompt. This limit also applies to commands and agents.

What this means:

  • Not all 170 skills may be visible in Claude's context at once
  • Skills are loaded based on relevance and available token budget
  • You can verify how many skills Claude currently sees by asking: "How many skills do you see in your system prompt?"

Checking Visible Skills

To verify which skills are currently loaded:

# Ask Claude Code directly
"Check what skills/plugins you see in your system prompt"

Claude will report something like: "85 of 170 skills visible due to token limits"

Workaround: Increase Token Budget

You can double the headroom for skill descriptions by setting an environment variable:

# Increase limit to 30,000 characters
export SLASH_COMMAND_TOOL_CHAR_BUDGET=30000

# Then launch Claude Code
claude

This gives you approximately 2x more skill visibility in the system prompt.

Note: This is a temporary workaround. The Claude Code team is working on better solutions for skill discovery and loading.


Token Efficiency

MetricManual SetupWith SkillsSavings
Average Tokens12,000-15,0004,000-5,000~65%
Typical Errors2-4 per service0 (prevented)100%
Setup Time2-4 hours15-45 minutes~80%

Across all 170 skills: 400+ documented errors prevented.


Contributing

Prerequisites for Contributors

Install the official plugin development toolkit:

/plugin install plugin-dev@claude-code-marketplace

This provides:

  • /plugin-dev:create-plugin command (8-phase guided workflow)
  • 7 comprehensive skills (hooks, MCP, structure, agents, commands, skills)
  • 2 specialized agents (agent-creator, plugin-validator)

Quick Steps

  1. Create skill directory in plugins/
  2. Add SKILL.md with YAML frontmatter
  3. Run ./scripts/sync-plugins.sh
  4. Submit pull request

See CONTRIBUTING.md and PLUGIN_DEV_BEST_PRACTICES.md for detailed guidelines.


Documentation

DocumentPurpose
START_HERE.mdStart here! Quick navigation guide
PLUGIN_DEV_BEST_PRACTICES.mdRepository-specific best practices (marketplace, budget, quality)
MARKETPLACE.mdFull skill catalog and installation guide
MARKETPLACE_MANAGEMENT.mdTechnical infrastructure (plugin.json, scripts, validation)
CLAUDE.mdProject context and development standards
CONTRIBUTING.mdContribution guidelines

Links


Built with ❤️ by Claude Skills Maintainers

View source on GitHub