> ## Documentation Index
> Fetch the complete documentation index at: https://www.cometchat.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Agents

> Integrate AI Agents for intelligent automated interactions using the CometChat iOS SDK with real-time streaming events.

<Accordion title="AI Integration Quick Reference">
  | Feature                                                   | Description                                                                   |
  | --------------------------------------------------------- | ----------------------------------------------------------------------------- |
  | [AI Agents](#agent-run-lifecycle-and-message-flow)        | Intelligent automated conversations with real-time streaming                  |
  | [AI Moderation](/sdk/ios/ai-moderation)                   | Automatic content moderation with pending/approved/disapproved flow           |
  | [AI User Copilot](/fundamentals/ai-user-copilot/overview) | Smart Replies, Conversation Starter, Conversation Summary (Dashboard-enabled) |

  ```swift theme={null}
  // Listen for real-time AI Agent events (streaming)
  CometChat.addAIAssistantListener("LISTENER_ID", self)

  // Listen for persisted agentic messages
  // Conform to CometChatMessageDelegate
  func onAIAssistantMessageReceived(_ msg: AIAssistantMessage) { }
  func onAIToolResultMessageReceived(_ msg: AIToolResultMessage) { }
  func onAIToolArgumentsMessageReceived(_ msg: AIToolArgumentMessage) { }

  // Cleanup
  CometChat.removeAIAssistantListener("LISTENER_ID")
  CometChat.removeMessageListener("LISTENER_ID")
  ```

  **Prerequisites:** `CometChat.init()` + `CometChat.login()` completed, AI features enabled in [Dashboard](https://app.cometchat.com)
  **Event flow:** Run Start -> Tool Call(s) -> Text Message Stream -> Run Finished
</Accordion>

AI Agents enable intelligent, automated interactions within your application. They 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>

## Sending a Message to an AI Agent

Send a text message to an agent's UID like any other user:

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let agentUID = "ai-agent-uid"
    let textMessage = TextMessage(
        receiverUid: agentUID,
        text: "What's the weather today?",
        receiverType: .user
    )

    CometChat.sendTextMessage(message: textMessage) { sentMessage in
        print("Message sent to agent")
    } onError: { error in
        print("Error: \(error?.errorDescription)")
    }
    ```
  </Tab>
</Tabs>

## 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 `AIAssistantEventsDelegate`
2. After the run completes, persisted Agentic Messages arrive via `CometChatMessageDelegate`

### Real-time Events

Events are received via `onAIAssistantEventReceived` as [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) objects, 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     | Card Start           | Agent began producing a card             |
| 7     | Card                 | Full card payload is available           |
| 8     | Card End             | Card stream is complete                  |
| 9     | Text Message Start   | Agent started composing a reply          |
| 10    | Text Message Content | Streaming content chunks (multiple)      |
| 11    | Text Message End     | Agent reply is complete                  |
| 12    | 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. Card events (`Card Start` → `Card` → `Card End`) appear only when the agent produces a card, and repeat for each card. Text Message events are always emitted and carry the assistant's reply incrementally.
</Note>

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    import CometChatSDK

    class AIAssistantEventHandler: AIAssistantEventsDelegate {
        
        private let sdkStreamListenerId = "unique_listener_id"
        
        func addListener() {
            CometChat.addAIAssistantListener(sdkStreamListenerId, self)
        }
        
        func removeListener() {
            CometChat.removeAIAssistantListener(sdkStreamListenerId)
        }
        
        func onAIAssistantEventReceived(_ event: AIAssistantBaseEvent) {
            print("Received AI Event: \(event.type) for Run ID: \(event.id)")
        }
    }
    ```
  </Tab>
</Tabs>

#### Card Streaming Events

When an agent produces a card, it is delivered through three streaming events on `onAIAssistantEventReceived`. Each event is a subclass of [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) — check the concrete type to handle it.

| Event                          | Accessor          | Description                                              |
| ------------------------------ | ----------------- | -------------------------------------------------------- |
| `AIAssistantCardStartedEvent`  | `cardId`          | Identifier for the card being generated.                 |
|                                | `executionText`   | Loading label shown while the card is built.             |
|                                | `streamMessageId` | Identifier of the streaming message that owns this card. |
| `AIAssistantCardReceivedEvent` | `cardId`          | Identifier matching the corresponding start event.       |
|                                | `getCard()`       | The complete card payload (`[String: Any]?`) to render.  |
| `AIAssistantCardEndedEvent`    | `cardId`          | Signals the card stream for this `cardId` is complete.   |

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    import CometChatSDK

    func onAIAssistantEventReceived(_ event: AIAssistantBaseEvent) {
        switch event {
        case let started as AIAssistantCardStartedEvent:
            let cardId = started.cardId
            let label = started.executionText   // e.g. "Building card…"
        case let received as AIAssistantCardReceivedEvent:
            let cardId = received.cardId
            let card = received.getCard()        // full card payload
        case let ended as AIAssistantCardEndedEvent:
            // card stream for ended.cardId is complete
            break
        default:
            break
        }
    }
    ```
  </Tab>
</Tabs>

### Agentic Messages

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

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

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    import CometChatSDK

    let listenerId = "unique_listener_id"

    class MessageHandler: CometChatMessageDelegate {
        
        // CometChat.addMessageListener(listenerId, self)
        
        func onAIAssistantMessageReceived(_ aiAssistantMessage: AIAssistantMessage) {
            print("AI Assistant Message Received: \(aiAssistantMessage)")
        }
        
        func onAIToolResultMessageReceived(_ aiToolResultMessage: AIToolResultMessage) {
            print("AI Tool Result Message Received: \(aiToolResultMessage)")
        }
        
        func onAIToolArgumentsMessageReceived(_ aiToolArgumentMessage: AIToolArgumentMessage) {
            print("AI Tool Arguments Message Received: \(aiToolArgumentMessage)")
        }
    }
    ```
  </Tab>
</Tabs>

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

### AIAssistantMessage Elements

Once a run completes, the assistant's reply is persisted as an `AIAssistantMessage`. Its content is exposed as an ordered list of blocks via `getElements()`, letting you render text and cards in the exact order the agent produced them. When `getElements()` is `nil` or empty, fall back to the plain `text` body.

| Method          | Returns                 | Description                                                 |
| --------------- | ----------------------- | ----------------------------------------------------------- |
| `getElements()` | `[AIAssistantElement]?` | Ordered content blocks. `nil`/empty for plain-text replies. |
| `text`          | `String`                | Plain-text body (fallback when there are no elements).      |

Each `AIAssistantElement` exposes:

| Method      | Returns  | Description                                    |
| ----------- | -------- | ---------------------------------------------- |
| `getType()` | `String` | Block type — `"text"` or `"card"`.             |
| `getData()` | `Any?`   | The block body (text string, or card payload). |

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    import CometChatSDK

    if let elements = message.getElements(), !elements.isEmpty {
        for element in elements {
            switch element.getType() {
            case "text":
                renderText(String(describing: element.getData() ?? ""))
            case "card":
                renderCard(element.getData())
            default:
                break
            }
        }
    } else {
        renderText(message.text)
    }
    ```
  </Tab>
</Tabs>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="AI Chatbots" icon="robot" href="/ai-chatbots/overview">
    Set up AI-powered chatbots for automated conversations
  </Card>

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

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

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