### 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 | object` ### Parameters - **toolCall** (object) - The tool call object from the server. - **name** (string) - The name of the tool to execute. - **params** (object) - The parameters for the tool execution. ### Return Value (Promise | object) - The result of the tool execution, which will be sent back to the server. ### Example Usage ```ts chatkit.setOptions({ onClientTool: async ({ name, params }) => { switch (name) { case 'getCurrentLocation': return new Promise((resolve) => navigator.geolocation.getCurrentPosition( (pos) => resolve({ lat: pos.coords.latitude, lng: pos.coords.longitude }), () => resolve({ error: 'Permission denied' }), ), ); case 'getClipboardText': try { return { text: await navigator.clipboard.readText() }; } catch { return { error: 'Clipboard access denied' }; } case 'readLocalStorage': return { value: localStorage.getItem(params.key as string) ?? null }; default: return { error: `Unknown client tool: ${name}` }; } }, }); ``` ``` -------------------------------- ### entities Source: https://context7.com/openai/chatkit-js/llms.txt Configures entity tagging and `@`-mention autocomplete, including handlers for search, click, and preview requests. ```APIDOC ## Configuration Object: entities ### Description Enables `@`-mention autocomplete in the composer, click handling for rendered entity tags, and hover previews powered by the Widget system. This object configures various behaviors related to entity interaction. ### Properties - **showComposerMenu** (boolean) - Optional - If true, shows an "@" button in the composer toolbar. - **onTagSearch** (function) - Required - A callback function invoked when the user types "@" followed by a query in the composer. - **Signature**: `onTagSearch(query: string) => Promise>` - **Parameters**: - **query** (string) - The search query entered by the user. - **Return Value**: (Promise>) - A promise resolving to an array of entity items. Each item should have `id`, `title`, `group`, `icon`, `interactive`, and `data` properties. - **onClick** (function) - Optional - A callback function invoked when a rendered entity tag is clicked. - **Signature**: `onClick(entity: object) => void` - **Parameters**: - **entity** (object) - The clicked entity object. - **onRequestPreview** (function) - Optional - A callback function invoked when a user requests a preview for an entity (e.g., on hover). - **Signature**: `onRequestPreview(entity: object) => Promise<{ preview: object | null }>` - **Parameters**: - **entity** (object) - The entity object for which a preview is requested. - **Return Value**: (Promise<{ preview: object | null }>) - A promise resolving to an object containing a `preview` property, which can be a widget object or null. ### Example Usage ```ts chatkit.setOptions({ entities: { showComposerMenu: true, 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, icon: item.avatarUrl, interactive: true, data: { url: item.detailUrl }, })); }, onClick(entity) { 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 }; }, }, }); ``` ``` -------------------------------- ### fetchUpdates() — Utility method Source: https://context7.com/openai/chatkit-js/llms.txt Forces the widget to re-fetch thread data from the server. Use this after mutating threads server-side out-of-band to ensure the widget displays the latest data. ```APIDOC ## fetchUpdates() ### Description Forces the widget to re-fetch thread data from the server. Useful after server-side mutations to threads that occur outside the widget's normal flow. ### Method Signature ```ts await chatkit.fetchUpdates(): Promise ``` ### Parameters None ### Response Returns a Promise that resolves when the update is complete. ### Example ```ts // 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(); ``` ``` -------------------------------- ### Define and handle structured widget types Source: https://context7.com/openai/chatkit-js/llms.txt Import `Widgets` type from `@openai/chatkit` to define Card, ListView, or BasicRoot widgets with child components (Title, Text, Input, Select, Badge, etc.). Handle widget actions via `setOptions({ widgets: { onAction } })` to process custom payloads. ```typescript import type { Widgets } from '@openai/chatkit'; // A Card widget with a form, rendered by ChatKit inside the chat bubble const orderConfirmationWidget: Widgets.Card = { type: 'Card', size: 'md', asForm: true, confirm: { label: 'Place order', action: { type: 'submitOrder', payload: { orderId: 'ord_99' } } }, cancel: { label: 'Cancel', action: { type: 'cancelOrder' } }, children: [ { type: 'Title', value: 'Confirm your order', size: 'md', weight: 'semibold' }, { type: 'Divider' }, { type: 'Row', justify: 'between', children: [ { type: 'Text', value: 'Product', color: { light: '#666', dark: '#aaa' } }, { type: 'Text', value: 'Wireless Headphones', weight: 'medium' }, ], }, { type: 'Row', justify: 'between', children: [ { type: 'Text', value: 'Price' }, { type: 'Badge', label: '$149.99', color: 'success', variant: 'soft' }, ], }, { type: 'Input', name: 'shippingAddress', placeholder: 'Shipping address', required: true }, { type: 'Select', name: 'shippingSpeed', placeholder: 'Shipping speed', options: [ { value: 'standard', label: 'Standard (5-7 days)' }, { value: 'express', label: 'Express (2 days)' }, ]}, ], }; // Handle widget actions chatkit.setOptions({ widgets: { async onAction(action, widgetItem) { console.log('Widget action:', action.type, 'from widget:', widgetItem.id); if (action.type === 'submitOrder') { await placeOrder(action.payload); } }, }, }); ``` -------------------------------- ### showHistory() — Utility method Source: https://context7.com/openai/chatkit-js/llms.txt Programmatically shows the conversation history panel. Useful when the built-in header is disabled and you need manual control over history visibility. ```APIDOC ## showHistory() ### Description Programmatically displays the conversation history panel. Useful for custom header implementations or when the built-in header is disabled. ### Method Signature ```ts await chatkit.showHistory(): Promise ``` ### Parameters None ### Response Returns a Promise that resolves when the history panel is shown. ### Example ```ts document.getElementById('btn-history')?.addEventListener('click', () => { chatkit.showHistory(); }); ``` ``` -------------------------------- ### Include ChatKit JavaScript Library in HTML Source: https://github.com/openai/chatkit-js/blob/main/README.md Add this script tag to your HTML to load the core ChatKit JavaScript library asynchronously from the OpenAI CDN, making it available globally. ```html ``` -------------------------------- ### sendCustomAction(action, itemId?) Source: https://context7.com/openai/chatkit-js/llms.txt Relays a client-side widget action back to your server for further handling. This method is typically called after `widgets.onAction` has performed any client-side work and needs to notify the backend. ```APIDOC ## Method: sendCustomAction ### Description Relays a client-side widget action back to your server for further handling. This method is typically called after `widgets.onAction` has performed any client-side work and needs to notify the backend. ### Signature `sendCustomAction(action: object, itemId?: string)` ### Parameters - **action** (object) - Required - The custom action object to relay to the server. It should typically include a `type` and `payload`. - **itemId** (string) - Optional - The ID of the widget item to associate the response with. ### Example Usage ```ts await chatkit.sendCustomAction( { type: 'submitOrder', payload: action.payload }, widgetItem.id, // associates the response with this widget ); ``` ``` -------------------------------- ### Relay client-side widget action to server with sendCustomAction (TypeScript) Source: https://context7.com/openai/chatkit-js/llms.txt Use `chatkit.sendCustomAction` within `onAction` to relay client-side widget actions to the server. Associates the server's response with the specified widget item. ```ts chatkit.setOptions({ widgets: { async onAction(action, widgetItem) { // 1. Handle the action client-side if (action.type === 'openModal') { openProductModal(action.payload?.productId); return; // no server relay needed } // 2. Relay to server for server-side handling if (action.type === 'submitOrder') { await chatkit.sendCustomAction( { type: 'submitOrder', payload: action.payload }, widgetItem.id, // associates the response with this widget ); } }, }, }); ``` -------------------------------- ### Register client-side tool execution handler with onClientTool (TypeScript) Source: https://context7.com/openai/chatkit-js/llms.txt Register a handler for server-delegated tool calls to be executed in the browser. The handler's return value is sent back to the server as the tool result. ```ts chatkit.setOptions({ api: { getClientSecret: async () => (await fetch('/api/session')).json().then(r => r.client_secret), }, onClientTool: async ({ name, params }) => { switch (name) { case 'getCurrentLocation': return new Promise((resolve) => navigator.geolocation.getCurrentPosition( (pos) => resolve({ lat: pos.coords.latitude, lng: pos.coords.longitude }), () => resolve({ error: 'Permission denied' }), ), ); case 'getClipboardText': try { return { text: await navigator.clipboard.readText() }; } catch { return { error: 'Clipboard access denied' }; } case 'readLocalStorage': return { value: localStorage.getItem(params.key as string) ?? null }; default: return { error: `Unknown client tool: ${name}` }; } }, }); ``` -------------------------------- ### setComposerValue(params) Source: https://context7.com/openai/chatkit-js/llms.txt Populates the composer input without immediately sending the message. Use it to inject suggested text, pre-attach files, or select a tool. ```APIDOC ## setComposerValue(params)\n\n### Description\nThis method allows you to programmatically pre-fill the composer input field of the ChatKit component. It can be used to suggest text, attach local files for upload, or pre-select a tool without sending the message immediately.\n\n### Signature\n`setComposerValue(params: SetComposerValueParams): Promise`\n\n### Parameters\n- **params** (object) - Required - An object containing the composer value details.\n - **text** (string) - Optional - The text to pre-fill in the composer.\n - **selectedToolId** (string | null) - Optional - The ID of the tool to select, or `null` to clear any selected tool.\n - **files** (Array) - Optional - An array of local `File` objects to attach. ChatKit handles the server upload process.\n\n### Example\n```ts\n// Pre-fill text and select a tool\nawait chatkit.setComposerValue({\n text: 'Draft a reply to this email: ',\n selectedToolId: 'email-compose',\n});\n\n// Upload local files (ChatKit handles the server upload)\nconst fileInput = document.querySelector('#file-input');\nawait chatkit.setComposerValue({\n files: Array.from(fileInput.files ?? []),\n});\n\n// Clear tool selection\nawait chatkit.setComposerValue({ selectedToolId: null });\n``` ``` -------------------------------- ### Source: https://context7.com/openai/chatkit-js/llms.txt `ChatKit` is a `React.forwardRef` component that renders the `` custom element. It applies `control.options` via `setOptions()` and registers/cleans up all event listeners from `control.handlers`. Any extra props (HTML attributes, `className`, `style`, ARIA attributes) are spread onto the underlying element. ```APIDOC ## \n\n### Description\nThe `ChatKit` component is a React.forwardRef component that renders the `` custom element. It manages the application of `control.options` and handles event listener registration and cleanup. Additional HTML attributes, `className`, `style`, and ARIA attributes are spread onto the underlying element.\n\n### Props\n- **control** (object) - Required - An object containing options and handlers for the ChatKit component, typically obtained from `useChatKit`.\n- **ref** (React.Ref) - Optional - A ref to access the underlying web component imperatively.\n- **className** (string) - Optional - CSS class names to apply to the component.\n- **style** (object) - Optional - Inline CSS styles to apply to the component.\n- **aria-label** (string) - Optional - ARIA label for accessibility.\n\n### Example\n```tsx\nimport { ChatKit, useChatKit } from '@openai/chatkit-react';\nimport type { OpenAIChatKit } from '@openai/chatkit';\n\nexport function FullFeaturedChat() {\n const ref = React.useRef(null);\n\n const { control, sendUserMessage } = useChatKit({\n api: { url: '/api/chatkit', domainKey: 'my-app-prod' },\n header: {\n title: { text: 'AI Assistant' },\n leftAction: {\n icon: 'home',\n onClick: () => router.push('/'),\n },\n },\n });\n\n return (\n \n );\n}\n``` ``` -------------------------------- ### setComposerValue Pre-fill and File Attachment Source: https://context7.com/openai/chatkit-js/llms.txt Populate the composer input without sending. Use to inject suggested text, pre-attach files, or select/clear tools. Files are uploaded by ChatKit to the server. ```ts // Pre-fill text and select a tool await chatkit.setComposerValue({ text: 'Draft a reply to this email: ', selectedToolId: 'email-compose', }); ``` ```ts // Upload local files (ChatKit handles the server upload) const fileInput = document.querySelector('#file-input'); await chatkit.setComposerValue({ files: Array.from(fileInput.files ?? []), }); ``` ```ts // Clear tool selection await chatkit.setComposerValue({ selectedToolId: null }); ``` -------------------------------- ### Configure TypeScript for Global ChatKit Types Source: https://github.com/openai/chatkit-js/blob/main/packages/chatkit/README.md Add `@openai/chatkit` to `compilerOptions.types` in your `tsconfig.json` to make the `openai-chatkit` element and its CustomEvents globally available, especially when using the custom element in JSX without explicit imports. ```json { "compilerOptions": { "types": ["@openai/chatkit"] } } ``` -------------------------------- ### Integrate ChatKit with React Source: https://github.com/openai/chatkit-js/blob/main/packages/docs/src/content/docs/index.mdx This snippet demonstrates how to embed the ChatKit component in a React application using the `useChatKit` hook for control and configuration. ```tsx function MyChat({ clientToken }) { const { control } = useChatKit({ api: { url, domainKey } }); return ( ); } ``` -------------------------------- ### Create ChatKit Session with Python FastAPI Source: https://github.com/openai/chatkit-js/blob/main/README.md This FastAPI endpoint generates a 'client_secret' for a ChatKit session using the OpenAI Python client, which is required for client-side initialization. ```python from fastapi import FastAPI from pydantic import BaseModel from openai import OpenAI import os app = FastAPI() openai = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) @app.post("/api/chatkit/session") def create_chatkit_session(): session = openai.chatkit.sessions.create({ # ... }) return { client_secret: session.client_secret } ``` -------------------------------- ### UseChatKitOptions type definition Source: https://github.com/openai/chatkit-js/blob/main/packages/docs/src/content/docs/quick-reference/use-chatkit.mdx Combines ChatKitOptions with React-friendly camel-cased event handlers (onReady, onResponseStart, onResponseEnd, onThreadChange, onThreadLoadStart, onThreadLoadEnd, onError, onLog, onEffect, onDeeplink). ```typescript type UseChatKitOptions = ChatKitOptions & Partial<{ onReady: () => void; onResponseStart: () => void; onResponseEnd: () => void; onThreadChange: (event: { threadId: string | null }) => void; onThreadLoadStart: (event: { threadId: string }) => void; onThreadLoadEnd: (event: { threadId: string }) => void; onError: (event: { error: Error }) => void; onLog: (event: { name: string; data?: Record }) => void; onEffect: (event: { name: string; data?: Record }) => void; onDeeplink: (event: { name: string; data?: Record }) => void; }>; ``` -------------------------------- ### focusComposer() — Utility method Source: https://context7.com/openai/chatkit-js/llms.txt Programmatically focuses the composer textarea. Useful for directing user attention after a tooltip or call-to-action. ```APIDOC ## focusComposer() ### Description Programmatically focuses the composer textarea to direct user input. Useful after displaying a tooltip or call-to-action. ### Method Signature ```ts await chatkit.focusComposer(): Promise ``` ### Parameters None ### Response Returns a Promise that resolves when focus is set. ### Example ```ts // Focus the composer textarea (e.g. after a tooltip CTA) await chatkit.focusComposer(); ``` ```