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

# Troubleshooting

> Common issues and solutions for the AI Chat SDK

## Overview

This guide covers common issues you may encounter when integrating the AI Chat SDK and how to resolve them.

## Installation issues

### Package not found

**Symptom**: `npm install` or `pnpm add` fails with "package not found"

**Solution**:

<Steps>
  <Step title="Configure .npmrc">
    Add the registry configuration 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}
    ```
  </Step>

  <Step title="Add your token">
    Replace `{YOUR_TOKEN_HERE}` with your authentication token
  </Step>

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

<Note>
  Contact [support@onsleek.com](mailto:support@onsleek.com) if you need an authentication token.
</Note>

### Module not found

**Symptom**: `Cannot find module '@sleek/ai-chat-sdk'`

**Solution**: Verify your TypeScript configuration includes:

```json tsconfig.json theme={null}
{
  "compilerOptions": {
    "moduleResolution": "bundler",
    "esModuleInterop": true
  }
}
```

## SDK initialization issues

### SDK not initializing

**Symptom**: SDK initialization fails or throws error

**Solution**: Enable debug mode to see detailed error messages:

```typescript theme={null}
import { initializeAiChatSdk } from '@sleek/ai-chat-sdk';

const sdk = initializeAiChatSdk('your-api-key', {
  enableDebug: true,  // Shows detailed logs in console
  chatConfig: {
    // ... your config
  },
  dataProviders: {
    offerRedirectUrlProvider: async (url) => null,
    merchantCashbackProvider: async (urls) => ({}),
  },
});
```

Check the browser console for specific error messages.

### "SDK already initialized" error

**Symptom**: Error when calling `initializeAiChatSdk` multiple times

**Solution**: The SDK returns the existing instance if already initialized. Use `getAiChatSdk()` to retrieve the existing instance:

```typescript theme={null}
import { getAiChatSdk } from '@sleek/ai-chat-sdk';

const sdk = getAiChatSdk();
sdk.initializeChat();
```

## UI issues

### Chat panel not appearing

**Symptom**: Calling `sdk.initializeChat()` doesn't show the chat panel

**Common causes**:

* Invalid or missing API key
* SDK not initialized before calling `initializeChat()`
* JavaScript errors in console

**Solution**:

<Steps>
  <Step title="Enable debug mode">
    ```typescript theme={null}
    enableDebug: true
    ```
  </Step>

  <Step title="Check browser console">
    Open DevTools (F12) and look for error messages
  </Step>

  <Step title="Verify initialization">
    ```typescript theme={null}
    try {
      const sdk = getAiChatSdk();
      sdk.initializeChat();
    } catch (error) {
      console.error('SDK error:', error);
    }
    ```
  </Step>
</Steps>

### Chat panel appears blank

**Symptom**: Panel opens but shows blank content

**Solution**:

1. Verify your API key is valid
2. Check browser console for network errors
3. Ensure you have internet connectivity
4. Try clearing browser cache

### Badge not appearing

**Symptom**: Calling `sdk.showBadge()` doesn't show the badge

**Solution**:

```typescript theme={null}
// Ensure SDK is initialized first
const sdk = getAiChatSdk();

// Show badge
await sdk.showBadge();
```

Check the browser console for errors. The badge may also be hidden if:

* `badgeConfig.allowExpand` is set to `false` and there are no prompts
* Layout position places it off-screen

### Inline input not rendering

**Symptom**: Calling `sdk.showInline()` doesn't show the inline input

**Solution**: Ensure you've configured a valid container selector:

```typescript theme={null}
initializeAiChatSdk('your-api-key', {
  inlineConfig: {
    layout: {
      containerSelector: '#chat-container',  // Must exist in the DOM
    },
  },
  dataProviders: {
    offerRedirectUrlProvider: async (url) => null,
    merchantCashbackProvider: async (urls) => ({}),
  },
});

// Make sure the container exists before calling showInline
const container = document.querySelector('#chat-container');
if (container) {
  await sdk.showInline();
}
```

## Data provider issues

### Providers not being called

**Symptom**: Data providers never execute

**Solution**: Ensure providers are configured correctly:

```typescript theme={null}
dataProviders: {
  offerRedirectUrlProvider: async (url) => {
    console.log('Provider called for:', url);
    // Your implementation
    return 'https://example.com/offer';
  },
  merchantCashbackProvider: async (urls) => {
    console.log('Cashback requested for:', urls);
    // Your implementation
    return {};
  },
}
```

Test by asking merchant-specific questions like "Show me deals on Amazon"

### Provider errors

**Symptom**: SDK stops working after provider throws error

**Solution**: Always handle errors and return valid fallback values:

```typescript theme={null}
const offerRedirectUrlProvider = async (url) => {
  try {
    const response = await fetch(`/api/offers?url=${url}`);
    const data = await response.json();
    return data.offerUrl || null;
  } catch (error) {
    console.error('Provider error:', error);
    return null;  // Always return null on error
  }
};

