@trillet-ai/web-sdk 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Trillet AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # Trillet AI Web SDK
2
+
3
+ Official Web SDK for integrating Trillet AI voice agents into your web applications. This SDK enables real-time voice communication with Trillet AI agents in your web applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @trillet-ai/webcalls-sdk
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { TrilletAgent } from '@trillet-ai/webcalls-sdk';
15
+
16
+ const agent = new TrilletAgent({
17
+ apiKey: 'your-api-key'
18
+ });
19
+
20
+ // Start a call
21
+ await agent.startCall();
22
+
23
+ // End the call
24
+ await agent.endCall();
25
+ ```
26
+
27
+ ## Documentation
28
+
29
+ For detailed documentation and integration examples, visit:
30
+ - [API Documentation](https://docs.trillet.ai/sdk)
31
+ - [Example Repository](https://github.com/trillet-ai/webcalls-examples)
32
+
33
+ ## License
34
+
35
+ MIT License - see LICENSE file for details
@@ -0,0 +1,2 @@
1
+ declare function App(): any;
2
+ export default App;
@@ -0,0 +1,9 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { TrilletAgent } from './TrilletAgent';
3
+ function App() {
4
+ return (_jsxs("div", { children: [_jsx("h1", { children: "My Website" }), _jsx(TrilletAgent, { workspaceId: "your_workspace_id", apiKey: "your_api_key", agentId: "your_agent_id", variables: {
5
+ customerName: "John Doe",
6
+ context: "Website Visit"
7
+ }, onStatusChange: (status) => console.log('Agent status:', status), onError: (error) => console.error('Agent error:', error) })] }));
8
+ }
9
+ export default App;
@@ -0,0 +1,11 @@
1
+ import React from 'react';
2
+ interface TrilletAgentProps {
3
+ workspaceId: string;
4
+ apiKey: string;
5
+ agentId: string;
6
+ variables?: Record<string, any>;
7
+ onStatusChange?: (status: string) => void;
8
+ onError?: (error: Error) => void;
9
+ }
10
+ export declare const TrilletAgent: React.FC<TrilletAgentProps>;
11
+ export {};
@@ -0,0 +1,77 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useEffect, useRef, useState } from 'react';
3
+ import { TrilletWebSDK } from '@trillet/web-sdk';
4
+ export const TrilletAgent = ({ workspaceId, apiKey, agentId, variables = {}, onStatusChange, onError, }) => {
5
+ const [isConnected, setIsConnected] = useState(false);
6
+ const [isMuted, setIsMuted] = useState(false);
7
+ const sdkRef = useRef();
8
+ useEffect(() => {
9
+ sdkRef.current = new TrilletWebSDK();
10
+ setupEventListeners();
11
+ return () => {
12
+ var _a;
13
+ (_a = sdkRef.current) === null || _a === void 0 ? void 0 : _a.endCall();
14
+ };
15
+ }, []);
16
+ const setupEventListeners = () => {
17
+ if (!sdkRef.current)
18
+ return;
19
+ sdkRef.current.on('connected', () => {
20
+ setIsConnected(true);
21
+ onStatusChange === null || onStatusChange === void 0 ? void 0 : onStatusChange('connected');
22
+ });
23
+ sdkRef.current.on('disconnected', () => {
24
+ setIsConnected(false);
25
+ onStatusChange === null || onStatusChange === void 0 ? void 0 : onStatusChange('disconnected');
26
+ });
27
+ sdkRef.current.on('error', (error) => {
28
+ onError === null || onError === void 0 ? void 0 : onError(error);
29
+ });
30
+ };
31
+ const startConversation = async () => {
32
+ var _a, _b;
33
+ try {
34
+ const response = await fetch('https://api.trillet.ai/v1/api/web-call', {
35
+ method: 'POST',
36
+ headers: {
37
+ 'Content-Type': 'application/json',
38
+ 'Accept': 'application/json',
39
+ 'x-workspace-id': workspaceId,
40
+ 'x-api-key': apiKey
41
+ },
42
+ body: JSON.stringify({
43
+ call_agent_id: agentId,
44
+ dynamic_variables: variables
45
+ })
46
+ });
47
+ if (!response.ok) {
48
+ throw new Error('Failed to initialize conversation');
49
+ }
50
+ const data = await response.json();
51
+ await ((_a = sdkRef.current) === null || _a === void 0 ? void 0 : _a.initializeCall({
52
+ token: data.token,
53
+ audioSettings: {
54
+ sampleRate: 48000
55
+ },
56
+ features: {
57
+ enableRawAudio: true
58
+ }
59
+ }));
60
+ await ((_b = sdkRef.current) === null || _b === void 0 ? void 0 : _b.enableAudioPlayback());
61
+ }
62
+ catch (error) {
63
+ onError === null || onError === void 0 ? void 0 : onError(error);
64
+ }
65
+ };
66
+ const toggleMute = () => {
67
+ if (!sdkRef.current)
68
+ return;
69
+ setIsMuted(!isMuted);
70
+ sdkRef.current.toggleMicrophone(!isMuted);
71
+ };
72
+ const endConversation = () => {
73
+ var _a;
74
+ (_a = sdkRef.current) === null || _a === void 0 ? void 0 : _a.endCall();
75
+ };
76
+ return (_jsxs("div", { className: "trillet-controls", children: [_jsxs("div", { className: "status", children: [_jsx("span", { className: `status-indicator ${isConnected ? 'active' : ''}` }), _jsx("span", { children: isConnected ? 'Connected' : 'Disconnected' })] }), _jsx("button", { onClick: startConversation, disabled: isConnected, children: "Start Conversation" }), _jsx("button", { onClick: endConversation, disabled: !isConnected, children: "End Conversation" }), _jsx("button", { onClick: toggleMute, disabled: !isConnected, children: isMuted ? 'Unmute' : 'Mute' })] }));
77
+ };
@@ -0,0 +1,31 @@
1
+ import { EventEmitter } from "eventemitter3";
2
+ export interface TrilletCallConfig {
3
+ token: string;
4
+ audioSettings?: {
5
+ sampleRate?: number;
6
+ inputDeviceId?: string;
7
+ outputDeviceId?: string;
8
+ };
9
+ features?: {
10
+ enableRawAudio?: boolean;
11
+ };
12
+ }
13
+ export declare class TrilletWebSDK extends EventEmitter {
14
+ private room;
15
+ private isConnected;
16
+ isAssistantSpeaking: boolean;
17
+ audioAnalyzer?: {
18
+ calculateVolume: () => number;
19
+ analyser: AnalyserNode;
20
+ cleanup: () => Promise<void>;
21
+ };
22
+ private audioFrameCapture;
23
+ constructor();
24
+ initializeCall(config: TrilletCallConfig): Promise<void>;
25
+ enableAudioPlayback(): Promise<void>;
26
+ endCall(): void;
27
+ toggleMicrophone(enabled: boolean): void;
28
+ private captureAudio;
29
+ private setupEventHandlers;
30
+ private handleDataEvent;
31
+ }
package/dist/index.js ADDED
@@ -0,0 +1,139 @@
1
+ import { EventEmitter } from "eventemitter3";
2
+ import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser, } from "livekit-client";
3
+ const TRILLET_WS_URL = "wss://trillet-ai-xdx0dw5r.livekit.cloud";
4
+ const decoder = new TextDecoder();
5
+ export class TrilletWebSDK extends EventEmitter {
6
+ constructor() {
7
+ super();
8
+ this.isConnected = false;
9
+ // Audio state tracking
10
+ this.isAssistantSpeaking = false;
11
+ }
12
+ async initializeCall(config) {
13
+ var _a, _b, _c;
14
+ try {
15
+ this.room = new Room({
16
+ audioCaptureDefaults: {
17
+ autoGainControl: true,
18
+ echoCancellation: true,
19
+ noiseSuppression: true,
20
+ channelCount: 1,
21
+ deviceId: (_a = config.audioSettings) === null || _a === void 0 ? void 0 : _a.inputDeviceId,
22
+ sampleRate: (_b = config.audioSettings) === null || _b === void 0 ? void 0 : _b.sampleRate,
23
+ },
24
+ audioOutput: {
25
+ deviceId: (_c = config.audioSettings) === null || _c === void 0 ? void 0 : _c.outputDeviceId,
26
+ },
27
+ });
28
+ this.setupEventHandlers(config);
29
+ await this.room.connect(TRILLET_WS_URL, config.token);
30
+ console.log("Connected to Trillet room:", this.room.name);
31
+ this.room.localParticipant.setMicrophoneEnabled(true);
32
+ this.isConnected = true;
33
+ this.emit("connected");
34
+ }
35
+ catch (error) {
36
+ this.emit("error", "Failed to initialize call");
37
+ console.error("Call initialization failed:", error);
38
+ this.endCall();
39
+ }
40
+ }
41
+ async enableAudioPlayback() {
42
+ var _a;
43
+ await ((_a = this.room) === null || _a === void 0 ? void 0 : _a.startAudio());
44
+ }
45
+ endCall() {
46
+ var _a;
47
+ if (!this.isConnected)
48
+ return;
49
+ this.isConnected = false;
50
+ this.emit("disconnected");
51
+ (_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
52
+ this.isAssistantSpeaking = false;
53
+ if (this.audioAnalyzer) {
54
+ this.audioAnalyzer.cleanup();
55
+ this.audioAnalyzer = undefined;
56
+ }
57
+ if (this.audioFrameCapture) {
58
+ cancelAnimationFrame(this.audioFrameCapture);
59
+ this.audioFrameCapture = undefined;
60
+ }
61
+ this.room = undefined;
62
+ }
63
+ toggleMicrophone(enabled) {
64
+ if (this.isConnected && this.room) {
65
+ this.room.localParticipant.setMicrophoneEnabled(enabled);
66
+ }
67
+ }
68
+ captureAudio() {
69
+ if (!this.isConnected || !this.audioAnalyzer)
70
+ return;
71
+ const bufferSize = this.audioAnalyzer.analyser.fftSize;
72
+ const audioData = new Float32Array(bufferSize);
73
+ this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
74
+ this.emit("audioData", audioData);
75
+ this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
76
+ }
77
+ setupEventHandlers(config) {
78
+ if (!this.room)
79
+ return;
80
+ // Room events
81
+ this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
82
+ if ((participant === null || participant === void 0 ? void 0 : participant.identity) === "assistant") {
83
+ this.endCall();
84
+ }
85
+ });
86
+ this.room.on(RoomEvent.Disconnected, () => {
87
+ if (this.isConnected)
88
+ this.endCall();
89
+ });
90
+ // Audio events
91
+ this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
92
+ var _a;
93
+ if (track.kind === Track.Kind.Audio) {
94
+ if (publication.trackName === "assistant_audio" &&
95
+ track instanceof RemoteAudioTrack &&
96
+ ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
97
+ const analyzer = createAudioAnalyser(track);
98
+ this.audioAnalyzer = {
99
+ calculateVolume: analyzer.calculateVolume,
100
+ analyser: analyzer.analyser,
101
+ cleanup: analyzer.cleanup
102
+ };
103
+ this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
104
+ }
105
+ track.attach();
106
+ }
107
+ });
108
+ // Data events
109
+ this.room.on(RoomEvent.DataReceived, (payload, participant) => {
110
+ if ((participant === null || participant === void 0 ? void 0 : participant.identity) !== "assistant")
111
+ return;
112
+ try {
113
+ const data = JSON.parse(decoder.decode(payload));
114
+ this.handleDataEvent(data);
115
+ }
116
+ catch (error) {
117
+ console.error("Failed to process received data:", error);
118
+ }
119
+ });
120
+ }
121
+ handleDataEvent(event) {
122
+ switch (event.type) {
123
+ case "status":
124
+ this.emit("status", event);
125
+ break;
126
+ case "metadata":
127
+ this.emit("metadata", event);
128
+ break;
129
+ case "assistant_speaking_started":
130
+ this.isAssistantSpeaking = true;
131
+ this.emit("assistantStartedSpeaking");
132
+ break;
133
+ case "assistant_speaking_ended":
134
+ this.isAssistantSpeaking = false;
135
+ this.emit("assistantStoppedSpeaking");
136
+ break;
137
+ }
138
+ }
139
+ }
@@ -0,0 +1,31 @@
1
+ import { EventEmitter } from "eventemitter3";
2
+ export interface TrilletCallConfig {
3
+ token: string;
4
+ audioSettings?: {
5
+ sampleRate?: number;
6
+ inputDeviceId?: string;
7
+ outputDeviceId?: string;
8
+ };
9
+ features?: {
10
+ enableRawAudio?: boolean;
11
+ };
12
+ }
13
+ export declare class TrilletWebSDK extends EventEmitter {
14
+ private room;
15
+ private isConnected;
16
+ isAssistantSpeaking: boolean;
17
+ audioAnalyzer?: {
18
+ calculateVolume: () => number;
19
+ analyser: AnalyserNode;
20
+ cleanup: () => Promise<void>;
21
+ };
22
+ private audioFrameCapture;
23
+ constructor();
24
+ initializeCall(config: TrilletCallConfig): Promise<void>;
25
+ enableAudioPlayback(): Promise<void>;
26
+ endCall(): void;
27
+ toggleMicrophone(enabled: boolean): void;
28
+ private captureAudio;
29
+ private setupEventHandlers;
30
+ private handleDataEvent;
31
+ }
@@ -0,0 +1,139 @@
1
+ import { EventEmitter } from "eventemitter3";
2
+ import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser, } from "livekit-client";
3
+ const TRILLET_WS_URL = "wss://trillet-ai-xdx0dw5r.livekit.cloud";
4
+ const decoder = new TextDecoder();
5
+ export class TrilletWebSDK extends EventEmitter {
6
+ constructor() {
7
+ super();
8
+ this.isConnected = false;
9
+ // Audio state tracking
10
+ this.isAssistantSpeaking = false;
11
+ }
12
+ async initializeCall(config) {
13
+ var _a, _b, _c;
14
+ try {
15
+ this.room = new Room({
16
+ audioCaptureDefaults: {
17
+ autoGainControl: true,
18
+ echoCancellation: true,
19
+ noiseSuppression: true,
20
+ channelCount: 1,
21
+ deviceId: (_a = config.audioSettings) === null || _a === void 0 ? void 0 : _a.inputDeviceId,
22
+ sampleRate: (_b = config.audioSettings) === null || _b === void 0 ? void 0 : _b.sampleRate,
23
+ },
24
+ audioOutput: {
25
+ deviceId: (_c = config.audioSettings) === null || _c === void 0 ? void 0 : _c.outputDeviceId,
26
+ },
27
+ });
28
+ this.setupEventHandlers(config);
29
+ await this.room.connect(TRILLET_WS_URL, config.token);
30
+ console.log("Connected to Trillet room:", this.room.name);
31
+ this.room.localParticipant.setMicrophoneEnabled(true);
32
+ this.isConnected = true;
33
+ this.emit("connected");
34
+ }
35
+ catch (error) {
36
+ this.emit("error", "Failed to initialize call");
37
+ console.error("Call initialization failed:", error);
38
+ this.endCall();
39
+ }
40
+ }
41
+ async enableAudioPlayback() {
42
+ var _a;
43
+ await ((_a = this.room) === null || _a === void 0 ? void 0 : _a.startAudio());
44
+ }
45
+ endCall() {
46
+ var _a;
47
+ if (!this.isConnected)
48
+ return;
49
+ this.isConnected = false;
50
+ this.emit("disconnected");
51
+ (_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
52
+ this.isAssistantSpeaking = false;
53
+ if (this.audioAnalyzer) {
54
+ this.audioAnalyzer.cleanup();
55
+ this.audioAnalyzer = undefined;
56
+ }
57
+ if (this.audioFrameCapture) {
58
+ cancelAnimationFrame(this.audioFrameCapture);
59
+ this.audioFrameCapture = undefined;
60
+ }
61
+ this.room = undefined;
62
+ }
63
+ toggleMicrophone(enabled) {
64
+ if (this.isConnected && this.room) {
65
+ this.room.localParticipant.setMicrophoneEnabled(enabled);
66
+ }
67
+ }
68
+ captureAudio() {
69
+ if (!this.isConnected || !this.audioAnalyzer)
70
+ return;
71
+ const bufferSize = this.audioAnalyzer.analyser.fftSize;
72
+ const audioData = new Float32Array(bufferSize);
73
+ this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
74
+ this.emit("audioData", audioData);
75
+ this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
76
+ }
77
+ setupEventHandlers(config) {
78
+ if (!this.room)
79
+ return;
80
+ // Room events
81
+ this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
82
+ if ((participant === null || participant === void 0 ? void 0 : participant.identity) === "assistant") {
83
+ this.endCall();
84
+ }
85
+ });
86
+ this.room.on(RoomEvent.Disconnected, () => {
87
+ if (this.isConnected)
88
+ this.endCall();
89
+ });
90
+ // Audio events
91
+ this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
92
+ var _a;
93
+ if (track.kind === Track.Kind.Audio) {
94
+ if (publication.trackName === "assistant_audio" &&
95
+ track instanceof RemoteAudioTrack &&
96
+ ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
97
+ const analyzer = createAudioAnalyser(track);
98
+ this.audioAnalyzer = {
99
+ calculateVolume: analyzer.calculateVolume,
100
+ analyser: analyzer.analyser,
101
+ cleanup: analyzer.cleanup
102
+ };
103
+ this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
104
+ }
105
+ track.attach();
106
+ }
107
+ });
108
+ // Data events
109
+ this.room.on(RoomEvent.DataReceived, (payload, participant) => {
110
+ if ((participant === null || participant === void 0 ? void 0 : participant.identity) !== "assistant")
111
+ return;
112
+ try {
113
+ const data = JSON.parse(decoder.decode(payload));
114
+ this.handleDataEvent(data);
115
+ }
116
+ catch (error) {
117
+ console.error("Failed to process received data:", error);
118
+ }
119
+ });
120
+ }
121
+ handleDataEvent(event) {
122
+ switch (event.type) {
123
+ case "status":
124
+ this.emit("status", event);
125
+ break;
126
+ case "metadata":
127
+ this.emit("metadata", event);
128
+ break;
129
+ case "assistant_speaking_started":
130
+ this.isAssistantSpeaking = true;
131
+ this.emit("assistantStartedSpeaking");
132
+ break;
133
+ case "assistant_speaking_ended":
134
+ this.isAssistantSpeaking = false;
135
+ this.emit("assistantStoppedSpeaking");
136
+ break;
137
+ }
138
+ }
139
+ }
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@trillet-ai/web-sdk",
3
+ "version": "1.0.1",
4
+ "description": "Trillet Web SDK for real-time audio communication",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "type": "module",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "scripts": {
12
+ "build": "tsc",
13
+ "dev": "tsc --watch",
14
+ "lint": "eslint src/**/*.{ts,tsx}",
15
+ "prepare": "npm run build",
16
+ "test": "node test/browser/server.js",
17
+ "test:api": "node test/test-api.js"
18
+ },
19
+ "peerDependencies": {
20
+ "react": ">=16.8.0",
21
+ "react-dom": ">=16.8.0"
22
+ },
23
+ "keywords": [
24
+ "trillet",
25
+ "audio",
26
+ "sdk",
27
+ "webrtc"
28
+ ],
29
+ "author": "Trillet AI",
30
+ "license": "MIT",
31
+ "dependencies": {
32
+ "dotenv": "^16.4.7",
33
+ "eventemitter3": "^5.0.1",
34
+ "livekit-client": "^1.15.5",
35
+ "node-fetch": "^3.3.2"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^20.11.0",
39
+ "@typescript-eslint/eslint-plugin": "^6.18.1",
40
+ "@typescript-eslint/parser": "^6.18.1",
41
+ "eslint": "^8.56.0",
42
+ "typescript": "^5.3.3",
43
+ "express": "^4.18.2",
44
+ "@types/react": "^18.2.0",
45
+ "@types/react-dom": "^18.2.0",
46
+ "react": "^18.2.0",
47
+ "react-dom": "^18.2.0"
48
+ },
49
+ "files": [
50
+ "dist",
51
+ "README.md"
52
+ ]
53
+ }