> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-agent-native-development.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Agents

> Handle CometChat AI Agent events, tool calls, and agent messages in JavaScript apps.

<Accordion title="AI Integration Quick Reference">
  | Field | Value |
  | - | - |
  | Package | `@cometchat/chat-sdk-javascript` |
  | Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` |
  | Key methods | `CometChat.addAIAssistantListener(listenerId, ...)` · `CometChat.removeAIAssistantListener(listenerId)` · `CometChat.addMessageListener(listenerId, ...)` · `CometChat.removeMessageListener(listenerId)` |
  | Key classes | `CometChat.AIAssistantBaseEvent` · `CometChat.AIAssistantMessage` · `CometChat.AIToolResultMessage` · `CometChat.AIToolArgumentMessage` · `CometChat.AIToolCall` |
  | Primary output | Real-time run events are delivered as `CometChat.AIAssistantBaseEvent` objects to the `onAIAssistantEventReceived` callback; after the run completes, persisted `AIAssistantMessage` / `AIToolResultMessage` / `AIToolArgumentMessage` objects arrive on the `MessageListener` |
  | Listeners registered | `AIAssistantListener` via `addAIAssistantListener` / `removeAIAssistantListener` (callback `onAIAssistantEventReceived`); `CometChat.MessageListener` via `addMessageListener` / `removeMessageListener` (callbacks `onAIAssistantMessageReceived`, `onAIToolResultReceived`, `onAIToolArgumentsReceived`) |
  | Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) |
  | Constraints | Agents only respond to text messages. `Run Start` and `Run Finished` events are always emitted; Tool Call events only appear when tools are invoked |
  | Related | [AI Moderation](/sdk/javascript/ai-moderation) · [AI User Copilot](/sdk/javascript/ai-user-copilot-overview) · [Card Messages](/sdk/javascript/card-messages) · [Send a Message](/sdk/javascript/send-message) |
  | Full reference | [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) · [`AIAssistantMessage`](/sdk/reference/messages#aiassistantmessage) · [`AIToolResultMessage`](/sdk/reference/messages#aitoolresultmessage) · [`AIToolArgumentMessage`](/sdk/reference/messages#aitoolargumentmessage) |
</Accordion>

## AI Agents Overview

AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents).

<Note>Agents only respond to text messages.</Note>

## Agent Run Lifecycle and Message Flow

When a user sends a text message to an Agent:

1. The platform starts a run and streams real-time events via `AIAssistantListener`
2. After the run completes, persisted Agentic Messages arrive via `MessageListener`

### Real-time Events

Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantListener`** class as [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) objects, in this general order:

Events arrive via `onAIAssistantEventReceived` in this order:

| Order | Event | Description |
| - | - | - |
| 1 | Run Start | A new run has begun |
| 2 | Tool Call Start | Agent decided to invoke a tool |
| 3 | Tool Call Arguments | Arguments being passed to the tool |
| 4 | Tool Call End | Tool execution completed |
| 5 | Tool Call Result | Tool's output is available |
| 6 | Text Message Start | Agent started composing a reply |
| 7 | Text Message Content | Streaming content chunks (multiple) |
| 8 | Text Message End | Agent reply is complete |
| 9 | Run Finished | Run finalized; persisted messages follow |

<Note>
  `Run Start` and `Run Finished` are always emitted. Tool Call events only
  appear when tools are invoked — there can be multiple tool call cycles in a
  single run. Text Message events are always emitted and carry the assistant's
  reply incrementally.
</Note>

### Event Object Properties

Every event is an `AIAssistantBaseEvent` with these common properties:

| Getter | Return Type | Description |
| - | - | - |
| `getType()` | `string` | Event type (e.g., `run_started`, `text_message_content`) |
| `getConversationId()` | `string` | The conversation this event belongs to |
| `getMessageId()` | `string` | The message ID associated with the event |
| `getParentMessageId()` | `string` | Parent message ID (for threaded messages) |
| `getRunId()` | `string` | The run ID for this agent execution |
| `getThreadId()` | `string` | The thread ID for this agent execution |
| `getTimestamp()` | `number` | Timestamp of the event |
| `getData()` | `object` | Full event data payload |

Some events carry additional data:

| Event | Extra Getter | Description |
| - | - | - |
| Text Message Content | `getDelta()` | The streaming text chunk for progressive rendering |
| Tool Call Arguments | `getToolCallId()`, `getDelta()` | Tool call ID and argument chunk |
| Tool Call Result | `getToolCallId()`, `getContent()`, `getRole()` | Tool call ID, result content, and role |

