npm package: @servexai/sdk
Description: Servex AI SDK - Embed AI chat widgets on any website with React, Vue, WordPress, and vanilla JavaScript support
Author: Servex AI
Latest version: 1.0.31

# 🚀 ServexUI

Embed AI-powered chat widgets on any website with just a few lines of code. Built for developers and businesses who want to integrate intelligent customer support seamlessly.

## ✨ Features

- **Universal Compatibility**: Works with vanilla JavaScript, React, Vue.js, WordPress, and more
- **API Key Authentication**: Secure access using your Servex AI API keys
- **Customizable UI**: Position, theme, and styling options
- **Auto-popup**: Configurable delay before showing the chat widget
- **Event System**: Listen to chat events and integrate with your analytics
- **TypeScript Support**: Full TypeScript definitions included
- **Lightweight**: Minimal bundle size with tree-shaking support

## 📦 Installation

### CDN (Recommended for quick setup)

```html
<script
  src="https://cdn.jsdelivr.net/npm/@servexai/sdk@latest/dist/index.js"
  data-servex-api-key="your-api-key-here"
  data-servex-agent-id="your-agent-id" <!-- Required for auto-initialization -->
  data-servex-customer-name="John Doe"
  data-servex-customer-id="12345"
  data-servex-position="bottom-right"
  data-servex-auto-show-delay="3000"
></script>
```

### NPM/Yarn

```bash
npm install @servexai/sdk
# or
yarn add @servexai/sdk
```

## 🚀 Quick Start

### Vanilla JavaScript

```html
<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/@servexai/sdk@latest/dist/index.js"></script>
  </head>
  <body>
    <script>
      // Initialize the chat widget
      const chatWidget = window.ServexUI.init({
        apiKey: 'your-api-key-here',
        agentId: 'your-agent-id', // Required
        customerName: 'John Doe',
        customerId: '12345',
        position: 'bottom-right',
        autoShowDelay: 3000,
      });

      // Listen for events
      chatWidget.on('ready', () => {
        console.log('Chat widget is ready!');
      });

      chatWidget.on('message', (message) => {
        console.log('New message:', message);
      });

      // Control the widget
      chatWidget.show();
      chatWidget.hide();
      chatWidget.toggle();
    </script>
  </body>
</html>
```

### React

```tsx
import React from 'react';
import { ServexUIProvider, ServexUIChat, useServexUI } from '@servexai/sdk/react';

function App() {
  return (
    <ServexUIProvider
      config={{
        apiKey: 'your-api-key-here',
        agentId: 'your-agent-id', // Required
        customerName: 'John Doe',
        customerId: '12345',
      }}
    >
      <div className="app">
        {/* Your app content */}
        <ServexUIChat
          config={{
            position: 'bottom-right',
            autoShowDelay: 3000,
          }}
        />
      </div>
    </ServexUIProvider>
  );
}

// Or use the hook directly
function MyComponent() {
  const plugics = useServexUI({
    apiKey: 'your-api-key-here',
    agentId: 'your-agent-id', // Required
  });

  const handleSendMessage = async () => {
    if (plugics) {
      const response = await plugics.sendMessage('Hello!');
      console.log('AI Response:', response);
    }
  };

  return <button onClick={handleSendMessage}>Send Message</button>;
}
```

### WordPress

1. Download and install the `plugics-chat.php` plugin
2. Go to **Settings > ServexUI Chat** in your WordPress admin
3. Enter your API key and configure options
4. The chat widget will automatically appear on your site

Or use the shortcode in any post/page:

```php
[plugics_chat agent_id="your-agent-id"]
```

## ⚙️ Configuration Options

| Option          | Type                                                           | Default               | Description                                              |
| --------------- | -------------------------------------------------------------- | --------------------- | -------------------------------------------------------- |
| `apiKey`        | `string`                                                       | **Required**          | Your API key from Servex AI                              |
| `agentId`       | `string`                                                       | **Required**          | Agent ID to chat with                                    |
| `projectId`     | `string`                                                       | `undefined`           | Project ID for the agent                                 |
| `customerName`  | `string`                                                       | `undefined`           | Name of the customer                                     |
| `customerId`    | `string`                                                       | `undefined`           | Unique identifier for the customer                       |
| `baseUrl`       | `string`                                                       | `'https://servex.so'` | Base URL for the chat service                            |
| `position`      | `'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left'` | `'bottom-right'`      | Position of the chat widget                              |
| `theme`         | `'light' \| 'dark' \| 'auto'`                                  | `'auto'`              | Theme for the chat widget                                |
| `autoShowDelay` | `number`                                                       | `3000`                | Delay in milliseconds before auto-showing (0 = disabled) |
| `customStyles`  | `Record<string, any>`                                          | `{}`                  | Custom CSS styles to apply                               |

