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

# Introduction

> Get started with the AI Chat SDK for web applications

## Overview

The AI Chat SDK (`@sleek/ai-chat-sdk`) enables web applications to integrate intelligent, context-aware AI chat capabilities. The SDK provides a beautiful chat interface with AI-powered recommendations and merchant offers, along with flexible entry points like floating badges and inline inputs to engage users.

## Key capabilities

* **Chat interface**: Full-featured chat panel with AI conversation interface
* **Multiple entry points**: Floating badge and inline input to engage users
* **Context-aware AI**: Optional page context for smarter, relevant responses
* **Event system**: Comprehensive events for all user interactions
* **Data integration**: Display offer redirect URLs and cashback offers in conversations
* **Full customization**: Brand colors, logos, fonts, and light/dark mode support
* **Multiple package formats**: NPM package or IIFE script injection
* **Shadow DOM isolation**: Prevents styling conflicts with your application

## Prerequisites

Before integrating the SDK, ensure your project meets these requirements:

* **Modern browser** with ES6+ support (Chrome 100+, Firefox 100+, Safari 15+, Edge 100+)
* **Node.js** 18+ and package manager (pnpm, npm, or yarn) for NPM installation

## Installation

<Tabs>
  <Tab title="NPM / PNPM">
    <Steps>
      <Step title="Configure npm registry">
        Add the registry to your `.npmrc` file:

        ```bash .npmrc theme={null}
        @sleek:registry=https://npm.cloudsmith.io/sleek/sleek/
        //npm.cloudsmith.io/sleek/sleek/:_authToken={YOUR_TOKEN_HERE}
        ```

        <Note>
          Contact [support@onsleek.com](mailto:support@onsleek.com) to receive your authentication token.
        </Note>
      </Step>

      <Step title="Install the package">
        ```bash theme={null}
        # Using pnpm
        pnpm add @sleek/ai-chat-sdk

        # Using npm
        npm install @sleek/ai-chat-sdk
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="IIFE (Script Injection)">
    <Note>
      If you're using the IIFE bundle for script injection, you do not need to install it via a package manager.
    </Note>

    <Steps>
      <Step title="Download SDK package">
        Download the latest SDK release using curl with your authentication token:

        ```bash theme={null}
        TOKEN="{YOUR_TOKEN_HERE}"; curl -s -L -H "Authorization: Bearer ${TOKEN}" "https://npm.cloudsmith.io/sleek/sleek/@sleek/ai-chat-sdk/latest" | jq -r '.dist.tarball' | xargs -I {} curl -s -L -H "Authorization: Bearer ${TOKEN}" {} | tar -xzvf -
        ```

        <Note>
          Contact [support@onsleek.com](mailto:support@onsleek.com) to receive your authentication token.
        </Note>

        Alternatively, if you have the package installed via npm, copy from node\_modules:

        ```bash theme={null}
        # Copy from node_modules after installation
        cp node_modules/@sleek/ai-chat-sdk/dist/ai-chat-sdk.iife.js public/
        ```

        The IIFE bundle will be located at `package/dist/ai-chat-sdk.iife.js` after extraction.
      </Step>

      <Step title="Inject into the page">
        Add the script tag to your HTML:

        ```html theme={null}
        <script src="/ai-chat-sdk.iife.js"></script>
        <script>
          // SDK is available on globalThis.sleek
          sleek.initializeAiChatSdk('your-api-key', {
            chatConfig: {
              brand: {
                logoUrl: 'https://your-app.com/logo.png',
                name: 'Your Brand',
              },
              styling: {
                primaryColor: '#5C59FE',
              },
            },
            dataProviders: {
              offerRedirectUrlProvider: async (url) => {
                return `https://offer.example.com?url=${encodeURIComponent(url)}`;
              },
              merchantCashbackProvider: async (urls) => {
                const result = {};
                for (const url of urls) {
                  result[url] = { text: '5% cash back' };
                }
                return result;
              },
            },
          });
        </script>
        ```
      </Step>
    </Steps>
  </Tab>
</Tabs>

## Quick start

Here's a minimal example to get the SDK running in your application:

<CodeGroup>
  ```typescript ESM / TypeScript theme={null}
  import {
    initializeAiChatSdk,
    getAiChatSdk,
    AiChatSdkEventType,
  } from '@sleek/ai-chat-sdk';

  // Initialize the SDK
  const sdk = initializeAiChatSdk('your-api-key', {
    enableDebug: true,
    chatConfig: {
      usePageContext: true,
      brand: {
        logoUrl: 'https://your-app.com/logo.png',
        name: 'Your Brand',
      },
      styling: {
        primaryColor: '#059669',
        colorMode: 'system',
      },
      content: {
        defaultPrompts: ['Show me deals', 'Compare prices'],
        disclaimerText: 'AI responses may not always be accurate',
      },
    },
    dataProviders: {
      offerRedirectUrlProvider: async (url) => {
        return `https://offer.example.com?url=${encodeURIComponent(url)}`;
      },
      merchantCashbackProvider: async (urls) => {
        const result = {};
        for (const url of urls) {
          result[url] = { text: '5% cash back' };
        }
        return result;
      },
    },
  }, [
    (event) => {
      console.log('SDK Event:', event.type, event.data);
    }
  ]);

  // Open the chat panel with an optional initial message
  sdk.initializeChat('What products are available?');
  ```

  ```javascript CommonJS theme={null}
  const {
    initializeAiChatSdk,
    getAiChatSdk,
    AiChatSdkEventType,
  } = require('@sleek/ai-chat-sdk');

  // Initialize the SDK
  const sdk = initializeAiChatSdk('your-api-key', {
    enableDebug: true,
    chatConfig: {
      usePageContext: true,
      brand: {
        logoUrl: 'https://your-app.com/logo.png',
        name: 'Your Brand',
      },
      styling: {
        primaryColor: '#059669',
        colorMode: 'system',
      },
    },
    dataProviders: {
      offerRedirectUrlProvider: async (url) => {
        return `https://offer.example.com?url=${encodeURIComponent(url)}`;
      },
      merchantCashbackProvider: async (urls) => {
        const result = {};
        for (const url of urls) {
          result[url] = { text: '5% cash back' };
        }
        return result;
      },
    },
  }, [
    (event) => {
      console.log('SDK Event:', event.type, event.data);
    }
  ]);

  // Open the chat panel
  sdk.initializeChat('What products are available?');
  ```

  ```html IIFE (Script Tag) theme={null}
  <!DOCTYPE html>
  <html>
  <head>
    <script src="/ai-chat-sdk.iife.js"></script>
  </head>
  <body>
    <button onclick="openChat()">Open AI Chat</button>
    <button onclick="showBadge()">Show Badge</button>

    <script>
      // Initialize SDK (available on globalThis.sleek)
      sleek.initializeAiChatSdk('your-api-key', {
        chatConfig: {
          brand: {
            logoUrl: 'https://your-app.com/logo.png',
            name: 'Your Brand',
          },
          styling: {
            primaryColor: '#059669',
          },
        },
        dataProviders: {
          offerRedirectUrlProvider: async (url) => {
            return `https://offer.example.com?url=${encodeURIComponent(url)}`;
          },
          merchantCashbackProvider: async (urls) => {
            return {};
          },
        },
      }, [
        (event) => console.log('Event:', event.type)
      ]);

      function openChat() {
        sleek.getAiChatSdk().initializeChat('Show me products');
      }

      function showBadge() {
        sleek.getAiChatSdk().showBadge();
      }
    </script>
  </body>
  </html>
  ```
</CodeGroup>

## SDK methods

### initializeAiChatSdk

Initializes the SDK with your API key and configuration options.

```typescript theme={null}
function initializeAiChatSdk(
  apiKey: string,
  options?: Partial<AiChatSdkOptions>,
  listeners?: AiChatSdkEventListener[]
): Sdk
```

**Parameters**:

* `apiKey`: Your API key for authentication
* `options`: Configuration options (optional)
* `listeners`: Array of event listener functions (optional)

**Returns**: SDK instance

### getAiChatSdk

Retrieves the initialized SDK instance.

```typescript theme={null}
function getAiChatSdk(): Sdk
```

**Returns**: SDK instance (throws error if not initialized)

### initializeChat

Opens the full chat panel with an optional initial message and default prompts.

```typescript theme={null}
sdk.initializeChat(initialMessage?: string, defaultPrompts?: string[]): void
```

**Parameters**:

* `initialMessage`: Optional message to send when opening the chat
* `defaultPrompts`: Optional array of prompt suggestions to display

**Example**:

```typescript theme={null}
// Open chat with initial message
sdk.initializeChat('Show me the best deals');

