### Install ChatKit Packages
Source: https://context7.com/openai/chatkit-js/llms.txt
Installs the ChatKit React package (which includes core types) or just the core ChatKit types for vanilla JavaScript projects.
```bash
npm install @openai/chatkit-react # React — also pulls in @openai/chatkit
# or
npm install @openai/chatkit # Vanilla JS / types only
```
--------------------------------
### Install ChatKit React Bindings via npm
Source: https://github.com/openai/chatkit-js/blob/main/README.md
Install the official React components and hooks for ChatKit using npm to integrate the chat interface into your React application.
```bash
npm install @openai/chatkit-react
```
--------------------------------
### Integrate ChatKit with Vanilla JavaScript
Source: https://github.com/openai/chatkit-js/blob/main/packages/docs/src/content/docs/quickstart.mdx
Install the ChatKit package and use vanilla JavaScript to create and configure the ChatKit custom element, then append it to the DOM.
```bash
npm install @openai/chatkit
```
```html
```
--------------------------------
### setOptions Web Component Configuration
Source: https://context7.com/openai/chatkit-js/llms.txt
Configure the openai-chatkit element imperatively with full options object. Options are not merged—pass complete configuration each time. Includes API setup with custom fetch, theme, and composer settings with attachment constraints.
```html
```
--------------------------------
### Integrate ChatKit with React
Source: https://github.com/openai/chatkit-js/blob/main/packages/docs/src/content/docs/quickstart.mdx
Install the ChatKit React package and define a React component to configure and render the ChatKit UI.
```bash
npm install @openai/chatkit-react
```
```tsx
import { ChatKit, useChatKit } from '@openai/chatkit-react';
export function SupportChat() {
const { control } = useChatKit({
api: {
url: 'http://localhost:8000/chatkit',
domainKey: 'local-dev',
},
});
return ;
}
```
--------------------------------
### Add ChatKit Script to HTML
Source: https://github.com/openai/chatkit-js/blob/main/packages/docs/src/content/docs/quickstart.mdx
Include the ChatKit JavaScript library in your root HTML file to make it available globally for all setups.
```html
```
--------------------------------
### Configure ChatKit options in React
Source: https://github.com/openai/chatkit-js/blob/main/packages/docs/src/content/docs/customize.mdx
Use useChatKit hook to configure theme, header, history, start screen, composer, and thread item actions. Pass the options object to customize appearance and behavior.
```tsx
import { useChatKit } from '@openai/chatkit-react';
const { control } = useChatKit({
theme: {
colorScheme: 'dark',
radius: 'round',
color: {
accent: { primary: '#8B5CF6', level: 2 },
},
},
header: {
enabled: true,
rightAction: {
icon: 'light-mode',
onClick: () => console.log('Toggle theme'),
},
},
history: {
enabled: true,
showDelete: true,
showRename: true,
},
startScreen: {
greeting: 'How can we help?',
prompts: [
{
label: 'Troubleshoot an issue',
prompt: 'Help me fix an issue',
icon: 'lifesaver',
},
{
label: 'Request a feature',
prompt: 'I have an idea',
icon: 'lightbulb',
},
],
},
composer: {
placeholder: 'Ask the assistant…',
},
threadItemActions: {
feedback: true,
retry: true,
},
});
```
```js
chatkit.setOptions({
theme: {
colorScheme: 'dark',
radius: 'round',
color: {
accent: { primary: '#8B5CF6', level: 2 },
},
},
header: {
enabled: true,
rightAction: {
icon: 'light-mode',
onClick: () => console.log('Toggle theme'),
},
},
history: {
enabled: true,
showDelete: true,
showRename: true,
},
startScreen: {
greeting: 'How can we help?',
prompts: [
{
label: 'Troubleshoot an issue',
prompt: 'Help me fix an issue',
icon: 'lifesaver',
},
{
label: 'Request a feature',
prompt: 'I have an idea',
icon: 'lightbulb',
},
],
},
composer: {
placeholder: 'Ask the assistant…',
},
threadItemActions: {
feedback: true,
retry: true,
},
});
```
--------------------------------
### setThreadId Thread Navigation and Persistence
Source: https://context7.com/openai/chatkit-js/llms.txt
Load an existing thread by ID or start a new conversation by passing null. Combine with chatkit.thread.change event and initialThread option to persist sessions across page reloads.
```ts
// Navigate to a specific historical thread
await chatkit.setThreadId('thread_abc123');
```
```ts
// Start a fresh conversation
await chatkit.setThreadId(null);
```
```ts
// Persist across page reloads
chatkit.addEventListener('chatkit.thread.change', ({ detail }) => {
if (detail.threadId) {
sessionStorage.setItem('chatkit-thread', detail.threadId);
}
});
// On mount, restore last thread
const savedThread = sessionStorage.getItem('chatkit-thread');
chatkit.setOptions({ initialThread: savedThread });
```
--------------------------------
### Listen to ChatKit DOM events with addEventListener
Source: https://context7.com/openai/chatkit-js/llms.txt
Attach typed CustomEvent listeners to the `` element for lifecycle events (ready, error), response streaming (start, end), thread/tool changes, analytics, effects, and deeplinks. Use `addEventListener` in vanilla JS or `on*` shortcuts in React.
```typescript
// Vanilla JS
chatkit.addEventListener('chatkit.ready', () => {
console.log('Widget loaded');
});
chatkit.addEventListener('chatkit.error', ({ detail }) => {
Sentry.captureException(detail.error);
});
chatkit.addEventListener('chatkit.response.start', () => {
showTypingIndicator();
});
chatkit.addEventListener('chatkit.response.end', () => {
hideTypingIndicator();
});
chatkit.addEventListener('chatkit.thread.change', ({ detail }) => {
// detail.threadId is null when a new thread is created
history.replaceState({}, '', detail.threadId ? `/chat/${detail.threadId}` : '/chat');
});
chatkit.addEventListener('chatkit.tool.change', ({ detail }) => {
console.log('Selected tool:', detail.toolId);
});
chatkit.addEventListener('chatkit.log', ({ detail }) => {
analytics.track(detail.name, detail.data);
});
chatkit.addEventListener('chatkit.effect', ({ detail }) => {
if (detail.name === 'navigate') router.push(detail.data?.path as string);
});
chatkit.addEventListener('chatkit.deeplink', ({ detail }) => {
if (detail.name === 'viewTicket') openTicket(detail.data?.id);
});
```
--------------------------------
### Integrate ChatKit with Vanilla JavaScript
Source: https://github.com/openai/chatkit-js/blob/main/packages/docs/src/content/docs/index.mdx
This snippet shows how to programmatically create and configure the `openai-chatkit` web component in a plain JavaScript environment.
```js
function InitChatkit({ clientToken }) {
const chatkit = document.createElement('openai-chatkit');
chatkit.setOptions({ api: { url, domainKey } });
chatkit.classList.add('h-[600px]', 'w-[320px]');
document.body.appendChild(chatkit);
}
```
--------------------------------
### setOptions(options: ChatKitOptions)
Source: https://context7.com/openai/chatkit-js/llms.txt
The imperative API for configuring the `` element in vanilla JavaScript (or when you hold a `ref` in React). Options are **not merged** — pass the full configuration object every time you call this method.
```APIDOC
## setOptions(options: ChatKitOptions)\n\n### Description\nThis method provides an imperative way to configure the `` web component. It is used in vanilla JavaScript or when interacting with the component via a React `ref`. It's important to note that options are not merged; a full configuration object must be passed with each call.\n\n### Signature\n`setOptions(options: ChatKitOptions): void`\n\n### Parameters\n- **options** (ChatKitOptions) - Required - The full configuration object for the ChatKit component. This object defines various aspects like API endpoints, theme, composer behavior, and attachments.\n\n### Example\n```html\n\n\n```
```
--------------------------------
### Use utility methods for sync, focus, and history management
Source: https://context7.com/openai/chatkit-js/llms.txt
Call `fetchUpdates()` to re-sync thread data after server mutations, `focusComposer()` to programmatically focus the input, and `showHistory()`/`hideHistory()` to toggle the conversation panel when the built-in header is disabled.
```typescript
// Force the widget to re-fetch thread data from the server
// (e.g. after you mutated threads server-side out-of-band)
await chatkit.fetchUpdates();
// Focus the composer textarea (e.g. after a tooltip CTA)
await chatkit.focusComposer();
// Show/hide the conversation history panel programmatically
// (useful when the built-in header is disabled)
document.getElementById('btn-history')?.addEventListener('click', () => {
chatkit.showHistory();
});
document.getElementById('btn-close-history')?.addEventListener('click', () => {
chatkit.hideHistory();
});
```
--------------------------------
### Configure theme with color scheme and typography
Source: https://context7.com/openai/chatkit-js/llms.txt
Set visual appearance including dark/light mode, border radius, density, accent colors, grayscale palette, and custom font families. Font sources use @font-face format and require WOFF2 URLs.
```typescript
chatkit.setOptions({
theme: {
colorScheme: 'dark',
radius: 'round', // 'pill' | 'round' | 'soft' | 'sharp'
density: 'compact', // 'compact' | 'normal' | 'spacious'
color: {
accent: { primary: '#10B981', level: 1 },
grayscale: { hue: 220, tint: 3, shade: -1 },
surface: { background: '#0f0f0f', foreground: '#f5f5f5' },
},
typography: {
baseSize: 15,
fontFamily: '"Inter", system-ui, sans-serif',
fontFamilyMono: '"JetBrains Mono", monospace',
fontSources: [
{
family: 'Inter',
src: 'https://fonts.gstatic.com/s/inter/v19/UcCO3FwrK3iLTeHuS_nVMrMxCp50.woff2',
weight: '400 700',
display: 'swap',
},
],
},
},
});
```
--------------------------------
### Configure message composer settings with composer (TypeScript)
Source: https://context7.com/openai/chatkit-js/llms.txt
Configure the message input area's placeholder, file attachments, selectable tools, models, and voice dictation. Customize options like `maxCount`, `accept` types, and tool properties.
```ts
chatkit.setOptions({
composer: {
placeholder: 'Ask the assistant…',
attachments: {
enabled: true,
maxCount: 3,
maxSize: 20 * 1024 * 1024, // 20 MB global limit
accept: { 'application/pdf': ['.pdf'], 'image/*': ['.jpg', '.png', '.webp'] },
},
tools: [
{
id: 'web-search',
label: 'Web search',
icon: 'globe',
shortLabel: 'Search',
placeholderOverride: 'What do you want to look up?',
pinned: true, // visible outside the overflow menu
persistent: false, // deselected after sending
},
{
id: 'code-interpreter',
label: 'Code interpreter',
icon: 'square-code',
pinned: false,
},
],
models: [
{ id: 'gpt-4o', label: 'GPT-4o', description: 'Best quality', default: true },
{ id: 'gpt-4o-mini', label: 'GPT-4o mini', description: 'Faster & cheaper' },
],
dictation: { enabled: true },
},
});
```
--------------------------------
### useChatKit(options: UseChatKitOptions): UseChatKitReturn
Source: https://github.com/openai/chatkit-js/blob/main/packages/docs/src/content/docs/quick-reference/use-chatkit.mdx
The `useChatKit` hook prepares the `` element for React applications, providing a stable interface for options, lifting out event handlers, and exposing imperative helpers from the underlying web component.
```APIDOC
## `useChatKit` hook
### Description
The `useChatKit` hook prepares the `` element for React applications, providing a stable interface for options, lifting out event handlers, and exposing imperative helpers from the underlying web component.
### Method
`useChatKit` (React Hook)
### Parameters
#### `options: UseChatKitOptions`
- **onReady** (`() => void`) - Optional - Callback fired when the component is ready.
- **onResponseStart** (`() => void`) - Optional - Callback fired when a response starts.
- **onResponseEnd** (`() => void`) - Optional - Callback fired when a response ends.
- **onThreadChange** (`(event: { threadId: string | null }) => void`) - Optional - Callback fired when the thread changes.
- **onThreadLoadStart** (`(event: { threadId: string }) => void`) - Optional - Callback fired when a thread starts loading.
- **onThreadLoadEnd** (`(event: { threadId: string }) => void`) - Optional - Callback fired when a thread finishes loading.
- **onError** (`(event: { error: Error }) => void`) - Optional - Callback fired on an error.
- **onLog** (`(event: { name: string; data?: Record }) => void`) - Optional - Callback for logging events.
- **onEffect** (`(event: { name: string; data?: Record }) => void`) - Optional - Callback for effect events.
- **onDeeplink** (`(event: { name: string; data?: Record })`) - Optional - Callback for deeplink events.
### Returns
#### `UseChatKitReturn`
- **focusComposer** (`() => Promise`) - Imperative helper to focus the composer.
- **setThreadId** (`(threadId: string | null) => Promise`) - Imperative helper to set the current thread ID.
- **sendUserMessage** (`(params: { text?: string; content?: UserMessageContent[]; reply?: string; attachments?: Attachment[]; newThread?: boolean; toolChoice?: ToolChoice; model?: string; }) => Promise`) - Imperative helper to send a user message.
- **setComposerValue** (`(params: { text?: string; content?: UserMessageContent[]; reply?: string; attachments?: Attachment[]; files?: File[]; selectedToolId?: string; selectedModelId?: string; }) => Promise`) - Imperative helper to set the composer's value.
- **fetchUpdates** (`() => Promise`) - Imperative helper to fetch updates.
- **sendCustomAction** (`(action: { type: string; payload?: Record }, itemId?: string) => Promise`) - Imperative helper to send a custom action.
- **showHistory** (`() => Promise`) - Imperative helper to show history.
- **hideHistory** (`() => Promise`) - Imperative helper to hide history.
- **control** (`ChatKitControl`) - A bundle of stable options and extracted handlers.
- **ref** (`React.RefObject`) - A ref to forward to the `` component.
```
--------------------------------
### setOptions() — theme configuration
Source: https://context7.com/openai/chatkit-js/llms.txt
Configure the visual appearance of the ChatKit widget including color scheme, border radius, density, typography, and custom font sources. This method accepts a theme object that controls all visual styling aspects of the widget.
```APIDOC
## setOptions() — theme
### Description
Configures the visual appearance and styling of the ChatKit widget, including color scheme, accent colors, border radius, density, typography, and custom font sources.
### Method Signature
```ts
chatkit.setOptions({
theme: ThemeConfig
})
```
### Parameters
#### theme (object) - Required
Theme configuration object with the following properties:
- **colorScheme** (string) - Optional - Color scheme mode: 'dark' or 'light'
- **radius** (string) - Optional - Border radius style: 'pill' | 'round' | 'soft' | 'sharp'
- **density** (string) - Optional - Spacing density: 'compact' | 'normal' | 'spacious'
- **color** (object) - Optional - Color configuration
- **accent** (object) - Accent color settings
- **primary** (string) - Primary accent color hex value
- **level** (number) - Accent level intensity
- **grayscale** (object) - Grayscale palette settings
- **hue** (number) - Hue value for grayscale
- **tint** (number) - Tint adjustment
- **shade** (number) - Shade adjustment
- **surface** (object) - Surface colors
- **background** (string) - Background color hex value
- **foreground** (string) - Foreground color hex value
- **typography** (object) - Optional - Typography configuration
- **baseSize** (number) - Base font size in pixels
- **fontFamily** (string) - Primary font family CSS string
- **fontFamilyMono** (string) - Monospace font family CSS string
- **fontSources** (array) - Custom font source definitions
- **family** (string) - Font family name
- **src** (string) - Font file URL
- **weight** (string) - Font weight range (e.g., '400 700')
- **display** (string) - Font display strategy (e.g., 'swap')
### Request Example
```ts
chatkit.setOptions({
theme: {
colorScheme: 'dark',
radius: 'round',
density: 'compact',
color: {
accent: { primary: '#10B981', level: 1 },
grayscale: { hue: 220, tint: 3, shade: -1 },
surface: { background: '#0f0f0f', foreground: '#f5f5f5' },
},
typography: {
baseSize: 15,
fontFamily: '"Inter", system-ui, sans-serif',
fontFamilyMono: '"JetBrains Mono", monospace',
fontSources: [
{
family: 'Inter',
src: 'https://fonts.gstatic.com/s/inter/v19/UcCO3FwrK3iLTeHuS_nVMrMxCp50.woff2',
weight: '400 700',
display: 'swap',
},
],
},
},
});
```
```
--------------------------------
### Configure entity tagging and @-mention autocomplete with entities (TypeScript)
Source: https://context7.com/openai/chatkit-js/llms.txt
Configure `@`-mention autocomplete, click handling for rendered entity tags, and hover previews. Implement `onTagSearch`, `onClick`, and `onRequestPreview` for custom behavior.
```ts
chatkit.setOptions({
entities: {
showComposerMenu: true, // show "@" button in composer toolbar
async onTagSearch(query) {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
const items = await res.json();
return items.map((item: any) => ({
id: item.id,
title: item.name,
group: item.type, // e.g. "People", "Documents"
icon: item.avatarUrl,
interactive: true,
data: { url: item.detailUrl },
}));
},
onClick(entity) {
// Navigate when a rendered tag is clicked
router.push(entity.data?.url as string);
},
async onRequestPreview(entity) {
const res = await fetch(`/api/entity/${entity.id}/preview`);
const widget = await res.json();
return { preview: widget ?? null };
},
},
});
```
--------------------------------
### Render ChatKit Component in a React Application
Source: https://github.com/openai/chatkit-js/blob/main/README.md
This React component demonstrates how to initialize and render the ChatKit UI, including a function to fetch the necessary 'client_secret' from a backend API.
```tsx
import { ChatKit, useChatKit } from '@openai/chatkit-react';
export function MyChat() {
const { control } = useChatKit({
api: {
async getClientSecret(existing) {
if (existing) {
// implement session refresh
}
const res = await fetch('/api/chatkit/session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const { client_secret } = await res.json();
return client_secret;
},
},
});
return ;
}
```
--------------------------------
### Add ChatKit CDN Script
Source: https://context7.com/openai/chatkit-js/llms.txt
Includes the ChatKit web component from OpenAI's CDN in your root HTML template, enabling its functionality.
```html
```
--------------------------------
### Implement ChatKit with useChatKit React Hook
Source: https://context7.com/openai/chatkit-js/llms.txt
Demonstrates how to use the `useChatKit` hook to integrate ChatKit into a React component, configuring API access, theme, initial state, and event handlers for a support chat interface.
```tsx
import { ChatKit, useChatKit } from '@openai/chatkit-react';
export function SupportChat() {
const {
control,
sendUserMessage,
setThreadId,
setComposerValue,
focusComposer,
fetchUpdates,
showHistory,
hideHistory,
} = useChatKit({
// --- API config (hosted) ---
api: {
getClientSecret: async (existing) => {
// `existing` is the current token; refresh when it expires
const res = await fetch('/api/chatkit/session', { method: 'POST' });
const { client_secret } = await res.json();
return client_secret;
},
},
// --- Theme ---
theme: {
colorScheme: 'dark',
radius: 'round',
density: 'normal',
color: {
accent: { primary: '#8B5CF6', level: 2 }
},
typography: {
baseSize: 15,
fontFamily: 'Inter, sans-serif'
}
},
// --- Restore the previous thread across page loads ---
initialThread: localStorage.getItem('chatThreadId'),
// --- Event handlers ---
onReady: () => console.log('ChatKit ready'),
onResponseStart: () => console.log('AI started responding'),
onResponseEnd: () => console.log('AI finished responding'),
onThreadChange: ({ threadId }) => {
if (threadId) localStorage.setItem('chatThreadId', threadId);
},
onError: ({ error }) => console.error('ChatKit error:', error),
onEffect: ({ name, data }) => {
if (name === 'openSidebar') activateSidebar(data?.section);
},
onDeeplink: ({ name, data }) => {
if (name === 'viewOrder') router.push(`/orders/${data?.id}`);
}
});
// Programmatic message after component mounts
React.useEffect(() => {
setComposerValue({ text: 'Hello! How can you help me today?' });
focusComposer();
}, []);
return (
);
}
```
--------------------------------
### onClientTool
Source: https://context7.com/openai/chatkit-js/llms.txt
Registers a handler for tool calls that your server delegates to the browser. The returned object (or resolved promise) is sent back to the server as the tool result.
```APIDOC
## Configuration Callback: onClientTool
### Description
Registers a handler for tool calls that your server delegates to the browser. The object or resolved promise returned by this handler is sent back to the server as the tool result.
### Signature
`onClientTool: (toolCall: { name: string, params: object }) => Promise