ChatKit JS

repository·main·Indexed 23 days ago

https://github.com/openai/chatkit-js

A batteries-included framework for building AI-powered chat experiences. It provides a production-ready, framework-agnostic chat interface via the <openai-chatkit> web component, featuring built-in support for streaming, tool integration, and interactive widgets. Includes @openai/chatkit-react for React-based interfaces with the <ChatKit /> component and useChatKit hook.

Tokens
8.3K
Snippets
18
Records
38
Agent score
83%

What's inside chatkit-js

  1. Use @openai/chatkit-react for React-based chat interfaces

    main

    The @openai/chatkit-react package provides React bindings for the ChatKit web component. It allows you to build AI-powered chat experiences using React-native patterns like JSX and hooks instead of direct DOM manipulation.

    Key features include:

    • The <ChatKit /> component for rendering the chat widget.
    • The useChatKit hook for managing configuration and handling events within the React lifecycle.
    • Full parity with the vanilla JavaScript API while maintaining a React-idiomatic developer experience.
  2. Compare OpenAI-hosted vs. Self-hosted backends

    main

    ChatKit supports two backend architectures depending on your needs for speed versus control:

    OpenAI-hosted backend

    • Best for: Fastest setup using OpenAI-managed infrastructure.
    • Management: OpenAI runs the chat server and stores messages/attachments.
    • Inference: Uses workflows published via Agent Builder.
    • Authentication: You mint short-lived ChatKit client secrets via the ChatKit API after handling auth on your own server.

    Self-hosted backend

    • Best for: Maximum control over custom workflows and proprietary data paths.
    • Management: You run the chat server and store messages/attachments.
    • Inference: Use the Agents SDK or a custom inference stack.
    • Authentication: You can inject auth headers for ChatKit requests by providing a custom fetch method to ChatKit.
    • Advanced Features: Supports Composer @-mentions, tool menus, model pickers, response cancelling, and pushing client effects from the server.
  3. Quickstart with Vanilla JavaScript

    main

    To use ChatKit in a vanilla JavaScript environment:

    1. Install the @openai/chatkit package.
    2. Create an openai-chatkit element using document.createElement('openai-chatkit').
    3. Configure the element using the .setOptions() method, passing an api object with the required url and domainKey.
    4. Append the element to a container in your DOM.
    <div id="chat-root"></div>
    <script type="module">
      import '@openai/chatkit';
    
      const chatkit = document.createElement('openai-chatkit');
    
      chatkit.setOptions({
        api: {
          url: 'http://localhost:8000/chatkit',
          domainKey: 'local-dev',
        },
      });
    
      document.getElementById('chat-root')?.append(chatkit);
    </script>
  4. Quickstart ChatKit with Vanilla JS (Web Component)

    main

    To use ChatKit in a non-React environment, use the <openai-chatkit> Web Component. Create the element, configure it using .setOptions({ api: { url, domainKey } }), and append it to the DOM.

    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);
    }
  5. Quickstart ChatKit in React

    main

    To embed ChatKit in a React application, use the useChatKit hook to obtain a control object and pass it to the <ChatKit /> component. You must provide an api configuration object containing the url and domainKey.

    function MyChat({ clientToken }) {
      const { control } = useChatKit({
        api: { url, domainKey }
      });
    
      return (
        <ChatKit 
          control={control}
          className="h-[600px] w-[320px]"
        />
      );
    }
  6. Quickstart: Set up ChatKit in a React application

    main

    To get started with ChatKit, follow these four steps:

    1. Generate a client token on your server: Create an endpoint (e.g., using FastAPI) that calls openai.chatkit.sessions.create() to return a client_secret.
    2. Install React bindings: Install the @openai/chatkit-react package via npm.
    3. Add the ChatKit JS script: Include the ChatKit CDN script in your HTML to load the core logic.
    4. Render the component: Use the ChatKit component and the useChatKit hook in your React application, providing a getClientSecret function to handle session authentication.
    npm install @openai/chatkit-react
  7. Quickstart with React

    main

    To use ChatKit in a React application:

    1. Install the @openai/chatkit-react package.
    2. Import ChatKit and useChatKit from @openai/chatkit-react.
    3. Initialize the chat interface using the useChatKit hook, providing an api configuration object containing the url and domainKey.
    4. Pass the returned control object to the ChatKit component.
    import { ChatKit, useChatKit } from '@openai/chatkit-react';
    
    export function SupportChat() {
      const { control } = useChatKit({
        api: {
          url: 'http://localhost:8000/chatkit',
          domainKey: 'local-dev',
        },
      });
    
      return <ChatKit control={control} className="h-[600px] w-[360px]" />;
    }
  8. Use the ChatKit React component

    main

    The ChatKit component is a React wrapper that renders the <openai-chatkit> web component. It requires a control object, which is obtained from the useChatKit hook. This object synchronizes the hook's state with the component. You can also pass standard HTML attributes (like className or style) and React event handlers, which are forwarded directly to the underlying web component.

    <ChatKit control={control} {...props} />
  9. Customize ChatKit via React or Web Component

    main

    ChatKit is fully configurable through a single options object. Depending on your integration method, you can apply these settings using the useChatKit hook in React or the chatkit.setOptions method when using the Web Component.

    Key configuration areas include:

    • Theme: Appearance settings like colorScheme, radius, and color.
    • Header & History: Layout management via header and browsing controls via history.
    • Start Screen: User greetings and suggested prompts.
    • Composer: Input configuration including placeholder.
    • Thread Item Actions: Controls for feedback and retry behavior.

    You can experiment with these settings in the ChatKit Playground to generate a ready-to-use configuration object.

    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,
      },
    });
  10. Configure TypeScript for @openai/chatkit global types

    main

    To make the openai-chatkit custom element and its associated CustomEvents available globally in your TypeScript project (for example, when using the custom element in JSX without an explicit import), add @openai/chatkit to the types array in your tsconfig.json under compilerOptions.

    {
      "compilerOptions": {
        "types": ["@openai/chatkit"]
      }
    }