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.
What this skill does
# better-chatbot-patterns **Status**: Production Ready **Last Updated**: 2025-11-21 **Dependencies**: None **Latest Versions**: [email protected], [email protected], [email protected], [email protected] --- ## 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 I
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.