-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
273 lines (230 loc) · 7.8 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import { DailyTransport } from "@daily-co/realtime-ai-daily";
import { OpenAIWebSocketTransport } from "./openai-websocket-transport";
import {
Transport,
RTVIClient,
RTVIEvent,
RTVIMessage,
Participant,
TranscriptData,
BotTTSTextData,
BotLLMTextData
} from "realtime-ai";
import { join } from "path";
import { profile } from "console";
//
//
//
let joinDiv;
document.addEventListener('DOMContentLoaded', () => {
joinDiv = document.getElementById('join-div');
document.getElementById('start-daily-transport-session').addEventListener('click', () => {
startBot('daily');
});
document.getElementById('start-websocket-transport-session').addEventListener('click', () => {
startBot('openai');
});
document.getElementById('start-smart-endpointing-session').addEventListener('click', () => {
startBot('natural-conversation');
});
});
//
//
//
async function startBot(profileChoice: string) {
let transport: Transport;
joinDiv.textContent = 'Joining...';
if (profileChoice === 'daily') {
console.log('-- starting bot with Daily transport --');
transport = new DailyTransport();
} else if (profileChoice === 'openai') {
console.log('-- starting bot with OpenAI WebSocket transport --');
transport = new OpenAIWebSocketTransport();
} else if (profileChoice === 'natural-conversation') {
console.log('-- starting bot with Natural Conversation transport --');
transport = new DailyTransport();
} else {
console.error('Unknown profile choice:', profileChoice);
return;
}
const rtviClient = new RTVIClient({
transport,
params: {
baseUrl: "api", // not currently used for OpenAI transport
requestData: {
natural_conversation: (profileChoice === "natural-conversation"),
llm_service_options: {
initial_messages: [
{
role: "system",
content:
"You are a helpful assistant. Your name is ExampleBot. Keep responses brief and legible. Your responses will be converted to audio, so avoid using special characters or formatting. Please do use normal punctuation at the end of a sentence.",
},
{ role: "user", content: "Hello, ExampleBot!" },
]
}
}
},
enableMic: true,
enableCam: false,
timeout: 30 * 1000,
});
setupEventHandlers(rtviClient);
try {
await rtviClient.initDevices();
await rtviClient.connect();
} catch (e) {
console.log('Error connecting', e);
}
}
//
//
//
let audioDiv: HTMLDivElement;
let chatTextDiv: HTMLDivElement;
let currentUserSpeechDiv: HTMLDivElement;
let currentBotSpeechDiv: HTMLDivElement;
let currentSpeaker = ''; // 'user' or 'bot'
export async function setupEventHandlers(rtviClient: RTVIClient) {
audioDiv = document.getElementById('audio') as HTMLDivElement;
chatTextDiv = document.getElementById('chat-text') as HTMLDivElement;
rtviClient.on(RTVIEvent.TransportStateChanged, (state: string) => {
console.log(`-- transport state change: ${state} --`);
joinDiv.textContent = `Transport state: ${state}`;
});
rtviClient.on(RTVIEvent.Connected, () => {
console.log("-- user connected --");
});
rtviClient.on(RTVIEvent.Disconnected, () => {
console.log("-- user disconnected --");
});
rtviClient.on(RTVIEvent.BotConnected, () => {
console.log("-- bot connected --");
});
rtviClient.on(RTVIEvent.BotDisconnected, () => {
console.log("--bot disconnected --");
});
rtviClient.on(RTVIEvent.BotReady, () => {
console.log("-- bot ready to chat! --");
});
rtviClient.on(RTVIEvent.TrackStarted, (track: MediaStreamTrack, participant: Participant) => {
console.log(" --> track started", participant, track);
if (participant.local) {
return;
}
let audio = document.createElement("audio");
audio.srcObject = new MediaStream([track]);
audio.autoplay = true;
audioDiv.appendChild(audio);
});
rtviClient.on(RTVIEvent.UserStartedSpeaking, startUserSpeechBubble);
rtviClient.on(RTVIEvent.UserStoppedSpeaking, finishUserSpeechBubble);
rtviClient.on(RTVIEvent.BotStartedSpeaking, startBotSpeechBubble);
rtviClient.on(RTVIEvent.BotStoppedSpeaking, finishBotSpeechBubble);
rtviClient.on(RTVIEvent.UserTranscript, (transcript: TranscriptData) => {
if (transcript.final) {
handleUserFinalTranscription(transcript.text);
} else {
handleUserInterimTranscription(transcript.text);
}
});
rtviClient.on(RTVIEvent.BotTtsText,
// this is a hack: need to make Pipecat pipeline setting for this configurable.
(data) => handleBotStreamedVoiceText(data, rtviClient._transport instanceof DailyTransport)
);
rtviClient.on(RTVIEvent.BotTranscript, handleBotLLMText);
rtviClient.on(RTVIEvent.Error, (message: RTVIMessage) => {
console.log("[EVENT] RTVI Error!", message);
});
rtviClient.on(RTVIEvent.MessageError, (message: RTVIMessage) => {
console.log("[EVENT] RTVI ErrorMessage error!", message);
});
rtviClient.on(RTVIEvent.Metrics, (data) => {
// let's only print out ttfb for now
if (! data.ttfb) {
return;
}
data.ttfb.map((metric) => {
console.log(`[METRICS] ${metric.processor} ttfb: ${metric.value}`);
});
});
}
async function startUserSpeechBubble() {
console.log('-- user started speaking -- ');
if (currentSpeaker === 'user') {
if (currentUserSpeechDiv) {
return;
}
// Should never get here, but, you know.
}
currentSpeaker = 'user';
// First check if we need to remove an empty assistant speech bubble. This can happen
// if there's a fast user interruption.
if (currentBotSpeechDiv && currentBotSpeechDiv.textContent === '') {
chatTextDiv.removeChild(currentBotSpeechDiv);
currentBotSpeechDiv = null;
if (!currentUserSpeechDiv) {
currentUserSpeechDiv = document.createElement('div');
currentUserSpeechDiv.className = 'user-message';
}
} else {
currentUserSpeechDiv = document.createElement('div');
currentUserSpeechDiv.className = 'user-message';
}
let span = document.createElement('span');
currentUserSpeechDiv.appendChild(span);
chatTextDiv.appendChild(currentUserSpeechDiv);
}
async function finishUserSpeechBubble() {
console.log('-- user stopped speaking -- ');
// noop for now. Could do UI update here.
}
async function startBotSpeechBubble() {
currentSpeaker = 'bot';
currentBotSpeechDiv = document.createElement('div');
currentBotSpeechDiv.className = 'assistant-message';
chatTextDiv.appendChild(currentBotSpeechDiv);
}
async function finishBotSpeechBubble() {
console.log('-- bot stopped speaking -- ');
}
async function handleUserInterimTranscription(text: string) {
console.log('interim transcription:', text);
if (currentSpeaker !== 'user') {
return;
}
let span = currentUserSpeechDiv.querySelector('span:last-of-type');
span.classList.add('interim');
span.textContent = text + " ";
scroll();
}
async function handleUserFinalTranscription(text: string) {
console.log('final transcription:', text);
// // Ignore transcriptions that arrive while the bot is talking.
// if (currentSpeaker === 'bot') {
// return;
// }
let span = currentUserSpeechDiv.querySelector('span:last-of-type');
span.classList.remove('interim');
span.textContent = text + " ";
let newSpan = document.createElement('span');
currentUserSpeechDiv.appendChild(newSpan);
scroll();
}
async function handleBotStreamedVoiceText(data: BotTTSTextData, addSpaces: boolean) {
console.log('bot streamed text:', data.text);
if (!currentBotSpeechDiv) {
return;
}
currentBotSpeechDiv.textContent += data.text + (addSpaces ? " " : "");
scroll();
}
async function handleBotLLMText(data: BotLLMTextData) {
console.log('bot llm text:', data.text);
}
function scroll() {
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});
}