const merchantCashbackProvider = async (urls) => {
  try {
    const response = await fetch('/api/cashback', {
      method: 'POST',
      body: JSON.stringify({ urls }),
    });
    const data = await response.json();
    return data.cashback || {};
  } catch (error) {
    console.error('Provider error:', error);
    return {};  // Always return {} on error
  }
};
```

### Slow performance

**Symptom**: Chat feels sluggish or freezes

**Solution**: Add timeouts to data providers (recommend 500ms):

```typescript theme={null}
const offerRedirectUrlProvider = async (url) => {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), 500);

  try {
    const response = await fetch(url, { signal: controller.signal });
    clearTimeout(timeout);
    return response.offerUrl;
  } catch (error) {
    clearTimeout(timeout);
    return null;
  }
};
```

## Event issues

### Events not firing

**Symptom**: Event listeners are never called

**Solution**: Ensure listeners are registered during initialization:

```typescript theme={null}
initializeAiChatSdk('your-api-key', {
  // ... config
}, [
  // Event listeners must be passed here
  (event) => {
    console.log('Event:', event.type, event.data);
  }
]);
```

<Warning>
  Event listeners cannot be added after SDK initialization. They must be passed as the third parameter to `initializeAiChatSdk()`.
</Warning>

## Network issues

### API requests failing

**Symptom**: Chat not responding, network errors in console

**Solution**:

<Steps>
  <Step title="Verify API key">
    Ensure your API key is correct and active
  </Step>

  <Step title="Check network">
    Verify you have internet connectivity
  </Step>

  <Step title="Enable debug mode">
    ```typescript theme={null}
    enableDebug: true
    ```

    Check console for detailed error messages
  </Step>

  <Step title="Check browser console">
    Look for 401/403 errors indicating authentication issues
  </Step>
</Steps>

If issues persist, contact [support@onsleek.com](mailto:support@onsleek.com)

## Configuration issues

### Colors not applying

**Symptom**: Custom colors don't appear in the UI

**Solution**: Verify you're using the correct configuration structure:

```typescript theme={null}
chatConfig: {
  styling: {
    primaryColor: '#5C59FE',           // For light mode
    primaryColorDarkMode: '#8B87FF',   // For dark mode
    colorMode: 'system',               // 'light' | 'dark' | 'system'
  },
}
```

### Logo not appearing

**Symptom**: Logo doesn't show in the chat header

**Solution**: Check the `brand` configuration:

```typescript theme={null}
chatConfig: {
  brand: {
    name: 'Your Brand',
    logoUrl: 'https://your-app.com/logo.png',  // Must be a valid, accessible URL
  },
}
```

Common issues:

* URL not accessible (CORS issues)
* Invalid image format
* Image too large to load

## Browser compatibility

The SDK supports modern browsers:

* Chrome 100+
* Firefox 100+
* Safari 15+
* Edge 100+

For best results, ensure users are on the latest browser version.

## Debugging tips

### Enable debug mode

Always start troubleshooting with debug mode enabled:

```typescript theme={null}
initializeAiChatSdk('your-api-key', {
  enableDebug: true,
  // ... other config
});
```

This provides detailed logs in the browser console.

### Check SDK version

Verify you're using the latest version:

```bash theme={null}
pnpm list @sleek/ai-chat-sdk
```

Update if needed:

```bash theme={null}
pnpm update @sleek/ai-chat-sdk
```

### Test in incognito mode

Test in incognito/private browsing to rule out:

* Browser extension interference
* Cached data issues
* Cookie problems

### Check the console

Always check the browser DevTools Console (F12) for:

* Error messages
* Network failures
* SDK debug logs

## Common error messages

### "Invalid API key"

Your API key is incorrect or inactive. Verify your key and ensure it's active.

### "AI Chat SDK not initialized"

You're trying to use `getAiChatSdk()` before calling `initializeAiChatSdk()`. Ensure SDK is initialized first:

```typescript theme={null}
// Initialize first
const sdk = initializeAiChatSdk('your-api-key', { ... });

// Then use it
sdk.initializeChat();

// Or later, retrieve the instance
const sdk = getAiChatSdk();  // Works after initialization
```

### "Data provider error"

1. Ensure providers return correct types (`null` or `{}` on error)
2. Add try-catch blocks to all providers
3. Never throw exceptions from providers

## Getting help

If you're still experiencing issues, contact our support team.

<CardGroup cols={2}>
  <Card title="Email support" icon="envelope" href="mailto:support@onsleek.com">
    Get help from our support team
  </Card>

  <Card title="Documentation" icon="book" href="/ai-chat-js-sdk-reference/introduction">
    Review the full SDK documentation
  </Card>
</CardGroup>

When contacting support, please include:

* SDK version (`pnpm list @sleek/ai-chat-sdk`)
* Browser name and version
* Error messages from console (with `enableDebug: true`)
* Code snippet of your SDK initialization
* Steps to reproduce the issue
