npm package: @lfaler/ai-chat-assist
Description: AI-powered chat support bot SDK for websites - embed intelligent customer support in minutes
Latest version: 1.0.0

# AI Chat Assist

> AI-powered chat support bot SDK for websites - embed intelligent customer support in minutes

![Version](https://img.shields.io/npm/v/ai-chat-assist)
![License](https://img.shields.io/npm/l/ai-chat-assist)
![Size](https://img.shields.io/bundlephobia/minzip/ai-chat-assist)

## Features

- **Easy Integration** - Add AI-powered chat to any website with just a few lines of code
- **Smart & Helpful** - Powered by advanced AI models (OpenAI, Anthropic Claude, or custom endpoints)
- **Beautiful UI** - Modern, responsive chat interface that works on all devices
- **Customizable** - Full control over colors, position, messages, and behavior
- **Framework Agnostic** - Works with vanilla JS, React, Vue, Angular, and more
- **Persistent Conversations** - Messages are saved across sessions
- **Quick Replies** - Suggest common questions to help users get started
- **TypeScript Support** - Fully typed for better developer experience

## Demo & Documentation

**Interactive Documentation Server:**
```bash
cd server && npm install && npm start
# Then open http://localhost:3000
```

The server provides:
- 📚 **Complete Documentation** - Searchable, interactive docs
- 💻 **Code Examples** - For React, Vue, Angular, and vanilla JS
- 🔒 **Security Guide** - Best practices and deployment guides
- 🎯 **Live Demo** - Try the chat widget with secure backend
- 📖 **API Reference** - Full API documentation

Try it live: [Demo Page](https://yourdomain.com/demo)

## Installation

### NPM

```bash
npm install ai-chat-assist
```

### Yarn

```bash
yarn add ai-chat-assist
```

### CDN

```html
<script src="https://unpkg.com/ai-chat-assist/dist/ai-chat-assist.js"></script>
```

## Quick Start

### HTML + CDN

```html
<!DOCTYPE html>
<html>
<head>
  <title>My Website</title>
</head>
<body>
  <!-- Your website content -->

  <script src="https://unpkg.com/ai-chat-assist/dist/ai-chat-assist.js"></script>
  <script>
    AIChatAssist.init({
      apiKey: 'your-openai-api-key',
      botName: 'Support Assistant',
      welcomeMessage: 'Hi! How can I help you today?'
    });
  </script>
</body>
</html>
```

### JavaScript / TypeScript

```typescript
import { initChatAssist } from 'ai-chat-assist';

const chat = initChatAssist({
  apiKey: 'your-openai-api-key',
  botName: 'Support Bot',
  primaryColor: '#667eea',
  welcomeMessage: 'Hello! I\'m here to help with any questions.'
});
```

### React

```tsx
import React, { useEffect, useRef } from 'react';
import { initChatAssist, ChatWidget } from 'ai-chat-assist';

function App() {
  const chatRef = useRef<ChatWidget | null>(null);

  useEffect(() => {
    chatRef.current = initChatAssist({
      apiKey: process.env.REACT_APP_OPENAI_API_KEY,
      botName: 'Support Bot',
      primaryColor: '#61dafb'
    });

    return () => chatRef.current?.destroy();
  }, []);

  return <div>Your app content</div>;
}
```

## Configuration

### Required Options

| Option | Type | Description |
|--------|------|-------------|
| `apiKey` | `string` | Your API key for the AI service (OpenAI, Anthropic, etc.) |

### Optional Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiEndpoint` | `string` | `'https://api.openai.com/v1/chat/completions'` | API endpoint for chat completions |
| `model` | `string` | `'gpt-3.5-turbo'` | AI model to use |
| `position` | `'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left'` | `'bottom-right'` | Widget position |
| `primaryColor` | `string` | `'#667eea'` | Primary theme color |
| `secondaryColor` | `string` | `'#764ba2'` | Secondary theme color |
| `botName` | `string` | `'Support Assistant'` | Name shown in chat header |
| `botAvatar` | `string` | `'🤖'` | Bot avatar (emoji or text) |
| `userAvatar` | `string` | `'👤'` | User avatar (emoji or text) |
| `welcomeMessage` | `string` | Pre-defined message | First message shown to users |
| `inputPlaceholder` | `string` | `'Type your message...'` | Placeholder for input field |
| `systemPrompt` | `string` | Technical support prompt | Instructions for the AI assistant |
| `quickReplies` | `string[]` | Pre-defined replies | Quick reply suggestions |
| `maxMessageHistory` | `number` | `50` | Maximum messages to keep |
| `persistMessages` | `boolean` | `true` | Save messages to localStorage |
| `customStyles` | `string` | `''` | Custom CSS styles |
| `customHeaders` | `Record<string, string>` | `{}` | Custom headers for API requests |

### Event Callbacks

| Callback | Parameters | Description |
|----------|------------|-------------|
| `onOpen` | `() => void` | Called when chat is opened |
| `onClose` | `() => void` | Called when chat is closed |
| `onMessageSent` | `(message: string) => void` | Called when user sends a message |
| `onMessageReceived` | `(message: string) => void` | Called when AI responds |
| `onError` | `(error: Error) => void` | Called when an error occurs |

## Advanced Usage

### Custom System Prompt

```typescript
initChatAssist({
  apiKey: 'your-api-key',
  systemPrompt: `You are a specialized support assistant for a SaaS platform.
    - Help users with account issues
    - Guide them through features
    - Escalate complex issues to human support
    - Always be professional and empathetic`
});
```

### Using with Anthropic Claude

```typescript
initChatAssist({
  apiKey: 'your-anthropic-api-key',
  apiEndpoint: 'https://api.anthropic.com/v1/messages',
  model: 'claude-3-sonnet-20240229',
  customHeaders: {
    'anthropic-version': '2023-06-01'
  }
});
```

### Custom Styling

```typescript
initChatAssist({
  apiKey: 'your-api-key',
  primaryColor: '#FF6B6B',
  secondaryColor: '#4ECDC4',
  customStyles: `
    .ai-chat-container {
      border-radius: 8px;
    }
    .ai-chat-message-bubble {
      font-size: 15px;
    }
  `
});
```

### Programmatic Control

```typescript
const chat = initChatAssist({ apiKey: 'your-api-key' });

// Open chat programmatically
chat.open();

// Close chat
chat.close();

// Send a message
chat.sendCustomMessage('Hello, I need help!');

// Clear chat history
chat.clearHistory();

// Remove widget completely
chat.destroy();
```

### Event Tracking

```typescript
initChatAssist({
  apiKey: 'your-api-key',
  onMessageSent: (message) => {
    // Track with analytics
    analytics.track('Chat Message Sent', { message });
  },
  onMessageReceived: (response) => {
    // Track AI responses
    analytics.track('Chat Response Received', { response });
  },
  onError: (error) => {
    // Send to error tracking
    Sentry.captureException(error);
  }
});
```

## API Providers

### OpenAI (Default)

```typescript
initChatAssist({
  apiKey: 'sk-...',
  model: 'gpt-4' // or 'gpt-3.5-turbo'
});
```

Get your API key: [OpenAI Platform](https://platform.openai.com/api-keys)

### Anthropic Claude

```typescript
initChatAssist({
  apiKey: 'sk-ant-...',
  apiEndpoint: 'https://api.anthropic.com/v1/messages',
  model: 'claude-3-sonnet-20240229',
  customHeaders: {
    'anthropic-version': '2023-06-01'
  }
});
```

Get your API key: [Anthropic Console](https://console.anthropic.com/)

### Azure OpenAI

```typescript
initChatAssist({
  apiKey: 'your-azure-key',
  apiEndpoint: 'https://your-resource.openai.azure.com/openai/deployments/your-deployment/chat/completions?api-version=2023-05-15',
  customHeaders: {
    'api-key': 'your-azure-key'
  }
});
```

### Custom / Self-Hosted

Any OpenAI-compatible API endpoint works:

```typescript
initChatAssist({
  apiKey: 'your-key',
  apiEndpoint: 'https://your-domain.com/v1/chat/completions',
  model: 'your-model'
});
```

## Examples

Check out the [examples](./examples) directory for complete working examples:

- [Basic HTML](./examples/basic.html) - Simple integration with CDN
- [React](./examples/react-example.tsx) - React component wrapper
- More examples coming soon!

## TypeScript

Full TypeScript support with detailed type definitions:

```typescript
import { AIChatConfig, ChatWidget, Message } from 'ai-chat-assist';

const config: AIChatConfig = {
  apiKey: 'your-key',
  botName: 'Assistant'
};

const chat: ChatWidget = initChatAssist(config);
```

## Browser Support

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
- Mobile browsers (iOS Safari, Chrome Mobile)

## Best Practices

### Security

- **Never expose API keys in client-side code for production**
- Use a backend proxy to handle API requests
- Implement rate limiting to prevent abuse
- Validate and sanitize user input

Example backend proxy (Node.js/Express):

```javascript
app.post('/api/chat', async (req, res) => {
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(req.body)
  });

  const data = await response.json();
  res.json(data);
});
```

Then configure the SDK to use your proxy:

```typescript
initChatAssist({
  apiKey: 'not-needed-with-proxy',
  apiEndpoint: '/api/chat'
});
```

### Performance

- The widget is lazy-loaded and doesn't impact initial page load
- Messages are efficiently stored in localStorage
- CSS is inlined to prevent FOUC (Flash of Unstyled Content)

### User Experience

- Set a clear, helpful welcome message
- Provide relevant quick replies for common questions
- Customize the system prompt for your specific use case
- Use appropriate colors that match your brand

## Troubleshooting

### Chat widget not appearing

- Check browser console for errors
- Verify the script is loaded: `console.log(window.AIChatAssist)`
- Ensure `apiKey` is provided

### API errors

- Verify your API key is correct
- Check API endpoint URL
- Review network tab for request/response details
- Ensure you have sufficient API credits

### Messages not persisting

- Check if `persistMessages` is set to `true`
- Verify localStorage is available in the browser
- Check browser privacy settings

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

MIT License - see [LICENSE](LICENSE) file for details

## Support

- Documentation: [docs.example.com](https://docs.example.com)
- Issues: [GitHub Issues](https://github.com/yourusername/ai-chat-assist/issues)
- Email: support@example.com

## Roadmap

- [ ] Voice input support
- [ ] File upload capability
- [ ] Multi-language support
- [ ] Analytics dashboard
- [ ] More AI provider integrations
- [ ] Conversation export
- [ ] Admin panel for managing conversations

## Credits

Built with:
- TypeScript
- Rollup
- Modern CSS

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for version history.

---

Made with ❤️ by the AI Chat Assist Team