Overview
CopilotKit is a WebSocket-based agent integration pattern that provides real-time, bidirectional communication between your React frontend and Python backend. It’s ideal for building chat interfaces and contextual help features with minimal setup.When to Use CopilotKit
Best suited for:
- Simple chat interfaces with real-time streaming
- Contextual help and in-app assistance
- Quick Q&A features with instant responses
- Real-time collaboration features
- Single-agent conversations
Not recommended for:
- Complex multi-agent orchestration (use AG-UI Protocol instead)
- Workflows requiring persistent state across sessions (use Workspace Context Sync)
- Bulk data processing or long-running background tasks
Architecture
CopilotKit uses WebSocket connections for low-latency, bidirectional communication: Key Benefits:- Low latency: WebSocket maintains persistent connection for instant responses
- Bidirectional: Server can push updates to client without polling
- Streaming: Real-time token streaming as the AI generates responses
- Simple state: Client-side state management with React hooks
Backend Setup
1. Install Dependencies
Add CopilotKit to your Python backend:requirements.txt should include:
2. Create CopilotKit Endpoint
Create a new fileapp/api/copilot.py:
3. Register the Router
In yourapp/main.py:
4. Health Check Endpoint
Add a health check to verify the CopilotKit service:Frontend Setup
1. Install Dependencies
The CopilotKit packages are already included in OpsHub’spackage.json:
2. Create API Proxy Route
Createapp/api/copilotkit/route.ts to proxy WebSocket connections:
- Next.js API Route
- WebSocket Upgrade
3. Add CopilotKit Provider
Wrap your page with the CopilotKit provider:4. Use CopilotKit Hooks
Access chat functionality in your components:Complete Example
Here’s a full working example of a contextual help sidebar:Authentication
CopilotKit uses JWT tokens for secure authentication:Server-Side (Next.js API Route)
Backend (Python FastAPI)
Always use JWT tokens from Supabase sessions instead of user IDs. The
getAuthHeaders() utility automatically extracts the JWT token from the session.Error Handling
Connection Failures
Handle WebSocket connection failures gracefully:Reconnection Logic
The WebSocket connection automatically reconnects on disconnect:Backend Error Handling
Best Practices
Performance
Optimize for low latency:
- Keep messages small (avoid sending large JSON payloads)
- Use message batching for multiple rapid updates
- Implement debouncing for user input
- Close connections when not in use
User Experience
Provide clear feedback:
- Show typing indicators while agent is thinking
- Display connection status in the UI
- Handle errors gracefully with user-friendly messages
- Provide retry mechanisms for failed messages
Security
Always secure your connections:
- Use JWT tokens, never expose API keys to the frontend
- Validate all user inputs on the backend
- Implement rate limiting to prevent abuse
- Log all authentication failures
State Management
Keep state simple:
- CopilotKit handles client-side state automatically
- Store conversation history in your database if persistence is needed
- Use Supabase for session data (see
agent.sessionstable) - Clean up old sessions periodically
Troubleshooting
WebSocket Connection Fails
Problem: Connection immediately closes or never establishes. Solutions:- Check that backend is running:
curl http://localhost:8000/copilotkit/health - Verify API proxy route exists:
app/api/copilotkit/route.ts - Check browser console for authentication errors
- Ensure
runtimeUrlprop matches your API route
Authentication Errors
Problem: Backend returns 401 or 1008 WebSocket close code. Solutions:- Verify Supabase session exists:
supabase.auth.getSession() - Check JWT token is being sent: inspect network request headers
- Ensure backend API key matches environment variable
- Test with the health endpoint first
Messages Not Streaming
Problem: Agent responses appear all at once instead of streaming. Solutions:- Verify backend is using
yieldfor streaming responses - Check Content-Type header is
text/event-stream - Ensure proxy is not buffering responses
- Test directly with backend (bypass Next.js proxy)
High Latency
Problem: Slow response times or delayed message delivery. Solutions:- Check network latency: test direct backend connection
- Optimize LangGraph workflow (reduce tool calls)
- Use faster LLM models (GPT-3.5 instead of GPT-4)
- Implement response caching for common queries
WebSocket connections can be blocked by corporate firewalls or proxies. Consider providing an HTTP fallback option for enterprise users.
Related Documentation
AG-UI Protocol
For complex multi-agent orchestration
SSE Streaming
Server-Sent Events for one-way streaming
Workspace Sync
Context-aware agent features
Authentication Guide
Secure your agent endpoints
Next Steps
1
Set up your backend
Follow the Backend Setup section to create your CopilotKit endpoint
2
Add the frontend provider
Wrap your page with the CopilotKit provider as shown in Frontend Setup
3
Test the connection
Use the health endpoint to verify your setup:
/api/copilotkit/health4
Build your chat UI
Start with the Complete Example and customize for your use case