Skip to main content

Documentation Index

Fetch the complete documentation index at: https://cometchat-22654f5b-react-uikit-v7.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

Overview

The AI Assistant feature provides two components that work together to deliver AI-powered conversations:
  • CometChatAIAssistantChat — A full-screen AI chat orchestrator with message list, composer, chat history sidebar, and streaming support
  • CometChatAIAssistantBubble — A bubble component that renders completed AI responses with markdown formatting and copy-to-clipboard
Both components are part of the AI plugin system and integrate with the CometChatAIPlugin registered via CometChatProvider.

CometChatAIAssistantChat

A complete AI chat interface that wraps CometChatMessageList, CometChatMessageComposer, and CometChatMessageHeader into a cohesive experience for conversing with an AI assistant.

Basic Usage

import { CometChat } from '@cometchat/chat-sdk-javascript';
import { CometChatAIAssistantChat } from '@cometchat/chat-uikit-react/plugins/ai';

function AIChat() {
  const [aiUser, setAiUser] = useState<CometChat.User | null>(null);

  useEffect(() => {
    CometChat.getUser("ai-agent-uid").then(setAiUser);
  }, []);

  if (!aiUser) return null;

  return (
    <CometChatAIAssistantChat
      user={aiUser}
      streamingSpeed={30}
      showSuggestedMessages
    />
  );
}

Props

PropTypeDefaultDescription
userCometChat.UserRequired. The AI assistant user object.
streamingSpeednumber30Delay in milliseconds between text chunks during streaming.
aiAssistantToolsCometChatAIAssistantToolsClient-side tool handlers for function calls.
loadLastAgentConversationbooleanfalseAuto-load the most recent conversation on mount.
showSuggestedMessagesbooleantrueWhether to display suggestion pills in the greeting state.
suggestedMessagesstring[][]Custom suggestion texts. Overrides user metadata suggestions.
greetingViewReactNodeCustom greeting view replacing the default greeting + intro.
hideChatHistorybooleanfalseHide the chat history sidebar toggle button.
hideNewChatbooleanfalseHide the “New Chat” button in the header.
showBackButtonbooleanfalseShow a back button in the header.
showCloseButtonbooleanfalseShow a close button in the header.
onBackButtonClicked() => voidCallback when the back button is clicked.
onCloseButtonClicked() => voidCallback when the close button is clicked.
onSendButtonClick(message: CometChat.BaseMessage) => voidCallback when a message is sent.
emptyViewReactNodeCustom empty state replacing the default greeting screen.
loadingViewReactNodeCustom loading view.
errorViewReactNodeCustom error view.
onError(error: unknown) => voidCallback when an error occurs.
classNamestringCustom CSS class name for the root element.
parentMessageIdnumberLoad a specific conversation thread by message ID.

Chat History Sidebar

The AI assistant includes a slide-in sidebar that displays past conversations with the AI agent. Users can browse previous threads and resume any conversation.
<CometChatAIAssistantChat
  user={aiUser}
  hideChatHistory={false}
  loadLastAgentConversation={true}
/>
Sidebar behavior:
  • Toggle the sidebar via the history icon button in the header
  • Clicking a past conversation loads that thread in the message list
  • The “New Chat” button (inside the sidebar) starts a fresh conversation
  • An overlay dims the main chat area while the sidebar is open
  • Focus is trapped within the sidebar when open and restored to the trigger button on close

Suggested Messages via User Metadata

The greeting screen displays suggestion pills that users can tap to quickly start a conversation. Suggestions are configured through the AI assistant user’s metadata:
// Set on the AI user's metadata (via CometChat Dashboard or SDK)
const metadata = {
  greetingMessage: "Hi! I'm your AI assistant",
  introductoryMessage: "I can help you with questions about our product.",
  suggestedMessages: [
    "How do I get started?",
    "What features are available?",
    "Show me an example"
  ]
};
You can also override metadata suggestions with the suggestedMessages prop:
<CometChatAIAssistantChat
  user={aiUser}
  suggestedMessages={["Help me set up", "What can you do?"]}
/>
When a suggestion pill is clicked, its text is inserted into the composer input via the ui:compose/text event.

Composer Behavior During Streaming

While the AI is generating a response, the composer enters a disabled state:
  • The input area blocks keyboard interaction (prevents sending messages mid-stream)
  • The send button displays a “streaming” visual state and is non-interactive
  • Once the stream completes (isComplete: true), the composer re-enables automatically
<CometChatAIAssistantChat
  user={aiUser}
  streamingSpeed={40}  // Slower typing effect
/>
The streamingSpeed prop controls the delay between text chunks — lower values produce faster typing, higher values give a more readable streaming effect.

