npm package: @kaia-team/kaia-api-js
Description: Official JavaScript SDK for Kaia AI Chat API
Author: Your Name
Latest version: 1.0.0

# Kaia API JavaScript SDK

A comprehensive JavaScript SDK for integrating with the Kaia AI Chat API. This SDK provides a complete solution for building AI-powered chat applications with support for multiple authentication methods, chat management, and session handling.

## Features

- 🤖 **AI Chat Integration** - Seamless integration with Kaia's AI assistants
- 🔐 **Multiple Authentication Methods** - Email/password, Google OAuth, JWT tokens
- 💬 **Advanced Chat Management** - Create, switch, and manage multiple chat sessions
- 🔄 **Real-time Updates** - Event-driven architecture for live UI updates
- 💾 **Session Management** - Automatic session persistence and restoration
- 🎯 **Recommended Content** - Personalized content recommendations primarily designed for conversation starter cards
- 🛠️ **CLI Example** - Command-line interface example for testing and development

## Quick Start

### Installation

```bash
npm install @kaia-team/kaia-api-js
```

### Basic Usage

```typescript
import { KaiaApi } from '@kaia-team/kaia-api-js';

// Initialize the API
const kaiaApi = new KaiaApi({
  host: 'https://api.kaia.team',        // API backend host
  configId: 'your-config-id',
  baseUrl: 'https://kaia.team'          // Frontend host for assets/components
});

// Initialize and start chatting
await kaiaApi.initialize();

// Send a message
const chatManager = kaiaApi.getChatManager();
chatManager.sendMessage({
  key: 'user-msg-1',
  role: 'user',
  content: 'Hello, how can you help me?',
  images: []
});

// Get personalized recommendations (primarily for conversation starter cards)
const apiClient = kaiaApi.getApiClient();
if (apiClient) {
  const recommendations = await apiClient.getRecommendedContent(6);
  console.log('Recommended content:', recommendations);
}
```

## Documentation

- [Getting Started Guide](./docs/GETTING_STARTED.md) - Quick setup and basic integration
- [Authentication Guide](./docs/AUTHENTICATION.md) - User authentication and session management
- [Chat Management Guide](./docs/CHAT_MANAGEMENT.md) - Managing chats and conversations
- [UI Integration Guide](./docs/UI_INTEGRATION.md) - Building chat interfaces
- [CLI Usage Guide](./docs/CLI_GUIDE.md) - Command-line interface usage
- [API Reference](./docs/API_REFERENCE.md) - Complete API documentation
- [Advanced Usage](./docs/ADVANCED_USAGE.md) - Advanced features and customization

## Configuration

### Basic Configuration

```typescript
const config = {
  baseUrl: 'https://api.kaia.team',        // API base URL
  configId: 'your-config-id',              // Your configuration ID
  host: 'https://kaia.team',               // Host domain
  qrcode: true,                            // Enable QR code functionality
  defaultOpen: false                       // Widget opens by default
};
```

### Customer Instance Configuration

For customer-specific instances, use subdomains of `kaia.team`:

```typescript
const config = {
  baseUrl: 'https://api.clients.kaia.team',
  configId: 'client-specific-config',
  host: 'https://clients.kaia.team'
};
```

## Authentication Methods

### 1. Anonymous Chatting
```typescript
// No authentication required - start chatting immediately
await kaiaApi.initialize();
```

### 2. Email/Password Login
```typescript
const userInfo = await kaiaApi.login('user@example.com', 'password123');
```

### 3. Google OAuth
```typescript
const userInfo = await kaiaApi.loginWithGoogle(googleAuthResponse);
```

### 4. JWT Token Authentication
```typescript
await kaiaApi.authenticateUser('your-jwt-token');
```

## Chat Management

### Creating and Managing Chats

```typescript
// Create a new chat
await kaiaApi.createNewChat();

// Switch to existing chat
await kaiaApi.switchChatHistory('chat-ulid');

// Load chat histories
const histories = await kaiaApi.loadHistories();
```

### Sending Messages

