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

# Embedding Multiple Agents

> Embed multiple AI agents on a single webpage with complete state isolation

## Overview

Mindset AI SDK 3 lets you embed multiple AI agents on a single webpage. Each agent operates independently with complete state isolation—conversations, inputs, and errors in one agent don't affect others.

This enables you to provide specialized agents for different contexts: a sales assistant in your checkout flow, a support bot in your account section, and a product expert on your catalog pages—all on the same site.

<Note>
  **SDK 3 Required:** Multi-agent embedding is available in SDK 3.
</Note>

## Quick Start

Include the SDK once, define multiple agents, and initialize—all agents render automatically.

```html theme={null}
<!-- Include the SDK -->
<script src="MINDSET-SERVER-URL/mindset-sdk3.umd.js"></script>

<!-- Define multiple agents -->
<mindset-agent agentUid="sales-assistant-agent-uid"></mindset-agent>
<mindset-agent agentUid="support-bot-agent-uid"></mindset-agent>

<!-- Initialize once - all agents render automatically -->
<script>
  window.mindset.init({
    appUid: 'your-app-uid',
    fetchAuthentication: async () => {
      const token = await yourAuthService.getToken();
      return { token };
    }
  });
</script>
```

<Warning>
  **`Call init() only once.`** The SDK automatically discovers and renders all `<mindset-agent>` tags on the page.
</Warning>

## How It Works

### Instance Isolation

Each agent receives a unique instance ID (`{agentUid}::{uuid}`), ensuring complete isolation:

| Resource                 | Behavior                                               |
| ------------------------ | ------------------------------------------------------ |
| **Conversation History** | Each agent maintains separate message threads          |
| **User Input**           | Typing in one agent doesn't affect others              |
| **Error State**          | Errors in one agent don't cascade to others            |
| **Theme/Styling**        | Shared across all agents (configured once in `init()`) |

### Shadow DOM

Each agent renders inside its own Shadow DOM container, providing:

* **CSS Isolation** — Your website styles don't affect agents, and vice versa
* **DOM Isolation** — Agent elements don't interfere with your page's JavaScript

<Tip>
  Shadow DOM ensures agents can be safely embedded in any website without CSS conflicts or JavaScript interference.
</Tip>

## Configuration

### Agent Tag Attributes

```html theme={null}
<mindset-agent agentUid="your-agent-uid"></mindset-agent>
```

| Attribute  | Required | Description                                                     |
| ---------- | -------- | --------------------------------------------------------------- |
| `agentUid` | Yes      | Unique identifier from Agent Management Studio (case-sensitive) |

### Initialization Options

```javascript theme={null}
window.mindset.init({
  // Required
  appUid: 'your-app-uid',
  fetchAuthentication: async () => ({ token: 'your-token' }),

  // Optional - Theme (applies to all agents)
  theme: {
    brightness: 'light',
    seedColor: '#5a8eff',
    dynamicSchemeVariant: 'content',
  },

  // Optional - Custom Font (applies to all agents)
  customFontTheme: {
    fontFamily: 'Inter',
  },

  // Optional
  enableVoice: false,
});
```

<Note>
  Theme and font customization apply to **all agents** on the page. Individual agents cannot have different themes.
</Note>

## Dynamic Agent Embedding

The SDK automatically detects agents added after initialization—useful for single-page applications and conditional loading.

```javascript theme={null}
// Initialize SDK first
await window.mindset.init({
  appUid: 'your-app-uid',
  fetchAuthentication: async () => ({ token: 'your-token' }),
});

// Later, add a new agent dynamically
const newAgent = document.createElement('mindset-agent');
newAgent.setAttribute('agentUid', 'contextual-helper-agent-uid');
document.getElementById('help-section').appendChild(newAgent);
// Agent renders automatically - no additional code needed
```

### Use Cases

**Single Page Applications** — Add agents on route changes without re-initializing

**Conditional Display** — Show agents based on user actions or state

**Lazy Loading** — Add agents only when their section becomes visible

## Flexible UI with Multiple Agents

When using Flexible UI (via `<mindset-container>`), only the first container on the page receives full flexible UI support. Subsequent containers render their agents as standard floating chat windows.

### What is Flexible UI?

Flexible UI provides display modes like tray view, pill button, and smooth transitions between minimized/maximized states. It's enabled by wrapping `<mindset-agent>` in a `<mindset-container>`.

### The Limitation

```html theme={null}
<!-- ✅ First container - Gets full flexible UI -->
<mindset-container
  agent-view-mode="all"
  agent-title="Sales Assistant"
  agent-icon="https://example.com/icon.png">
  <mindset-agent agentUid="sales-agent-uid"></mindset-agent>
</mindset-container>

<!-- ⚠️ Second container - NO flexible UI, renders as standard chat -->
<mindset-container
  agent-view-mode="tray-only"
  agent-title="Support Bot">
  <mindset-agent agentUid="support-agent-uid"></mindset-agent>
</mindset-container>
```

| Container   | Flexible UI | Display Modes                                              | Tray/Pill Button |
| ----------- | ----------- | ---------------------------------------------------------- | ---------------- |
| **First**   | ✅ Yes       | ✅ all/chat-only/tray-only/no-tray/docked-left/docked-right | ✅ Available      |
| **Second+** | ❌ No        | ❌ Fixed floating window                                    | ❌ Not available  |

### Recommended Pattern

