Techniques
Headless
While Copilot.js includes with a customizable chat UI, you can also build your own UI, using Copilot as a headless frontend service that:
- manages communication with the backend, including reconnects.
- handles the state machine and message queues.
- handles code execution in a sandbox.
For headless operation, simply useCopilot()
to access the Copilot's internal state and methods, and build your UI on top of it.
// Example.jsx
import { CopilotProvider, useCopilot } from '@copilotjs/react'
export default function Example() {
return (
<CopilotProvider appId="..." userId="..." companyId="..." context={...}>
<MyChat />
</CopilotProvider>
)
}
function MyChat() {
// Access the copilot instance, and build your chat UI.
const copilot = useCopilot()
return (
<>
<div>Threads: {JSON.stringify(copilot.threads)}</div>
<div>Selected thread: {copilot.selectedThreadId}</div>
<div>Status: {copilot.status}</div>
<div>Messages: {JSON.stringify(copilot.messages)}</div>
<button onClick={async () => await copilot.createAndSelectThread()}>New thread</button>
<button onClick={() => copilot.prompt('Add 2 circles.')}>Prompt</button>
<button onClick={() => copilot.cancel()}>Cancel</button>
</>
)
}