<Tabs>
  <Tab title="TypeScript">
    ```ts theme={null}
            const listnerId: string = "unique_listener_id";

            // Adding the AIAssistantListener
            CometChat.addAIAssistantListener(listnerId, {
                onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => {
                    console.log("AIAssistant event received successfully", message);
                }
            });

            // Removing the AIAssistantListener
            CometChat.removeAIAssistantListener(listnerId);
    ```
  </Tab>

  <Tab title="JavaScript">
    ```ts theme={null}
            const listnerId: string = "unique_listener_id";

            // Adding the AIAssistantListener
            CometChat.addAIAssistantListener(listnerId, {
                onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => {
                    console.log("AIAssistant event received successfully", message);
                }
            });

            // Removing the AIAssistantListener
            CometChat.removeAIAssistantListener(listnerId);
    ```
  </Tab>
</Tabs>

#### Event descriptions

* Run Start: A new run has begun for the user’s message.
* Tool Call Start: The agent decided to invoke a tool.
* Tool Call Arguments: Arguments being passed to the tool.
* Tool Call End: Tool execution completed.
* Tool Call Result: Tool’s output is available.
* Text Message Start: The agent started composing a reply.
* Text Message Content: Streaming content chunks for progressive rendering.
* Text Message End: The agent reply is complete.
* Run Finished: The run is finalized; persisted messages will follow.

### Agentic Messages

After the run completes, these messages arrive via `MessageListener`:

| Message Type | Description |
| - | - |
| `AIAssistantMessage` | The full assistant reply |
| `AIToolResultMessage` | The final output of a tool call |
| `AIToolArgumentMessage` | The arguments passed to a tool |

Each message type extends [`BaseMessage`](/sdk/reference/messages#basemessage) and has a typed data accessor:

| Message Type | Data Getter | Data Properties |
| - | - | - |
| `AIAssistantMessage` | `getAssistantMessageData()` | `getRunId()`, `getThreadId()`, `getText()` |
| `AIToolResultMessage` | `getToolResultMessageData()` | `getRunId()`, `getThreadId()`, `getText()`, `getToolCallId()` |
| `AIToolArgumentMessage` | `getToolArgumentMessageData()` | `getRunId()`, `getThreadId()`, `getToolCalls()` |

<Note>
  When an agent reply contains a card, the card is embedded inline in the
  `AIAssistantMessage` and exposed through `getElements()`. Cards are also
  streamed in real time via the `card_start` / `card` / `card_end` events on
  the `AIAssistantListener`. See the [Card Messages
  guide](/sdk/javascript/card-messages) for both flows.
</Note>

The `getToolCalls()` method on `AIToolArgumentMessage` returns an array of `AIToolCall` objects, each with:

| Getter | Return Type | Description |
| - | - | - |
| `getId()` | `string` | Unique tool call ID |
| `getType()` | `string` | Tool call type |
| `getFunction()` | `AIToolCallFunction` | Function object with `getName()` and `getArguments()` |
| `getDisplayName()` | `string` | Display name of the tool |
| `getExecutionText()` | `string` | Execution description text |

<Tabs>
  <Tab title="TypeScript">
    ```ts theme={null}
    const listnerId: string = "unique_listener_id";

    // Adding the MessageListener
    CometChat.addMessageListener(listnerId, {
        onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => {
            console.log("AI Assistant message received successfully", message);
        },
        onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => {
            console.log("AI Tool result message received successfully", message);
        },
        onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => {
            console.log("AI Tool argument message received successfully", message);
        },
    });

    // Removing the MessageListener
    CometChat.removeMessageListener(listnerId);
    ```
  </Tab>

  <Tab title="JavaScript">
    ```js theme={null}
    const listnerId = "unique_listener_id";

    // Adding the MessageListener
    CometChat.addMessageListener(listnerId, {
        onAIAssistantMessageReceived: (message) => {
            console.log("AI Assistant message received successfully", message);
        },
        onAIToolResultReceived: (message) => {
            console.log("AI Tool result message received successfully", message);
        },
        onAIToolArgumentsReceived: (message) => {
            console.log("AI Tool argument message received successfully", message);
        },
    });

    // Removing the MessageListener
    CometChat.removeMessageListener(listnerId);
    ```
  </Tab>
</Tabs>

<Warning>
  Always remove listeners when they're no longer needed (e.g., on component
  unmount or page navigation). Failing to remove listeners can cause memory
  leaks and duplicate event handling.
</Warning>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="AI Chatbots" icon="robot" href="https://assets.cometchat.io/legacy-docs/ai-chatbots/ai-bots/overview.html">
    Set up AI-powered chatbots for automated conversations
  </Card>

  <Card title="AI Moderation" icon="shield-check" href="/sdk/javascript/ai-moderation">
    Automatically moderate messages with AI
  </Card>

  <Card title="AI User Copilot" icon="wand-magic-sparkles" href="/sdk/javascript/ai-user-copilot-overview">
    AI-powered features like smart replies and conversation summaries
  </Card>

  <Card title="Send Messages" icon="paper-plane" href="/sdk/javascript/send-message">
    Send text messages that trigger AI Agent responses
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.