---
title: Basic Usage
url: https://docs.kaltura.com/docs/conversational-agents/agentic-avatars-sdk/client-sdk-basic-usage
---

## Basic Usage

Learn the fundamentals of using the Kaltura Avatar Client SDK to display and control avatars.

### Creating an SDK Instance

First, create a `KalturaAvatarSession` instance:

```javascript
import { KalturaAvatarSession } from '@unisphere/models-sdk-js';

// Recommended: With apiKey in config (SDK creates session)
const session = new KalturaAvatarSession({
  apiKey: 'your-kaltura-session',
  baseUrl: 'https://api.avatar.us.kaltura.ai/',
});

// Recommended: Without apiKey (backend creates session)
const session = new KalturaAvatarSession({
  baseUrl: 'https://api.avatar.us.kaltura.ai/',
});
```

#### Constructor Parameters

```javascript
new KalturaAvatarSession(config?: AvatarConfig)
```

#### Configuration Options

```typescript
interface AvatarConfig {
  apiKey?: string;              // Your Kaltura Session (KS) - only needed if SDK creates the session
  baseUrl?: string;             // Backend API URL (required for non-default endpoints)
  logLevel?: 'debug' | 'info' | 'warn' | 'error';  // Default: 'info'
}
```

> **apiKey in Config**
>
> - **Include it** for FE-only control where the SDK creates sessions
> - **Omit it** for BE/FE split where backend creates sessions (recommended for production)

### Two Usage Patterns

The SDK supports two patterns for displaying avatars:

#### Pattern 1: Auto-Attach (Recommended)

The SDK automatically creates and attaches a video element:

```javascript
await session.createSession({
  visualId: 'visual-123',
  voiceId: 'voice-456',
  videoContainerId: 'avatar-container', // SDK creates video element here
});
```

**HTML:**

```html
<div id="avatar-container" style="width: 512px; height: 512px;"></div>
```

The SDK will:

1. Create a `<video>` element
2. Insert it into `#avatar-container`
3. Set up WebRTC streaming
4. Start playing automatically

#### Pattern 2: Manual Attach

Create the session first, then attach the video manually:

```javascript
// Step 1: Create session
await session.createSession({
  visualId: 'visual-123',
  voiceId: 'voice-456',
});

// Step 2: Manually attach video
session.attachAvatar('avatar-container');
```

**When to use:**

- You need control over when the video appears
- You want to add UI elements before showing the avatar
- You need to perform checks before displaying

### Complete Example: Auto-Attach

```javascript
import { KalturaAvatarSession } from '@unisphere/models-sdk-js';

async function initAvatar() {
  // Create SDK instance
  const session = new KalturaAvatarSession({
    apiKey: 'your-api-key',
    baseUrl: 'https://api.avatar.us.kaltura.ai/',
    logLevel: 'info',
  });

  // Setup event listeners
  session.on('stateChange', (state) => {
    console.log('Session state:', state);
  });

  session.on('error', (error) => {
    console.error('Error:', error.message);
  });

  try {
    // Create session with auto-attach
    await session.createSession({
      visualId: 'visual-123',
      voiceId: 'voice-456',
      videoContainerId: 'avatar-container',
    });

    console.log('Avatar ready! Session ID:', session.getSessionId());

    // Make avatar speak
    await session.sayText('Hello! I am your Kaltura Avatar.');
  } catch (error) {
    console.error('Failed to initialize avatar:', error);
  }
}

// Call when DOM is ready
initAvatar();
```

### Complete Example: Manual Attach

```javascript
import { KalturaAvatarSession } from '@unisphere/models-sdk-js';

async function initAvatar() {
  const session = new KalturaAvatarSession({
    apiKey: 'your-api-key',
    baseUrl: 'https://api.avatar.us.kaltura.ai/',
  });

  try {
    // Step 1: Create session (no video yet)
    await session.createSession({
      visualId: 'visual-123',
      voiceId: 'voice-456',
    });

    console.log('Session created:', session.getSessionId());

    // Step 2: Show loading UI
    document.getElementById('loading').style.display = 'block';

    // Step 3: Attach video when ready
    session.attachAvatar('avatar-container');

    // Step 4: Hide loading UI
    document.getElementById('loading').style.display = 'none';

    // Step 5: Make avatar speak
    await session.sayText('Hello! I am ready.');
  } catch (error) {
    console.error('Failed to initialize avatar:', error);
  }
}

initAvatar();
```

### Making the Avatar Speak

#### Text-to-Speech

```javascript
await session.sayText('Hello, how are you doing today?');
```

> **Multi-Language Support**
>
> When creating a session with a voice, you can specify a `language` to control the TTS language:

```javascript
await session.createSession({
  visualId: 'visual-123',
  voiceId: 'voice-456',
  language: 'es', // Spanish
  videoContainerId: 'avatar-container',
});
```

See [API Reference](./client-sdk-api-reference#tts-languages) for the full list of 33 supported languages.

Text is automatically chunked into 3-word segments for optimal processing:

- Input: `"Hello, how are you doing today?"`
- Chunks: `["Hello, how are", "you doing today"]`

#### Audio File

Audio must be **MP3 at 44.1 kHz**. Provide the duration and a unique `turnId`:

```javascript
const arrayBuffer = await audioBlob.arrayBuffer();
const audioCtx = new AudioContext();
const decoded = await audioCtx.decodeAudioData(arrayBuffer);
await audioCtx.close();

const duration = decoded.duration;
const audioFile = new File([audioBlob], 'speech.mp3', { type: 'audio/mpeg' });
const turnId = `turn-${Date.now()}`;

await session.sayAudio(audioFile, turnId, duration);
```

### Controlling the Avatar

#### Interrupt Speech

Stop the avatar mid-speech:

```javascript
await session.interrupt();
```

#### End Session

Clean up and end the session:

```javascript
await session.endSession();
```

This will:

- Stop keep-alive
- Disconnect WebRTC
- End the backend session
- Clean up all resources

### Keep-Alive

The SDK automatically sends keep-alive signals every 10 seconds once a session is created. This ensures:

- Session remains active
- Backend doesn't terminate the session
- Resources are properly maintained

> **Automatic Management**
>
> You don't need to manage keep-alive manually. It starts automatically when the session is ready and stops when you call `endSession()`.

### Video Element Details

When the SDK creates a video element, it has:

- `autoplay` and `playsinline` attributes
- Width and height set to 100%
- Appropriate styling for fullscreen display within the container

**Generated HTML:**

```html
<div id="avatar-container">
  <video autoplay playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>
</div>
```

### Common Patterns

#### Initialize on Button Click

By using this pattern, you provide a better UX by allowing users to control when the avatar initializes. This is also good for browsers autoplay policies that require user interaction.

```javascript
document.getElementById('start-btn').addEventListener('click', async () => {
  const session = new KalturaAvatarSession({
    apiKey: 'your-api-key',
    baseUrl: 'https://api.avatar.us.kaltura.ai/',
  });

  await session.createSession({
    visualId: 'visual-123',
    videoContainerId: 'avatar-container',
  });

  await session.sayText('Hello! You clicked the start button.');
});
```

### Next Steps

- **[Catalog Service](./client-sdk-catalog)** - Browse available visuals and voices
- **[API Reference](./client-sdk-api-reference)** - Complete method documentation
- **[State Management](./client-sdk-state-management)** - Handle states and events
- **[Error Handling](./client-sdk-error-handling)** - Robust error handling
- **[Examples](./examples-simple-client-side)** - More complete examples