// Open chat with custom prompts
sdk.initializeChat(undefined, ['Compare prices', 'Find discounts', 'Show deals']);
```

### showBadge

Shows a floating badge with AI-generated prompt suggestions. When users interact with the badge, it opens the chat panel.

```typescript theme={null}
sdk.showBadge(query?: string, isOnboarding?: boolean, maxPrompts?: number): Promise<void>
```

**Parameters**:

* `query`: Optional query to generate contextual prompts
* `isOnboarding`: Whether to show onboarding content (default: false)
* `maxPrompts`: Optional maximum number of prompts to display on the badge (clamped to 1-3)

**Example**:

```typescript theme={null}
// Show badge with default prompts
await sdk.showBadge();

// Show badge with contextual prompts based on query
await sdk.showBadge('winter jackets');

// Show onboarding badge for new users
await sdk.showBadge(undefined, true);

// Show badge with at most 2 prompts
await sdk.showBadge('winter jackets', false, 2);
```

### showInline

Shows an inline input component that can be embedded in a container element. When users interact with the inline input, it opens the chat panel.

```typescript theme={null}
sdk.showInline(query?: string): Promise<void>
```

**Parameters**:

* `query`: Optional query to generate contextual prompts

**Example**:

```typescript theme={null}
// First configure the inline container in options
initializeAiChatSdk('your-api-key', {
  inlineConfig: {
    layout: {
      containerSelector: '#chat-container',
    },
  },
  // ... other options
});