```typescript
const chatManager = kaiaApi.getChatManager();

// Send a message
chatManager.sendMessage({
  key: 'user-msg-1',
  role: 'user',
  content: 'Hello, how are you?',
  images: []
});
```

## UI Integration

The SDK provides the data structures and event system needed to build chat interfaces. Message content can be either:

- **Plain text strings** - Simple text messages
- **Structured JSON** - Rich content with blocks (markdown, images, tiles)

The SDK includes TypeScript interfaces for all message types and content blocks. See the [UI Integration Guide](./docs/UI_INTEGRATION.md) for implementation guidance.

## CLI Example

The SDK includes a CLI example for testing and development:

```bash
# Navigate to CLI example
cd examples/cli
npm install
npm start

# Or use the CLI programmatically
import { KaiaCLI } from './examples/cli/src/cli';
const cli = new KaiaCLI();
await cli.start();
```

See the [CLI Usage Guide](./docs/CLI_GUIDE.md) for complete CLI example documentation.

## Event System

The SDK uses an event-driven architecture for real-time updates:

```typescript
// Listen for events
kaiaApi.addEventListener('user_authenticated', (event, data) => {
  console.log('User logged in:', data.userInfo.username);
});

kaiaApi.addEventListener('message_received', (event, data) => {
  console.log('New message:', data.message.content);
});
```

## Backend Requirements

### Required Backend Setup

1. **API Endpoints** - Ensure your backend implements the required Kaia API endpoints
2. **Authentication** - Configure authentication providers (email, Google OAuth, JWT)
3. **Configuration** - Set up your configuration ID and assistant definitions
4. **CORS** - Configure CORS settings for your domain

### Environment Variables

```bash
KAIA_BASE_URL=https://api.kaia.team
KAIA_CONFIG_ID=your-config-id
KAIA_HOST=https://kaia.team
```

## Examples

### React Integration

```typescript
import React, { useEffect, useState } from 'react';
import { KaiaApi, MessageType } from '@kaia-team/kaia-api-js';

function ChatInterface() {
  const [kaiaApi] = useState(() => new KaiaApi(config));
  const [messages, setMessages] = useState<MessageType[]>([]);
  
  useEffect(() => {
    kaiaApi.initialize().then(() => {
      const chatManager = kaiaApi.getChatManager();
      
      // Listen for new messages
      chatManager.addEventListener('message_added', (event, data) => {
        setMessages(prev => [...prev, data.message]);
      });
    });
  }, [kaiaApi]);
  
  const handleSendMessage = (content: string) => {
    const chatManager = kaiaApi.getChatManager();
    chatManager.sendMessage({
      key: `user-${Date.now()}`,
      role: 'user',
      content,
      images: []
    });
  };

  return (
    <div>
      {/* Your chat UI components */}
    </div>
  );
}
```

### Node.js Integration

```typescript
import { KaiaApi } from '@kaia-team/kaia-api-js';

const kaiaApi = new KaiaApi(config);
await kaiaApi.initialize();

// Use in your Node.js application
const chatManager = kaiaApi.getChatManager();
chatManager.sendMessage({
  key: 'node-msg-1',
  role: 'user',
  content: 'Hello from Node.js!',
  images: []
});
```

## TypeScript Support

The SDK is built with TypeScript and provides full type definitions:

```typescript
import { 
  KaiaApi, 
  KaiaApiConfig, 
  MessageType, 
  UserInfo 
} from '@kaia-team/kaia-api-js';
```

## Browser Support

- Chrome 80+
- Firefox 75+
- Safari 13+
- Edge 80+

## Contributing

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

## License

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

## Support

- 📚 [Documentation](./docs/)
- 🐛 [Issue Tracker](https://github.com/kaia-team/kaia-api-js/issues)
- 💬 [Discussions](https://github.com/kaia-team/kaia-api-js/discussions)
- 📧 [Email Support](mailto:support@kaia.team)

## Changelog

See [CHANGELOG.md](./CHANGELOG.md) for version history and updates.