> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-angular-v5-docs-update.mintlify.site/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     | 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. 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>

### 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>

***

## 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>
