React Copilot Widget
The React Copilot Widget is a powerful React component library that provides seamless integration of Copilot functionality into your React applications. It offers automatic single/multi-mode detection, custom tools integration, and user management capabilities.
Features
- Automatic Single/Multi Mode: Automatically detects and supports both single and multiple Copilot instances
 - Custom Tools Integration: Register powerful tools with support for async handlers
 - User Management: Easily set/unset user information across sessions
 - Ergonomic Hooks: Intuitive and declarative hooks for tools and users
 - Smart Resolution: Access Copilot instances by name or index with graceful fallback
 - Type-Safe: Built in TypeScript with full type support and validation
 - Simple Integration: Drop-in provider and hook system for seamless integration
 
Installation
npm install @copilotlive/react-sdk
# or
yarn add @copilotlive/react-sdk
# or
pnpm add @copilotlive/react-sdk
Quick Start
Basic Setup (Single Instance)
import { CopilotProvider } from '@copilotlive/react-sdk';
function App() {
  return (
    <CopilotProvider
      token="your-copilot-token"
      config={{
        theme: 'light',
        position: 'bottom-right',
        botName: 'My Assistant'
      }}
    >
      <YourApp />
    </CopilotProvider>
  );
}
Multiple Instances Setup
import { CopilotProvider } from '@copilotlive/react-sdk';
function App() {
  return (
    <CopilotProvider
      instances={[
        {
          token: 'token-1',
          config: { theme: 'light', botName: 'Support Bot' }
        },
        {
          token: 'token-2',
          config: { theme: 'dark', botName: 'Sales Bot' }
        }
      ]}
    >
      <YourApp />
    </CopilotProvider>
  );
}
Core Components
CopilotProvider
The main provider component that initializes Copilot functionality:
interface CopilotProviderProps {
  // Single instance
  token?: string;
  config?: Record<string, any>;
  scriptUrl?: string;
  botName?: string;
  // Multiple instances
  instances?: Array<{
    token: string;
    config?: Record<string, any>;
    scriptUrl?: string;
    botName?: string;
  }>;
  children: React.ReactNode;
}
Copilot Component
Register tools and configure specific Copilot instances:
import { Copilot, ToolDefinition } from '@copilotlive/react-sdk';
const tools: ToolDefinition[] = [
  {
    name: 'get_user_info',
    description: 'Retrieves user information',
    parameters: {
      type: 'object',
      properties: {
        userId: {
          type: 'string',
          description: 'User ID to retrieve'
        },
      },
      required: ['userId']
    },
    handler: async ({ userId }) => {
      const response = await fetch(`/api/users/${userId}`);
      return response.json();
    }
  }
];
function ToolsLoader() {
  return <Copilot tools={tools} />;
}
Hooks
useCopilot
Access Copilot instance functionality:
import { useCopilot } from '@copilotlive/react-sdk';
function CopilotControls() {
  const copilot = useCopilot(); // Defaults to index 0
  return (
    <div>
      <button onClick={() => copilot.show?.()}>
        Open Chat
      </button>
      <button onClick={() => copilot.hide?.()}>
        Close Chat
      </button>
    </div>
  );
}
useCopilotTool
Register tools using hooks:
import { useCopilotTool } from '@copilotlive/react-sdk';
function MyComponent() {
  useCopilotTool({
    name: 'calculate_sum',
    description: 'Adds two numbers together',
    parameters: {
      type: 'object',
      properties: {
        a: { type: 'number', description: 'First number' },
        b: { type: 'number', description: 'Second number' }
      },
      required: ['a', 'b']
    },
    handler: ({ a, b }) => ({ result: a + b })
  }, {
    removeOnUnmount: true // Automatically remove tool when component unmounts
  });
  return <div>Component with tool registered</div>;
}
useCopilotUser
Manage user information:
import { useCopilotUser } from '@copilotlive/react-sdk';
function UserProfile() {
  useCopilotUser({
    id: 'user123',
    name: 'Jane Doe',
    email: 'jane@example.com',
    role: 'admin',
    preferences: {
      theme: 'dark',
      language: 'en'
    }
  }, {
    unsetOnUnmount: true // Clear user data when component unmounts
  });
  return <div>User profile loaded</div>;
}
Advanced Usage
Multiple Instance Management
function MultiCopilotApp() {
  const supportCopilot = useCopilot('support-bot');
  const salesCopilot = useCopilot('sales-bot');
  return (
    <div>
      <button onClick={() => supportCopilot.show?.()}>
        Support Chat
      </button>
      <button onClick={() => salesCopilot.show?.()}>
        Sales Chat
      </button>
    </div>
  );
}
Dynamic Tool Registration
function DynamicTools() {
  const [tools, setTools] = useState<ToolDefinition[]>([]);
  const addTool = (tool: ToolDefinition) => {
    setTools(prev => [...prev, tool]);
  };
  const removeTool = (toolName: string) => {
    setTools(prev => prev.filter(tool => tool.name !== toolName));
  };
  return (
    <Copilot
      tools={tools}
      botName="dynamic-bot"
    />
  );
}
Custom Configuration
function CustomCopilot() {
  return (
    <CopilotProvider
      token="your-token"
      config={{
        theme: 'dark',
        position: 'bottom-left',
        width: '400px',
        height: '600px',
        showWelcomeMessage: true,
        welcomeMessage: 'Hello! How can I help you today?',
        placeholder: 'Type your message...',
        enableTypingIndicator: true,
        enableReadReceipts: true
      }}
    >
      <YourApp />
    </CopilotProvider>
  );
}
TypeScript Support
Tool Definition Types
interface ToolDefinition {
  name: string;
  description: string;
  parameters?: {
    type: 'object';
    properties: Record<string, ToolParameter>;
    required?: string[];
  };
  timeout?: number;
  handler: (args: Record<string, any>) => any;
}
interface ToolParameter {
  type: string;
  description?: string;
  enum?: string[];
}
Copilot API Types
interface CopilotAPI {
  show: () => void;
  hide: () => void;
  tools: {
    add: (tool: ToolDefinition | ToolDefinition[]) => void;
    remove: (name: string) => void;
    removeAll?: () => void;
  };
  users: {
    set: (user: Record<string, any>) => void;
    unset: () => void;
  };
}
Best Practices
Performance Optimization
- Lazy Load Tools: Register tools only when needed
 - Memoize Handlers: Use 