> **Note**: The SDK now uses the `/api/v1/dev/` prefix for all API endpoints for better organization and consistency. For real-time streaming responses, use the `/api/v1/dev/chat/message/stream` endpoint.

## 🎯 API Reference

### SDK Methods

```typescript
interface ServexUIInstance {
  // UI Control
  show(): void;
  hide(): void;
  toggle(): void;
  destroy(): void;

  // Chat
  sendMessage(message: string): Promise<ChatResponse>;
  chatWithAgent(agentId: string, message: string, conversationId?: string): Promise<ChatResponse>;

  // Data Methods
  getConversations(): Promise<Conversation[]>;
  getConversation(conversationId: string): Promise<Conversation & { messages: ChatMessage[] }>;
  getAgent(agentId: string): Promise<Agent>;
  setParams(params: ChatParams): void;

  // Events
  on(event: string, callback: Function): void;
  off(event: string, callback: Function): void;
}
```

### New Methods

#### `chatWithAgent(agentId, message, conversationId?)`

Chat directly with a specific agent without using the UI widget.

```javascript
const response = await chatWidget.chatWithAgent('agent_123', 'Hello!', 'conv_456');
console.log(response.response); // AI response text
console.log(response.conversationId); // Conversation ID used
```

**Parameters:**

- `agentId` (string): The ID of the agent to chat with
- `message` (string): The message to send to the agent
- `conversationId` (string, optional): Existing conversation ID to continue, or undefined for new conversation

**Returns:** `Promise<ChatResponse>` - Contains response, conversation ID, and metadata

#### `getConversations()`

Get all conversations for the current user/customer.

```javascript
const conversations = await chatWidget.getConversations();
console.log(conversations);
// [{ id: 'conv_1', agent_id: 'agent_1', customer_name: 'John', ... }]
```

#### `getConversation(conversationId)`

Get a specific conversation with all messages.

```javascript
const conversation = await chatWidget.getConversation('conv_123');
console.log(conversation.messages);
// Array of chat messages
```

#### `getAgent(agentId)`

Get information about a specific agent.

```javascript
const agent = await chatWidget.getAgent('agent_123');
console.log(agent.name, agent.status);
// "Customer Support Agent", "running"
```

#### `setParams(params)`

Update chat parameters dynamically.

```typescript
chatWidget.setParams({
  customerName: 'Jane Doe',
  customerId: 'user_456',
  agentId: 'agent_789',
});
```

### Events

| Event            | Description                     | Data                    |
| ---------------- | ------------------------------- | ----------------------- |
| `ready`          | Widget is initialized and ready | `{ agentName: string }` |
| `show`           | Widget becomes visible          | `undefined`             |
| `hide`           | Widget becomes hidden           | `undefined`             |
| `message`        | New message received            | `ChatMessage`           |
| `error`          | An error occurred               | `ServexUIError`         |
| `params_updated` | Parameters were updated         | `ChatParams`            |
| `destroy`        | Widget is destroyed             | `undefined`             |

### Types

```typescript
interface ServexConfig {
  apiKey: string; // Required - Your API key from Servex AI
  agentId: string; // Required - Agent ID to chat with
  projectId?: string; // Optional - Project ID for the agent
  customerName?: string; // Optional - Name of the customer
  customerId?: string; // Optional - Unique identifier for the customer
  baseUrl?: string; // Optional - Base URL (default: 'https://servex.so')
  theme?: 'light' | 'dark' | 'auto'; // Optional - Theme
  position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'; // Optional - Position
  autoShowDelay?: number; // Optional - Auto-show delay in milliseconds
  customStyles?: Record<string, any>; // Optional - Custom CSS styles
}

interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: Date;
}

interface ChatResponse {
  response: string;
  conversationId: string;
  table?: any;
  cards?: any[];
}
```

## 🔧 Framework Integrations

### Vue.js

```vue
<template>
  <ServexUIChat :config="chatConfig" @ready="onChatReady" @message="onMessage" />
</template>

<script>
import { ServexUIChat } from '@servexai/sdk/vue';

export default {
  components: { ServexUIChat },
  data() {
    return {
      chatConfig: {
        apiKey: 'your-api-key',
        agentId: 'your-agent',
        customerName: 'Vue User',
      },
    };
  },
  methods: {
    onChatReady() {
      console.log('Vue chat ready!');
    },
    onMessage(message) {
      console.log('New message:', message);
    },
  },
};
</script>
```

