Overview
The State Machine Copilot example demonstrates a multi-stage car sales flow where state transitions are managed through AI interactions. It showcases:- Complex state machines with multiple stages
- Bidirectional state sync between UI and agents
- Stage-specific AI behavior with context switching
- Visual state representation using React Flow
- Generative UI for each stage
- Form validation and data collection
Live Demo: https://copilotkit.ai/examples/state-machine-copilot
Source Code: GitHub
What You’ll Learn
This example teaches you how to:- Use
useAgentfor bidirectional state synchronization - Build multi-stage state machines with AI
- Implement stage-specific actions and prompts
- Create state-driven generative UI
- Visualize state transitions
- Manage complex application state with TypeScript
Prerequisites
- Node.js 18 or higher
- npm, yarn, or pnpm
- Copilot Cloud Public API Key
Quick Start
Open Application
Navigate to http://localhost:3000
Application Flow
The car sales application progresses through these stages:Stages
- Get Contact Info - Collect customer name, email, phone
- Build Car - Configure car model, color, features
- Sell Financing - Present financing options
- Get Financing Info - Collect financing details (if accepted)
- Get Payment Info - Process direct payment (if financing declined)
- Confirm Order - Review and confirm the order
Core Implementation
1. State Definition
File:lib/types.ts
2. Global State Hook with useAgent
File:lib/stages/use-global-state.tsx
useAgentprovides bidirectional state sync- State changes in UI automatically propagate to agent
- Agent state updates trigger UI re-renders
- Type-safe state management with TypeScript
- Helper functions for common operations
3. Stage-Specific Actions
Each stage has its own hook with stage-specific actions and prompts: File:lib/stages/use-stage-get-contact-info.tsx
lib/stages/use-stage-build-car.tsx
4. Orchestrating Stage Hooks
File:components/car-sales-chat.tsx
5. State Visualization
File:components/state-visualizer.tsx
6. Stage-Specific Generative UI
File:components/generative-ui/contact-info.tsx
Advanced Patterns
Conditional Stage Transitions
State Validation
State Persistence
Undo/Redo Functionality
Real-World Use Cases
Form Wizards
Multi-step forms with AI assistance at each step:- Onboarding flows
- Application processes
- Survey builders
- Checkout flows
Game State Management
Turn-based games or interactive stories:- Player inventory and stats
- Game progression and levels
- Decision trees
- Quest tracking
Workflow Automation
Business process automation:- Approval workflows
- Document processing
- Customer support tickets
- Project management
Educational Applications
Learning platforms with progress tracking:- Quiz progression
- Learning paths
- Skill assessments
- Personalized tutoring
Best Practices
1. Keep State Flat
Avoid deeply nested state:2. Use TypeScript
Enforce type safety across state updates:3. Separate Concerns
Keep state logic separate from UI:4. Memoize Expensive Computations
5. Document State Transitions
Debugging Tips
Log State Changes
React DevTools
Use React DevTools to inspect state:- Install React DevTools browser extension
- Open DevTools
- Navigate to Components tab
- Find your component
- Inspect hooks → CoAgent state
State Snapshots
Troubleshooting
State Not Syncing
State Not Syncing
Verify:
useAgentis called with correct agent ID- Agent name matches in backend configuration
- State types are consistent
- CopilotKit provider wraps the app
UI Not Updating
UI Not Updating
Check:
- You’re calling
setStatewith a new object reference - State updates aren’t being batched incorrectly
- Components are properly subscribed to state changes
- No memoization preventing re-renders
Stage Transitions Failing
Stage Transitions Failing
Ensure:
- Stage names are consistent across the application
- Validation logic allows progression
- All required data is collected before transition
- No async operations blocking the transition
Next Steps
Multi-Agent
Combine shared state with multi-agent systems
Generative UI
Create state-driven generative UI
useAgent
Complete API reference
Human-in-the-Loop
Add approval workflows to state transitions