useCallbackfor tool handlers - Cleanup: Always use 
removeOnUnmountfor temporary tools - Debounce: Implement debouncing for frequently called tools
 
const debouncedHandler = useCallback(
  debounce((args) => {
    // Tool logic here
  }, 300),
  []
);
useCopilotTool({
  name: 'search',
  description: 'Search functionality',
  handler: debouncedHandler
}, { removeOnUnmount: true });
Error Handling
useCopilotTool({
  name: 'api_call',
  description: 'Make API call',
  handler: async (args) => {
    try {
      const response = await fetch('/api/data');
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('Tool error:', error);
      return { error: 'Failed to fetch data' };
    }
  }
});
State Management Integration
function CopilotWithState() {
  const [userState, setUserState] = useState(null);
  useCopilotUser(userState, { unsetOnUnmount: true });
  useCopilotTool({
    name: 'update_user_state',
    description: 'Update user state',
    handler: (newState) => {
      setUserState(newState);
      return { success: true };
    }
  });
  return <div>State-managed Copilot</div>;
}
Troubleshooting
Common Issues
- Widget not appearing: Check token validity and network connectivity
 - Tools not working: Verify tool registration and handler functions
 - User data not persisting: Ensure proper user management implementation
 - Multiple instances conflict: Use unique bot names and proper instance targeting
 
Debug Mode
Enable debug mode for detailed logging:
<CopilotProvider
  token="your-token"
  config={{
    debug: true,
    logLevel: 'verbose'
  }}
>
  <YourApp />
</CopilotProvider>
Migration Guide
From Vanilla JavaScript
If migrating from vanilla JavaScript implementation:
- Install the React SDK
 - Replace script tags with 
CopilotProvider - Convert tool registration to React hooks
 - Update user management to use 
useCopilotUser 
Support
For additional help with React Copilot Widget:
- Check our FAQ
 - Contact support at support@kaily.ai
 - Visit our GitHub repository for examples and issues