Or use the composable:

````javascript
import { useServexUI } from '@servexai/sdk/vue';

export default {
  setup() {
    const { widget, init, sendMessage } = useServexUI();

    const startChat = () => {
      init({
        apiKey: 'your-api-key',
        agentId: 'your-agent'
      });
    };

    return { startChat, sendMessage };
  }
};


### Webflow

Add this script to your Webflow site's **Site Settings > Custom Code**:

```html
<script src="https://cdn.jsdelivr.net/npm/@servexai/sdk@latest/dist/index.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
  const chatWidget = window.ServexUIWebflow.init({
    apiKey: 'your-api-key-here',
    agentId: 'your-agent-id',
    customerName: 'Webflow User',
    position: 'bottom-right'
  });
});
</script>
````

Or use data attributes:

```html
<script
  src="https://cdn.jsdelivr.net/npm/@servexai/sdk@latest/dist/index.js"
  data-plugics-api-key="your-api-key"
  data-plugics-agent-id="your-agent"
  data-plugics-position="bottom-right"
></script>
```

### Framer

```tsx
import { ServexUIFramer } from '@servexai/sdk/framer';

export function ChatWidget() {
  return (
    <ServexUIFramer
      apiKey="your-api-key-here"
      agentId="your-agent-id"
      customerName="Framer User"
      position="bottom-right"
    />
  );
}
```

### Svelte

```svelte
<script>
  import { ServexUICore } from '@servexai/sdk/core';

  let chatWidget;

  function initChat() {
    chatWidget = new ServexUICore({
      apiKey: 'your-api-key',
      agentId: 'your-agent',
      customerName: 'Svelte User'
    });
  }

  function sendMessage() {
    chatWidget?.sendMessage('Hello!');
  }
</script>

<button on:click={initChat}>Start Chat</button>
<button on:click={sendMessage}>Send Message</button>
```

}
};
</script>

````

### Svelte

```svelte
<script>
  import { onMount } from 'svelte';
  import { ServexUI } from '@servexai/sdk';

  let chatWidget;

  onMount(() => {
    chatWidget = ServexUI.init({
      apiKey: 'your-api-key',
      // ... other config
    });

    return () => {
      if (chatWidget) {
        chatWidget.destroy();
      }
    };
  });
</script>

<main>
  <!-- Your app content -->
</main>
````

### Framer

1. Create a new Framer component
2. Add the ServexUI script to your project's custom code
3. Use the React integration in your component

### Webflow

1. Go to your Webflow project settings
2. Add the ServexUI script to the custom code section
3. Use data attributes to configure the widget

## 🔐 Authentication

ServexUI uses API key authentication for all external requests. API keys are tied to specific projects and include permissions.

### Creating API Keys

API keys can be created through the servex dashboard:

1. Go to **Project Settings > API Keys**
2. Click **"Create API Key"**
3. Set permissions (`read`, `write`, `admin`)
4. Copy the generated key (shown only once)

### API Key Permissions

- **`read`**: View conversations, agents, and project data
- **`write`**: Send messages and create conversations
- **`admin`**: Full access including agent management

### Authentication Headers

All SDK API calls automatically include the Authorization header:

```javascript
// Automatic header added by SDK
Authorization: Bearer your-api-key-here
```

### Validation Flow

1. **API Key Validation**: Key is validated against database
2. **Project Access**: Ensures key belongs to accessible project
3. **Permissions Check**: Verifies required permissions for operation
4. **Rate Limiting**: Optional rate limiting per key
5. **Usage Tracking**: Updates `last_used_at` timestamp

## 📊 Analytics & Events

Track user interactions and integrate with your analytics platform:

```javascript
chatWidget.on('message', (message) => {
  // Track in your analytics platform
  analytics.track('Chat Message', {
    messageLength: message.content.length,
    messageType: message.role,
  });
});

chatWidget.on('show', () => {
  analytics.track('Chat Widget Opened');
});
```

## 🐛 Troubleshooting

### Widget doesn't appear

- Check that your API key is valid
- Verify the `autoShowDelay` setting
- Check browser console for errors

### Messages not sending

- Ensure the API key has proper permissions
- Check network connectivity
- Verify agent ID is correct

### Styling issues

- Use `customStyles` to override default styles
- Check for CSS conflicts with your site

## 📝 License

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

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## 📞 Support

- 📧 Email: support@servex.ai
- 💬 Chat: Use the widget on our website!
- 📖 Docs: [https://docs.servex.ai](https://docs.servex.ai)

---

Built with ❤️ by the Servex AI team