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

# Integrate an AI Agent into the Chat Widget

> Embed your AI Agent (Agent Builder or Bring Your Own Agent) into the CometChat Chat Widget.

## Prerequisites

* CometChat app (App ID, Region, Auth Key).
* Chat Widget variant configured in UI Kit Builder.
* An AI Agent already created and enabled in your app via:
  * [Agent Builder](/ai-agents/agent-builder/overview) — build and host inside CometChat, or
  * [Bring Your Own Agent](/ai-agents/mastra) — connect your own hosted agent.
* Agent ID and (optional) variant set to default to that agent.
* (Optional) Frontend Action definitions if you want UI‑bound behaviors.

***

## Step 1 - Export & Embed

In UI Kit Builder click **Get Embedded Code** → copy credentials:

* App ID
* Auth Key
* Region
* Variant ID

Example embed (HTML):

<Steps>
  <Step title="Include script (<head>)">Add script tag in document head (see snippet below).</Step>
  <Step title="Initialize (<body> end)">Add mount div + init script before closing body.</Step>
</Steps>

```html theme={null}
<script defer src="https://cdn.jsdelivr.net/npm/@cometchat/chat-embed@1.x.x/dist/main.js"></script>
```

Choose the auth flow that matches your site:

### Option A - Anonymous (Guest Mode)

**Use this when:**

* Let anyone chat anonymously without signing up or logging in.
* Perfect for marketing pages, help centers, or demo sites.

```html lines highlight={7-8, 10, 14-16, 21-22, 25-26} theme={null}
<div id="cometChatMount"></div>

<script type="module">

  //  EDIT ONLY THE TEXT INSIDE QUOTES
  const COMETCHAT_WIDGET_CONFIG = {
    appID: "YOUR_APP_ID",
    region: "YOUR_APP_REGION",   // e.g. "us", "eu", "in"
    mode: "guest",
    authKey: "YOUR_AUTH_KEY",

    // Optional: how the guest appears in chat
    user: {
      name: "Guest User",
      avatar: "",
      link: ""
    },

    // Widget placement + size
    mount: "#cometChatMount",
    width: "700px",
    height: "500px",
    isDocked: true,
    chatType: "user",
    defaultChatID: "<YOUR_AGENT_ID>",  // point to your AI agent
    variantID: "<YOUR_VARIANT_ID>",
    //dockedAlignment: "left" | "right"

    // Define your tools here
    aiAssistantTools: {
      getCurrentWeather: ({ location }) => {
        // Call your weather API, or return mock data
        return `The weather in ${location} is 25°C and sunny.`;
      },
      createTicket: ({ title }) => {
        // Call your ticketing system, or return a confirmation
        return `Ticket "${title}" created successfully with ID #12345.`;
      },
    },
  };

  CometChatApp.CometChatAuth.start(COMETCHAT_WIDGET_CONFIG);
</script>
```

### Option B - Create + Log In User On The Fly (Auth Key + UID)

**Use this when:**

* Use your existing user IDs (email, username etc.) to create and log in users automatically.
* No backend needed—CometChat creates users the first time they visit.

```html lines highlight={7-8, 10, 13, 17-19, 24-25, 28-29} theme={null}
<div id="cometChatMount"></div>

<script type="module">

  //  EDIT ONLY THE TEXT INSIDE QUOTES
  const COMETCHAT_WIDGET_CONFIG = {
    appID: "YOUR_APP_ID",
    region: "YOUR_APP_REGION",      // e.g. "us", "eu", "in"
    mode: "uid",
    authKey: "YOUR_AUTH_KEY",

    // IMPORTANT: this must be unique per user
    uid: "UNIQUE_USER_ID",          // e.g. "user_123", "customer_42"

    // Optional: user profile shown in chat
    user: {
      name: "User Name",
      avatar: "https://example.com/uid.png",
      link: "https://example.com/profile/uid"
    },

    // Widget placement + size
    mount: "#cometChatMount",
    width: "700px",
    height: "500px",
    isDocked: true,
    chatType: "user",
    defaultChatID: "<YOUR_AGENT_ID>",  // open AI agent by default
    variantID: "<YOUR_VARIANT_ID>",
    //dockedAlignment: "left" | "right"

    // Define your tools here
    aiAssistantTools: {
      getCurrentWeather: ({ location }) => {
        // Call your weather API, or return mock data
        return `The weather in ${location} is 25°C and sunny.`;
      },
      createTicket: ({ title }) => {
        // Call your ticketing system, or return a confirmation
        return `Ticket "${title}" created successfully with ID #12345.`;
      },
    },
  };

  CometChatApp.CometChatAuth.start(COMETCHAT_WIDGET_CONFIG);
</script>
```

### Option C - Backend-Created User (Auth Token Login)

**Use this when:**

* Create your users via server and login them using secure auth token on frontend.
* Ideal for sites with existing login systems and backends.

```html lines highlight={7-8, 12, 16-17, 20-21} theme={null}
<div id="cometChatMount"></div>

<script type="module">

  //  EDIT ONLY THE TEXT INSIDE QUOTES
  const COMETCHAT_WIDGET_CONFIG = {
    appID: "YOUR_APP_ID",
    region: "YOUR_APP_REGION",       // e.g. "us", "eu", "in"
    mode: "authToken",

    // Generated BY YOUR BACKEND after user login
    authToken: "USER_AUTH_TOKEN",

    // Widget placement + size
    mount: "#cometChatMount",
    width: "700px",
    height: "500px",
    isDocked: true,
    chatType: "user",
    defaultChatID: "<YOUR_AGENT_ID>",   // open AI agent by default
    variantID: "<YOUR_VARIANT_ID>",
    //dockedAlignment: "left" | "right"

    // Define your tools here
    aiAssistantTools: {
      getCurrentWeather: ({ location }) => {
        // Call your weather API, or return mock data
        return `The weather in ${location} is 25°C and sunny.`;
      },
      createTicket: ({ title }) => {
        // Call your ticketing system, or return a confirmation
        return `Ticket "${title}" created successfully with ID #12345.`;
      },
    },
  };

  CometChatApp.CometChatAuth.start(COMETCHAT_WIDGET_CONFIG);
</script>
```

> Replace the placeholder values (app ID, region, auth key or auth token, UID, agent ID, and variant ID) with values from your deployment. Keep `chatType: "user"` and set `defaultChatID` to your agent for an AI-first experience.

***

## Step 2 - Verify

| Check            | How                                                               |
| :--------------- | :---------------------------------------------------------------- |
| Agent appears    | Open widget → new conversation / agent entry available            |
| Basic reply      | Send a prompt → response under a few seconds                      |
| Tool logic works | Ask for a tool-backed request (e.g., recipe lookup or data fetch) |
| Error free       | Browser console + agent logs have no unhandled errors             |

<Note>
  If responses fail, confirm the endpoint is publicly reachable and the Agent ID matches the Dashboard configuration.
</Note>

***

## Troubleshooting

| Issue            | Fix                                                    |
| :--------------- | :----------------------------------------------------- |
| Agent not listed | Confirm it’s enabled in Dashboard + variant saved      |
| 404 from agent   | Endpoint path or agent key mismatch                    |
| Timeout          | Expose via a tunnel or deploy to a public host         |
| Tool not invoked | Ensure tool ID referenced in agent instructions & code |
| Auth error       | Re-check Auth Key / App credentials in embed snippet   |