// Show the inline input
await sdk.showInline();
```

## Entry points

The SDK provides multiple entry points to engage users and open the chat panel:

### Direct chat

Open the chat panel directly using `initializeChat()`. Best for explicit "Open Chat" buttons or when you want to immediately start a conversation.

```typescript theme={null}
sdk.initializeChat('Hello, how can I help?');
```

### Floating badge

A compact badge that shows AI-generated prompts. Expands on hover and opens the chat panel when clicked. Great for non-intrusive engagement that encourages users to start a conversation.

```typescript theme={null}
await sdk.showBadge();
```

### Inline input

An input field that can be embedded in any container element. When users type or click a prompt, the chat panel opens. Ideal for seamless integration with existing UI layouts.

```typescript theme={null}
await sdk.showInline();
```

## Build formats

The SDK is distributed in multiple formats for maximum compatibility:

| Format | File                  | Use Case                               |
| ------ | --------------------- | -------------------------------------- |
| IIFE   | `ai-chat-sdk.iife.js` | Script tag or runtime script injection |
| ESM    | `ai-chat-sdk.js`      | Modern bundlers (Vite, Webpack, etc.)  |
| CJS    | `ai-chat-sdk.cjs`     | Node or CommonJS environments          |

All formats include TypeScript definitions (`.d.ts`) for full IDE support.

## Getting help

* **Email support**: [support@onsleek.com](mailto:support@onsleek.com)
* **Sales inquiries**: [sales@onsleek.com](mailto:sales@onsleek.com)

## API reference

For detailed type definitions and API documentation, refer to the TypeScript definitions included with the SDK package.