Use flexible UI for your primary agent only, and standard `<mindset-agent>` tags for others:

```html theme={null}
<!-- Primary agent with flexible UI -->
<mindset-container agent-view-mode="all">
  <mindset-agent agentUid="primary-agent-uid"></mindset-agent>
</mindset-container>

<!-- Additional agents without container -->
<mindset-agent agentUid="secondary-agent-uid"></mindset-agent>
<mindset-agent agentUid="tertiary-agent-uid"></mindset-agent>
```

## Best Practices

### Authentication with Token Refresh

Always return a fresh or refreshed token from `fetchAuthentication`:

```javascript theme={null}
fetchAuthentication: async () => {
  // Always return fresh/refreshed token
  const token = await yourAuthService.getOrRefreshToken();
  if (!token) throw new Error('Authentication failed');
  return { token };
}
```

### Strategic Placement

Place agents where they provide contextual help:

```html theme={null}
<section class="checkout">
  <mindset-agent agentUid="checkout-helper"></mindset-agent>
</section>

<section class="account">
  <mindset-agent agentUid="account-support"></mindset-agent>
</section>
```

This ensures users get relevant assistance in each section of your application.

### Mobile Considerations

Consider limiting the number of agents on smaller screens:

```javascript theme={null}
if (window.innerWidth > 768) {
  // Show multiple agents on desktop
} else {
  // Show only primary agent on mobile
}
```

Multiple floating chat windows can overwhelm mobile users—prioritize the most important agent.

## Use Cases

<CardGroup cols={2}>
  <Card title="Contextual Support" icon="compass">
    Deploy different agents in different sections: checkout assistant, account support, product expert
  </Card>

  <Card title="Role-Based Agents" icon="users">
    Show specialized agents based on user role: customer agent, admin agent, partner agent
  </Card>

  <Card title="Single Page Apps" icon="browser">
    Dynamically add/remove agents as users navigate between routes
  </Card>

  <Card title="Progressive Enhancement" icon="layer-group">
    Start with one agent, add more based on user behavior or session length
  </Card>
</CardGroup>

## Troubleshooting

### Agent not rendering

**Possible causes:**

* Invalid `agentUid`
* Agent UID doesn't match Agent Management Studio exactly (case-sensitive)
* SDK not loaded before agent tags

**Solution:** Verify the UID matches Agent Management Studio exactly. Ensure SDK script loads before `<mindset-agent>` tags appear in the DOM.

### Authentication error

**Possible causes:**

* `fetchAuthentication` not returning correct format
* Token is invalid or expired
* Network request failed

**Solution:** Ensure `fetchAuthentication` returns `{ token: string }`. Check token validity. Verify network connectivity.

### Agent shows error screen

**Possible causes:**

* SDK initialization failed
* Invalid configuration parameters
* Network connectivity issues

**Solution:** Check browser console for error codes. Verify all required parameters (`appUid`, `fetchAuthentication`) are provided.

### Styles look broken

**Possible causes:**

* CSS conflicts with website styles
* Outdated SDK version
* Browser compatibility issues

**Solution:** Ensure you're using the latest SDK version. Check that Shadow DOM is supported in your browser. Update SDK to latest version.

### Multiple agents sharing state

**Possible causes:**

* SDK bug (rare)
* Multiple `init()` calls
* Incorrect agent UID configuration

**Solution:** Verify you're calling `init()` only once. Ensure each agent has a unique `agentUid`. Update SDK to latest version. If issue persists, contact [support@mindset.ai](mailto:support@mindset.ai).

## Browser Support

**Supported browsers:** Chrome 90+, Firefox 88+, Safari 14+, Edge 90+

<Note>
  Older browsers may not support Shadow DOM or other modern features required by the SDK.
</Note>

## Examples

### Example 1: E-commerce Site

```html theme={null}
<!-- Product pages - Product expert -->
<div class="product-detail">
  <mindset-agent agentUid="product-expert-uid"></mindset-agent>
</div>

<!-- Checkout - Sales assistant -->
<div class="checkout-flow">
  <mindset-agent agentUid="checkout-assistant-uid"></mindset-agent>
</div>

<!-- Account - Support bot -->
<div class="account-settings">
  <mindset-agent agentUid="account-support-uid"></mindset-agent>
</div>
```

### Example 2: SaaS Dashboard

```html theme={null}
<!-- Main dashboard - General assistant with flexible UI -->
<mindset-container agent-view-mode="all">
  <mindset-agent agentUid="general-assistant-uid"></mindset-agent>
</mindset-container>

<!-- Analytics page - Data expert -->
<div class="analytics-section">
  <mindset-agent agentUid="analytics-expert-uid"></mindset-agent>
</div>

<!-- Settings - Configuration helper -->
<div class="settings-section">
  <mindset-agent agentUid="settings-helper-uid"></mindset-agent>
</div>
```

### Example 3: Dynamic Loading (SPA)

```javascript theme={null}
// Router logic for single-page app
router.on('/products', () => {
  const productAgent = document.createElement('mindset-agent');
  productAgent.setAttribute('agentUid', 'product-expert-uid');
  document.getElementById('agent-container').appendChild(productAgent);
});

router.on('/support', () => {
  const supportAgent = document.createElement('mindset-agent');
  supportAgent.setAttribute('agentUid', 'support-bot-uid');
  document.getElementById('agent-container').appendChild(supportAgent);
});
```