Full Example with Tools

import {
  CometChatAIAssistantChat,
  CometChatAIAssistantTools,
} from '@cometchat/chat-uikit-react/plugins/ai';

const tools = new CometChatAIAssistantTools({
  openProfile: (args) => {
    const { userId } = args as { userId: string };
    navigate(`/users/${userId}`);
  },
  showHelp: () => {
    setHelpVisible(true);
  },
});

function AIPanel() {
  return (
    <CometChatAIAssistantChat
      user={aiUser}
      aiAssistantTools={tools}
      streamingSpeed={30}
      showBackButton
      onBackButtonClicked={() => setShowAI(false)}
      onError={(err) => console.error('AI error:', err)}
    />
  );
}

CometChatAIAssistantBubble

Renders a completed AI assistant message with full markdown formatting and a copy-to-clipboard action. This component is used by the CometChatAIPlugin’s renderBubble method to display messages of type assistant in the agentic category.

Basic Usage

import { CometChatAIAssistantBubble } from '@cometchat/chat-uikit-react/plugins/ai';

<CometChatAIAssistantBubble message={aiMessage} alignment="left" />

Props

PropTypeDefaultDescription
messageCometChat.BaseMessageRequired. The AI assistant message to render.
alignment'left' | 'right''left'Bubble alignment. left for incoming AI responses, right for outgoing.
classNamestringCustom CSS class name.

Markdown Rendering

The bubble uses CometChatMarkdownFormatter to render rich content including:
  • Bold, italic, strikethrough, and inline code
  • Fenced code blocks with syntax highlighting
  • Ordered and unordered lists
  • Tables, blockquotes, and links
  • Images (clickable to expand)
All rendered HTML is sanitized via sanitizeAIHtml() before being injected into the DOM, preventing XSS from AI-generated content.

Copy-to-Clipboard

A copy button is rendered below the message content. When clicked:
  1. The raw text (pre-markdown, without HTML) is copied to the clipboard
  2. A “Copied!” confirmation appears briefly (2 seconds)
  3. The navigator.clipboard API is used with a document.execCommand fallback for older browsers

Alignment

The alignment prop controls the bubble’s visual positioning:
  • 'left' (default) — AI responses appear on the left side of the message list, styled as incoming messages
  • 'right' — Used when the AI message is contextually sent by the current user (rare)
The alignment value is set via a data-alignment attribute on the root element, which CSS uses for directional styling (border radius, background color).

AIPlugin renderBubble Relationship

You typically don’t render CometChatAIAssistantBubble directly. The CometChatAIPlugin handles rendering automatically when it encounters an assistant type message:
// Inside CometChatAIPlugin.renderBubble():
// For messages with type === 'assistant' and category === 'agentic'
renderBubble(message, context) {
  const alignment = context.alignment === 'right' ? 'right' : 'left';
  const type = message.getType();

  if (type === 'assistant') {
    return (
      <Suspense fallback={null}>
        <CometChatAIAssistantBubble message={message} alignment={alignment} />
      </Suspense>
    );
  }
  // ... other message types (toolArguments, toolResults, run_started)
}
The bubble component is lazy-loaded — it’s only fetched when the first AI assistant message needs to render, keeping it out of the initial bundle.

Plugin Registration

To enable AI assistant bubbles in the message list, register the CometChatAIPlugin:
import { CometChatProvider } from '@cometchat/chat-uikit-react';
import { defaultPlugins } from '@cometchat/chat-uikit-react/plugins/core';
import { CometChatAIPlugin } from '@cometchat/chat-uikit-react/plugins/ai';

<CometChatProvider
  appId="YOUR_APP_ID"
  region="YOUR_REGION"
  authKey="YOUR_AUTH_KEY"
  plugins={[...defaultPlugins, CometChatAIPlugin]}
>
  {/* AI assistant messages will render with CometChatAIAssistantBubble */}
</CometChatProvider>

Streaming State Reference

Both components interact with the streaming service. Here’s the state shape that drives rendering:
interface CometChatStreamState {
  text: string;              // Accumulated text content
  isComplete: boolean;       // Whether the stream has finished
  activeToolCall: string | null;
  toolExecutionText: string;
  isThinking: boolean;       // AI processing before first text
  hasContent: boolean;       // Whether any text has been received
  hasError: boolean;         // Network/offline error occurred
  hasStarted: boolean;       // Whether streaming has begun
}
StateComposer BehaviorBubble Behavior
hasStarted && !isCompleteInput disabled, send button shows streaming iconCometChatStreamMessageBubble renders with typing effect
isCompleteInput re-enabled, send button activeCometChatAIAssistantBubble renders final markdown
hasErrorInput re-enabledError indicator shown