@onlive.ai/chat
v0.3.54
Published
A comprehensive web components package for real-time chat functionality built with Lit and LiveKit. This package provides a complete chat interface with support for text messaging, voice communication, multimedia sharing, form handling, and conversation m
Downloads
9
Readme
@onlive.ai/chat
A comprehensive web components package for real-time chat functionality built with Lit and LiveKit. This package provides a complete chat interface with support for text messaging, voice communication, multimedia sharing, form handling, and conversation management.
🚀 Features
Core Chat Features
- Real-time messaging with LiveKit integration
- Voice chat support with audio visualization
- Text-based conversations with markdown support
- Message persistence with server/client options
- Message reactions (👍/👎) and reporting
- Conversation evaluation and feedback system
Rich Media Support
- Multimedia sharing (images, videos, documents)
- Media visualizer for viewing shared content
- Audio device selection and management
- Voice amplitude visualization with D3.js
Form Integration
- Interactive forms within chat messages
- Dynamic field validation with @onlive.ai/flow
- Form submission tracking and analytics
- Multi-step form workflows
User Experience
- Message grouping by participant
- Typing indicators and loading states
- Auto-scroll to latest messages
- Link handling with domain restrictions
- Multi-language support with localization
- Custom theming and styling support
Analytics & Tracking
- Event tracking with @onlive.ai/tracker
- User interaction analytics
- Form submission metrics
- Conversation flow analysis
📦 Installation
Using pnpm
pnpm add @onlive.ai/chatUsing npm
npm install @onlive.ai/chatUsing yarn
yarn add @onlive.ai/chat🏗️ Package Structure
packages/chat/
├── components/
│ ├── actions/ # Action buttons and controls
│ ├── audio-device/ # Audio device selection
│ ├── chat/ # Main chat component
│ ├── evaluation/ # Conversation rating
│ ├── media-visualizer/ # Media gallery viewer
│ ├── message/ # Message display component
│ ├── player/ # Media player component
│ ├── send/ # Message input component
│ └── wave/ # Voice amplitude visualization
├── locales/ # Internationalization files
├── theme/ # Base styling and themes
├── translations/ # Language translations
├── index.ts # Main exports
└── package.json # Package configuration🔧 Basic Usage
Simple Text Chat
import '@onlive.ai/chat';
import { LivekitService } from '@onlive.ai/common-121/services/livekit.service.js';
// Create LiveKit service instance
const livekitService = new LivekitService({
baseUrl: 'https://your-livekit-server.com',
organizationId: 'your-org-id'
});
// Initialize chat room
const room = await livekitService.createRoom({
language: 'en',
timezone: 'America/New_York'
});<och-chat
lang="en"
.livekitService="${livekitService}"
.options="${{
agent: {
id: 'agent-123',
type: 'text',
name: 'Assistant',
image: '/path/to/avatar.png'
}
}}"
></och-chat>Voice Chat Configuration
<och-chat
lang="en"
.livekitService="${livekitService}"
.audioService="${audioService}"
.options="${{
agent: {
id: 'voice-agent-456',
type: 'voice',
name: 'Voice Assistant',
image: '/path/to/voice-avatar.png'
}
}}"
></och-chat>With Custom Styling and Tracking
import { Tracker } from '@onlive.ai/tracker';
const tracker = new Tracker({
apiKey: 'your-tracking-key',
endpoint: 'https://analytics.example.com'
});
const customStyles = new CSSStyleSheet();
customStyles.replaceSync(`
.och__chat {
--ol-color-primary: #your-brand-color;
}
`);<och-chat
lang="en"
.livekitService="${livekitService}"
.context="${{
tracker: tracker,
customStyles: customStyles
}}"
.options="${chatOptions}"
></och-chat>📋 Component API
OCHChat (Main Component)
Properties
lang: string- Language code for localizationlivekitService: LivekitService- LiveKit service instanceaudioService?: AudioService- Audio service for voice featuresorganizationId?: string- Organization identifieroptions?: ChatOptions- Chat configuration optionstracking?: TrackingOptions- Analytics configurationcontext: PackageContext- Shared context for styling and tracking
Events
open-link- Fired when a link is clickedorganization-call- Fired when requesting a meetingconversation-ended- Fired when conversation is completedrestart-conversation- Fired when restarting chat
Chat Options
interface ChatOptions {
agent?: {
id: string;
type: 'text' | 'voice';
name: string;
image: string;
};
browser?: {
allowedDomains?: string[];
};
}OCHMessage (Message Display)
Properties
messages: ChatMessage[]- Array of messages to displayfrom?: ChatMessage["from"]- Message sender informationlang: string- Language for localizationloading?: boolean- Show loading state
Events
submit-form- Fired when form is submittedcancel-form- Fired when form is cancelledopen-link- Fired when link is clickedclick-media- Fired when media is clickedreport-message- Fired when message is reported
OCHSend (Message Input)
Properties
disabled?: boolean- Disable the entire componentsendDisabled?: boolean- Disable only send buttoninputDisabled?: boolean- Disable only input fieldlang: string- Language for localization
Events
send- Fired when message is sent
🌍 Internationalization
The package supports multiple languages with built-in localization:
import { configureLocalization } from '@lit/localize';
configureLocalization({
sourceLocale: 'en',
targetLocales: ['es', 'fr', 'de', 'it'],
loadLocale: (locale) => import(`./locales/${locale}.js`)
});Supported languages:
- English (en)
- Spanish (es)
- French (fr)
- German (de)
- Italian (it)
🎨 Styling and Theming
CSS Custom Properties
The components use CSS custom properties for theming:
och-chat {
--ol-color-primary: #0066cc;
--ol-color-neutral-50: #f9fafb;
--ol-color-neutral-800: #1f2937;
--ol-spacing-small: 0.5rem;
--ol-spacing-medium: 1rem;
--ol-spacing-large: 1.5rem;
}Custom Styles
You can provide custom styles through the context:
const customStyleSheet = new CSSStyleSheet();
customStyleSheet.replaceSync(`
.och__chat__messages {
background: linear-gradient(to bottom, #f0f0f0, #ffffff);
}
.och__message {
border-radius: 12px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
`);
const chatContext = {
customStyles: customStyleSheet,
tracker: yourTracker
};📊 Analytics Integration
The package integrates with @onlive.ai/tracker for comprehensive analytics:
Tracked Events
- Element interactions (button clicks, input focus)
- Message sending and receiving
- Form submissions and cancellations
- Link clicks and navigation
- Conversation flow events
- Media interactions
Event Types
interface TrackingEvents {
'element_click': ElementClickData;
'element_interaction': InteractionData;
'form_submit': FormSubmissionData;
'impression': ImpressionData;
}🔌 LiveKit Integration
Room Management
// Create a room
const room = await livekitService.createRoom({
language: 'en',
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
affinity: {
agentId: 'your-agent-id',
agentType: 'text'
}
});
// Subscribe to messages
livekitService.subscribeMessages((messages) => {
console.log('New messages:', messages);
});
// Send a message
await livekitService.sendMessage('Hello, world!');Voice Chat Features
// Enable microphone
await room.localParticipant.setMicrophoneEnabled(true);
// Handle audio tracks
room.on(RoomEvent.TrackSubscribed, (track, publication) => {
if (track.kind === Track.Kind.Audio) {
const audioElement = track.attach();
document.body.appendChild(audioElement);
}
});🛠️ Development
Prerequisites
- Node.js 18+
- pnpm 8+
Setup
# Install dependencies
pnpm install
# Build the package
pnpm run build:package
# Extract localization strings
pnpm run localize:extract
# Build localization files
pnpm run localize:buildTesting
# Run in development mode
pnpm run dev
# Build for production
pnpm run build
# Clean build artifacts
pnpm run clean📝 Distribution Formats
The package is distributed in multiple formats:
- ES Modules (
index.js) - Modern bundlers - CommonJS (
index.cjs) - Node.js compatibility - TypeScript Definitions (
index.d.ts) - Type support
🔗 Dependencies
Core Dependencies
@lit/context- Component context management@lit/localize- Internationalization support@livekit/components-core- LiveKit integration@onlive.ai/flow- Form component integration@onlive.ai/ui- UI component library@onlive.ai/common-121- Shared utilities@onlive.ai/tracker- Analytics tracking
Visualization Dependencies
d3- Data visualization libraryd3-shape- Shape generation for audio visualization
Utility Dependencies
mime- File type detectiontimeago.js- Relative time formatting
🤝 Integration Examples
With React
import '@onlive.ai/chat';
import { useRef, useEffect } from 'react';
function ChatComponent() {
const chatRef = useRef(null);
useEffect(() => {
if (chatRef.current) {
chatRef.current.livekitService = livekitService;
chatRef.current.options = chatOptions;
}
}, []);
return (
<och-chat
ref={chatRef}
lang="en"
/>
);
}With Angular
import '@onlive.ai/chat';
@Component({
template: `
<och-chat
[lang]="language"
[livekitService]="livekitService"
[options]="chatOptions"
(conversation-ended)="onConversationEnded($event)"
></och-chat>
`
})
export class ChatComponent {
language = 'en';
livekitService = new LivekitService(config);
chatOptions = { /* your options */ };
onConversationEnded(event: CustomEvent) {
console.log('Conversation ended:', event.detail);
}
}With Vue.js
<template>
<och-chat
:lang="language"
:livekitService="livekitService"
:options="chatOptions"
@conversation-ended="onConversationEnded"
/>
</template>
<script>
import '@onlive.ai/chat';
export default {
data() {
return {
language: 'en',
livekitService: new LivekitService(config),
chatOptions: { /* your options */ }
};
},
methods: {
onConversationEnded(event) {
console.log('Conversation ended:', event.detail);
}
}
};
</script>📱 Browser Compatibility
- Chrome/Edge 88+
- Firefox 78+
- Safari 14+
- Mobile browsers with ES2020 support
📄 License
This package is part of the Onlive 121 ecosystem and follows the project's licensing terms.
