@livekit/agents-plugin-openai 0.2.0 → 0.3.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/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +28 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/realtime/api_proto.d.ts +399 -0
- package/dist/realtime/api_proto.d.ts.map +1 -0
- package/dist/realtime/api_proto.js +9 -0
- package/dist/realtime/api_proto.js.map +1 -0
- package/dist/realtime/index.d.ts +3 -0
- package/dist/realtime/index.d.ts.map +1 -0
- package/dist/realtime/index.js +6 -0
- package/dist/realtime/index.js.map +1 -0
- package/dist/realtime/realtime_model.d.ts +149 -0
- package/dist/realtime/realtime_model.d.ts.map +1 -0
- package/dist/realtime/realtime_model.js +571 -0
- package/dist/realtime/realtime_model.js.map +1 -0
- package/package.json +5 -3
- package/src/index.ts +1 -2
- package/src/realtime/api_proto.ts +565 -0
- package/src/realtime/index.ts +5 -0
- package/src/realtime/realtime_model.ts +859 -0
- package/dist/omni_assistant/agent_playout.d.ts +0 -27
- package/dist/omni_assistant/agent_playout.d.ts.map +0 -1
- package/dist/omni_assistant/agent_playout.js +0 -111
- package/dist/omni_assistant/agent_playout.js.map +0 -1
- package/dist/omni_assistant/index.d.ts +0 -61
- package/dist/omni_assistant/index.d.ts.map +0 -1
- package/dist/omni_assistant/index.js +0 -453
- package/dist/omni_assistant/index.js.map +0 -1
- package/dist/omni_assistant/proto.d.ts +0 -218
- package/dist/omni_assistant/proto.d.ts.map +0 -1
- package/dist/omni_assistant/proto.js +0 -68
- package/dist/omni_assistant/proto.js.map +0 -1
- package/dist/omni_assistant/transcription_forwarder.d.ts +0 -28
- package/dist/omni_assistant/transcription_forwarder.d.ts.map +0 -1
- package/dist/omni_assistant/transcription_forwarder.js +0 -117
- package/dist/omni_assistant/transcription_forwarder.js.map +0 -1
- package/src/omni_assistant/agent_playout.ts +0 -127
- package/src/omni_assistant/index.ts +0 -547
- package/src/omni_assistant/proto.ts +0 -280
- package/src/omni_assistant/transcription_forwarder.ts +0 -128
|
@@ -0,0 +1,859 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import { AsyncIterableQueue, Future, Queue } from '@livekit/agents';
|
|
5
|
+
import { llm, log, multimodal } from '@livekit/agents';
|
|
6
|
+
import { AudioFrame } from '@livekit/rtc-node';
|
|
7
|
+
import { once } from 'events';
|
|
8
|
+
import { WebSocket } from 'ws';
|
|
9
|
+
import * as api_proto from './api_proto.js';
|
|
10
|
+
|
|
11
|
+
interface ModelOptions {
|
|
12
|
+
modalities: ['text', 'audio'] | ['text'];
|
|
13
|
+
instructions: string;
|
|
14
|
+
voice: api_proto.Voice;
|
|
15
|
+
inputAudioFormat: api_proto.AudioFormat;
|
|
16
|
+
outputAudioFormat: api_proto.AudioFormat;
|
|
17
|
+
inputAudioTranscription: api_proto.InputAudioTranscription | null;
|
|
18
|
+
turnDetection: api_proto.TurnDetectionType | null;
|
|
19
|
+
temperature: number;
|
|
20
|
+
maxResponseOutputTokens: number;
|
|
21
|
+
model: api_proto.Model;
|
|
22
|
+
apiKey: string;
|
|
23
|
+
baseURL: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface RealtimeResponse {
|
|
27
|
+
id: string;
|
|
28
|
+
status: api_proto.ResponseStatus;
|
|
29
|
+
output: RealtimeOutput[];
|
|
30
|
+
doneFut: Future;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface RealtimeOutput {
|
|
34
|
+
responseId: string;
|
|
35
|
+
itemId: string;
|
|
36
|
+
outputIndex: number;
|
|
37
|
+
role: api_proto.Role;
|
|
38
|
+
type: 'message' | 'function_call';
|
|
39
|
+
content: RealtimeContent[];
|
|
40
|
+
doneFut: Future;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface RealtimeContent {
|
|
44
|
+
responseId: string;
|
|
45
|
+
itemId: string;
|
|
46
|
+
outputIndex: number;
|
|
47
|
+
contentIndex: number;
|
|
48
|
+
text: string;
|
|
49
|
+
audio: AudioFrame[];
|
|
50
|
+
textStream: AsyncIterableQueue<string>;
|
|
51
|
+
audioStream: AsyncIterableQueue<AudioFrame>;
|
|
52
|
+
toolCalls: RealtimeToolCall[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface RealtimeToolCall {
|
|
56
|
+
name: string;
|
|
57
|
+
arguments: string;
|
|
58
|
+
toolCallID: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface InputSpeechTranscriptionCompleted {
|
|
62
|
+
itemId: string;
|
|
63
|
+
transcript: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface InputSpeechTranscriptionFailed {
|
|
67
|
+
itemId: string;
|
|
68
|
+
message: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface InputSpeechStarted {
|
|
72
|
+
itemId: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface InputSpeechCommitted {
|
|
76
|
+
itemId: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
class InputAudioBuffer {
|
|
80
|
+
#session: RealtimeSession;
|
|
81
|
+
|
|
82
|
+
constructor(session: RealtimeSession) {
|
|
83
|
+
this.#session = session;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
append(frame: AudioFrame) {
|
|
87
|
+
this.#session.queueMsg({
|
|
88
|
+
type: 'input_audio_buffer.append',
|
|
89
|
+
audio: Buffer.from(frame.data.buffer).toString('base64'),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
clear() {
|
|
94
|
+
this.#session.queueMsg({
|
|
95
|
+
type: 'input_audio_buffer.clear',
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
commit() {
|
|
100
|
+
this.#session.queueMsg({
|
|
101
|
+
type: 'input_audio_buffer.commit',
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
class ConversationItem {
|
|
107
|
+
#session: RealtimeSession;
|
|
108
|
+
|
|
109
|
+
constructor(session: RealtimeSession) {
|
|
110
|
+
this.#session = session;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
truncate(itemId: string, contentIndex: number, audioEnd: number) {
|
|
114
|
+
this.#session.queueMsg({
|
|
115
|
+
type: 'conversation.item.truncate',
|
|
116
|
+
item_id: itemId,
|
|
117
|
+
content_index: contentIndex,
|
|
118
|
+
audio_end_ms: audioEnd,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
delete(itemId: string) {
|
|
123
|
+
this.#session.queueMsg({
|
|
124
|
+
type: 'conversation.item.delete',
|
|
125
|
+
item_id: itemId,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
create(item: api_proto.ConversationItemCreateContent, previousItemId?: string): void {
|
|
130
|
+
this.#session.queueMsg({
|
|
131
|
+
type: 'conversation.item.create',
|
|
132
|
+
item,
|
|
133
|
+
previous_item_id: previousItemId,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
class Conversation {
|
|
139
|
+
#session: RealtimeSession;
|
|
140
|
+
|
|
141
|
+
constructor(session: RealtimeSession) {
|
|
142
|
+
this.#session = session;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
get item(): ConversationItem {
|
|
146
|
+
return new ConversationItem(this.#session);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
class Response {
|
|
151
|
+
#session: RealtimeSession;
|
|
152
|
+
|
|
153
|
+
constructor(session: RealtimeSession) {
|
|
154
|
+
this.#session = session;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
create() {
|
|
158
|
+
this.#session.queueMsg({
|
|
159
|
+
type: 'response.create',
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
cancel() {
|
|
164
|
+
this.#session.queueMsg({
|
|
165
|
+
type: 'response.cancel',
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
interface ContentPtr {
|
|
171
|
+
response_id: string;
|
|
172
|
+
output_index: number;
|
|
173
|
+
content_index: number;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export class RealtimeModel extends multimodal.RealtimeModel {
|
|
177
|
+
sampleRate = api_proto.SAMPLE_RATE;
|
|
178
|
+
numChannels = api_proto.NUM_CHANNELS;
|
|
179
|
+
inFrameSize = api_proto.IN_FRAME_SIZE;
|
|
180
|
+
outFrameSize = api_proto.OUT_FRAME_SIZE;
|
|
181
|
+
|
|
182
|
+
#defaultOpts: ModelOptions;
|
|
183
|
+
#sessions: RealtimeSession[] = [];
|
|
184
|
+
|
|
185
|
+
constructor({
|
|
186
|
+
modalities = ['text', 'audio'],
|
|
187
|
+
instructions = '',
|
|
188
|
+
voice = 'alloy',
|
|
189
|
+
inputAudioFormat = 'pcm16',
|
|
190
|
+
outputAudioFormat = 'pcm16',
|
|
191
|
+
inputAudioTranscription = { model: 'whisper-1' },
|
|
192
|
+
turnDetection = { type: 'server_vad' },
|
|
193
|
+
temperature = 0.8,
|
|
194
|
+
maxResponseOutputTokens = Infinity,
|
|
195
|
+
model = 'gpt-4o-realtime-preview-2024-10-01',
|
|
196
|
+
apiKey = process.env.OPENAI_API_KEY || '',
|
|
197
|
+
baseURL = api_proto.API_URL,
|
|
198
|
+
}: {
|
|
199
|
+
modalities?: ['text', 'audio'] | ['text'];
|
|
200
|
+
instructions?: string;
|
|
201
|
+
voice?: api_proto.Voice;
|
|
202
|
+
inputAudioFormat?: api_proto.AudioFormat;
|
|
203
|
+
outputAudioFormat?: api_proto.AudioFormat;
|
|
204
|
+
inputAudioTranscription?: api_proto.InputAudioTranscription;
|
|
205
|
+
turnDetection?: api_proto.TurnDetectionType;
|
|
206
|
+
temperature?: number;
|
|
207
|
+
maxResponseOutputTokens?: number;
|
|
208
|
+
model?: api_proto.Model;
|
|
209
|
+
apiKey?: string;
|
|
210
|
+
baseURL?: string;
|
|
211
|
+
}) {
|
|
212
|
+
super();
|
|
213
|
+
|
|
214
|
+
if (apiKey === '') {
|
|
215
|
+
throw new Error(
|
|
216
|
+
'OpenAI API key is required, either using the argument or by setting the OPENAI_API_KEY environmental variable',
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
this.#defaultOpts = {
|
|
221
|
+
modalities,
|
|
222
|
+
instructions,
|
|
223
|
+
voice,
|
|
224
|
+
inputAudioFormat,
|
|
225
|
+
outputAudioFormat,
|
|
226
|
+
inputAudioTranscription,
|
|
227
|
+
turnDetection,
|
|
228
|
+
temperature,
|
|
229
|
+
maxResponseOutputTokens,
|
|
230
|
+
model,
|
|
231
|
+
apiKey,
|
|
232
|
+
baseURL,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
get sessions(): RealtimeSession[] {
|
|
237
|
+
return this.#sessions;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
session({
|
|
241
|
+
fncCtx,
|
|
242
|
+
modalities = this.#defaultOpts.modalities,
|
|
243
|
+
instructions = this.#defaultOpts.instructions,
|
|
244
|
+
voice = this.#defaultOpts.voice,
|
|
245
|
+
inputAudioFormat = this.#defaultOpts.inputAudioFormat,
|
|
246
|
+
outputAudioFormat = this.#defaultOpts.outputAudioFormat,
|
|
247
|
+
inputAudioTranscription = this.#defaultOpts.inputAudioTranscription,
|
|
248
|
+
turnDetection = this.#defaultOpts.turnDetection,
|
|
249
|
+
temperature = this.#defaultOpts.temperature,
|
|
250
|
+
maxResponseOutputTokens = this.#defaultOpts.maxResponseOutputTokens,
|
|
251
|
+
}: {
|
|
252
|
+
fncCtx?: llm.FunctionContext;
|
|
253
|
+
modalities?: ['text', 'audio'] | ['text'];
|
|
254
|
+
instructions?: string;
|
|
255
|
+
voice?: api_proto.Voice;
|
|
256
|
+
inputAudioFormat?: api_proto.AudioFormat;
|
|
257
|
+
outputAudioFormat?: api_proto.AudioFormat;
|
|
258
|
+
inputAudioTranscription?: api_proto.InputAudioTranscription | null;
|
|
259
|
+
turnDetection?: api_proto.TurnDetectionType | null;
|
|
260
|
+
temperature?: number;
|
|
261
|
+
maxResponseOutputTokens?: number;
|
|
262
|
+
}): RealtimeSession {
|
|
263
|
+
const opts: ModelOptions = {
|
|
264
|
+
modalities,
|
|
265
|
+
instructions,
|
|
266
|
+
voice,
|
|
267
|
+
inputAudioFormat,
|
|
268
|
+
outputAudioFormat,
|
|
269
|
+
inputAudioTranscription,
|
|
270
|
+
turnDetection,
|
|
271
|
+
temperature,
|
|
272
|
+
maxResponseOutputTokens,
|
|
273
|
+
model: this.#defaultOpts.model,
|
|
274
|
+
apiKey: this.#defaultOpts.apiKey,
|
|
275
|
+
baseURL: this.#defaultOpts.baseURL,
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
const newSession = new RealtimeSession(opts, fncCtx);
|
|
279
|
+
this.#sessions.push(newSession);
|
|
280
|
+
return newSession;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async close() {
|
|
284
|
+
await Promise.allSettled(this.#sessions.map((session) => session.close()));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export class RealtimeSession extends multimodal.RealtimeSession {
|
|
289
|
+
#fncCtx: llm.FunctionContext | undefined = undefined;
|
|
290
|
+
#opts: ModelOptions;
|
|
291
|
+
#pendingResponses: { [id: string]: RealtimeResponse } = {};
|
|
292
|
+
#sessionId = 'not-connected';
|
|
293
|
+
#ws: WebSocket | null = null;
|
|
294
|
+
#expiresAt: number | null = null;
|
|
295
|
+
#logger = log();
|
|
296
|
+
#task: Promise<void>;
|
|
297
|
+
#closing = true;
|
|
298
|
+
#sendQueue = new Queue<api_proto.ClientEvent>();
|
|
299
|
+
|
|
300
|
+
constructor(opts: ModelOptions, fncCtx?: llm.FunctionContext | undefined) {
|
|
301
|
+
super();
|
|
302
|
+
|
|
303
|
+
this.#opts = opts;
|
|
304
|
+
this.#fncCtx = fncCtx;
|
|
305
|
+
|
|
306
|
+
this.#task = this.#start();
|
|
307
|
+
|
|
308
|
+
this.sessionUpdate({
|
|
309
|
+
modalities: this.#opts.modalities,
|
|
310
|
+
instructions: this.#opts.instructions,
|
|
311
|
+
voice: this.#opts.voice,
|
|
312
|
+
inputAudioFormat: this.#opts.inputAudioFormat,
|
|
313
|
+
outputAudioFormat: this.#opts.outputAudioFormat,
|
|
314
|
+
inputAudioTranscription: this.#opts.inputAudioTranscription,
|
|
315
|
+
turnDetection: this.#opts.turnDetection,
|
|
316
|
+
temperature: this.#opts.temperature,
|
|
317
|
+
maxResponseOutputTokens: this.#opts.maxResponseOutputTokens,
|
|
318
|
+
toolChoice: 'auto',
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
get fncCtx(): llm.FunctionContext | undefined {
|
|
323
|
+
return this.#fncCtx;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
set fncCtx(ctx: llm.FunctionContext | undefined) {
|
|
327
|
+
this.#fncCtx = ctx;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
get defaultConversation(): Conversation {
|
|
331
|
+
return new Conversation(this);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
get inputAudioBuffer(): InputAudioBuffer {
|
|
335
|
+
return new InputAudioBuffer(this);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
get response(): Response {
|
|
339
|
+
return new Response(this);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
get expiration(): number {
|
|
343
|
+
if (!this.#expiresAt) {
|
|
344
|
+
throw new Error('session not started');
|
|
345
|
+
}
|
|
346
|
+
return this.#expiresAt * 1000;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
queueMsg(command: api_proto.ClientEvent): void {
|
|
350
|
+
this.#sendQueue.put(command);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/// Truncates the data field of the event to the specified maxLength to avoid overwhelming logs
|
|
354
|
+
/// with large amounts of base64 audio data.
|
|
355
|
+
#loggableEvent(
|
|
356
|
+
event: api_proto.ClientEvent | api_proto.ServerEvent,
|
|
357
|
+
maxLength: number = 30,
|
|
358
|
+
): Record<string, unknown> {
|
|
359
|
+
const untypedEvent: Record<string, unknown> = {};
|
|
360
|
+
for (const [key, value] of Object.entries(event)) {
|
|
361
|
+
if (value !== undefined) {
|
|
362
|
+
untypedEvent[key] = value;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
if (untypedEvent.audio && typeof untypedEvent.audio === 'string') {
|
|
367
|
+
const truncatedData =
|
|
368
|
+
untypedEvent.audio.slice(0, maxLength) + (untypedEvent.audio.length > maxLength ? '…' : '');
|
|
369
|
+
return { ...untypedEvent, audio: truncatedData };
|
|
370
|
+
}
|
|
371
|
+
if (
|
|
372
|
+
untypedEvent.delta &&
|
|
373
|
+
typeof untypedEvent.delta === 'string' &&
|
|
374
|
+
event.type === 'response.audio.delta'
|
|
375
|
+
) {
|
|
376
|
+
const truncatedDelta =
|
|
377
|
+
untypedEvent.delta.slice(0, maxLength) + (untypedEvent.delta.length > maxLength ? '…' : '');
|
|
378
|
+
return { ...untypedEvent, delta: truncatedDelta };
|
|
379
|
+
}
|
|
380
|
+
return untypedEvent;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
sessionUpdate({
|
|
384
|
+
modalities = this.#opts.modalities,
|
|
385
|
+
instructions = this.#opts.instructions,
|
|
386
|
+
voice = this.#opts.voice,
|
|
387
|
+
inputAudioFormat = this.#opts.inputAudioFormat,
|
|
388
|
+
outputAudioFormat = this.#opts.outputAudioFormat,
|
|
389
|
+
inputAudioTranscription = this.#opts.inputAudioTranscription,
|
|
390
|
+
turnDetection = this.#opts.turnDetection,
|
|
391
|
+
temperature = this.#opts.temperature,
|
|
392
|
+
maxResponseOutputTokens = this.#opts.maxResponseOutputTokens,
|
|
393
|
+
toolChoice = 'auto',
|
|
394
|
+
}: {
|
|
395
|
+
modalities: ['text', 'audio'] | ['text'];
|
|
396
|
+
instructions?: string;
|
|
397
|
+
voice?: api_proto.Voice;
|
|
398
|
+
inputAudioFormat?: api_proto.AudioFormat;
|
|
399
|
+
outputAudioFormat?: api_proto.AudioFormat;
|
|
400
|
+
inputAudioTranscription?: api_proto.InputAudioTranscription | null;
|
|
401
|
+
turnDetection?: api_proto.TurnDetectionType | null;
|
|
402
|
+
temperature?: number;
|
|
403
|
+
maxResponseOutputTokens?: number;
|
|
404
|
+
toolChoice?: api_proto.ToolChoice;
|
|
405
|
+
}) {
|
|
406
|
+
this.#opts = {
|
|
407
|
+
modalities,
|
|
408
|
+
instructions,
|
|
409
|
+
voice,
|
|
410
|
+
inputAudioFormat,
|
|
411
|
+
outputAudioFormat,
|
|
412
|
+
inputAudioTranscription,
|
|
413
|
+
turnDetection,
|
|
414
|
+
temperature,
|
|
415
|
+
maxResponseOutputTokens,
|
|
416
|
+
model: this.#opts.model,
|
|
417
|
+
apiKey: this.#opts.apiKey,
|
|
418
|
+
baseURL: this.#opts.baseURL,
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
const tools = this.#fncCtx
|
|
422
|
+
? Object.entries(this.#fncCtx).map(([name, func]) => ({
|
|
423
|
+
type: 'function' as const,
|
|
424
|
+
name,
|
|
425
|
+
description: func.description,
|
|
426
|
+
parameters: llm.oaiParams(func.parameters),
|
|
427
|
+
}))
|
|
428
|
+
: [];
|
|
429
|
+
|
|
430
|
+
this.queueMsg({
|
|
431
|
+
type: 'session.update',
|
|
432
|
+
session: {
|
|
433
|
+
modalities: this.#opts.modalities,
|
|
434
|
+
instructions: this.#opts.instructions,
|
|
435
|
+
voice: this.#opts.voice,
|
|
436
|
+
input_audio_format: this.#opts.inputAudioFormat,
|
|
437
|
+
output_audio_format: this.#opts.outputAudioFormat,
|
|
438
|
+
input_audio_transcription: this.#opts.inputAudioTranscription,
|
|
439
|
+
turn_detection: this.#opts.turnDetection,
|
|
440
|
+
temperature: this.#opts.temperature,
|
|
441
|
+
max_response_output_tokens:
|
|
442
|
+
this.#opts.maxResponseOutputTokens === Infinity
|
|
443
|
+
? 'inf'
|
|
444
|
+
: this.#opts.maxResponseOutputTokens,
|
|
445
|
+
tools,
|
|
446
|
+
tool_choice: toolChoice,
|
|
447
|
+
},
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
#start(): Promise<void> {
|
|
452
|
+
return new Promise(async (resolve, reject) => {
|
|
453
|
+
this.#ws = new WebSocket(`${this.#opts.baseURL}?model=${this.#opts.model}`, {
|
|
454
|
+
headers: {
|
|
455
|
+
Authorization: `Bearer ${this.#opts.apiKey}`,
|
|
456
|
+
'OpenAI-Beta': 'realtime=v1',
|
|
457
|
+
},
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
this.#ws.onerror = (error) => {
|
|
461
|
+
reject(error);
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
await once(this.#ws, 'open');
|
|
465
|
+
this.#closing = false;
|
|
466
|
+
|
|
467
|
+
this.#ws.onmessage = (message) => {
|
|
468
|
+
const event: api_proto.ServerEvent = JSON.parse(message.data as string);
|
|
469
|
+
this.#logger.debug(`<- ${JSON.stringify(this.#loggableEvent(event))}`);
|
|
470
|
+
switch (event.type) {
|
|
471
|
+
case 'error':
|
|
472
|
+
this.#handleError(event);
|
|
473
|
+
break;
|
|
474
|
+
case 'session.created':
|
|
475
|
+
this.#handleSessionCreated(event);
|
|
476
|
+
break;
|
|
477
|
+
case 'session.updated':
|
|
478
|
+
this.#handleSessionUpdated(event);
|
|
479
|
+
break;
|
|
480
|
+
case 'conversation.created':
|
|
481
|
+
this.#handleConversationCreated(event);
|
|
482
|
+
break;
|
|
483
|
+
case 'input_audio_buffer.committed':
|
|
484
|
+
this.#handleInputAudioBufferCommitted(event);
|
|
485
|
+
break;
|
|
486
|
+
case 'input_audio_buffer.cleared':
|
|
487
|
+
this.#handleInputAudioBufferCleared(event);
|
|
488
|
+
break;
|
|
489
|
+
case 'input_audio_buffer.speech_started':
|
|
490
|
+
this.#handleInputAudioBufferSpeechStarted(event);
|
|
491
|
+
break;
|
|
492
|
+
case 'input_audio_buffer.speech_stopped':
|
|
493
|
+
this.#handleInputAudioBufferSpeechStopped(event);
|
|
494
|
+
break;
|
|
495
|
+
case 'conversation.item.created':
|
|
496
|
+
this.#handleConversationItemCreated(event);
|
|
497
|
+
break;
|
|
498
|
+
case 'conversation.item.input_audio_transcription.completed':
|
|
499
|
+
this.#handleConversationItemInputAudioTranscriptionCompleted(event);
|
|
500
|
+
break;
|
|
501
|
+
case 'conversation.item.input_audio_transcription.failed':
|
|
502
|
+
this.#handleConversationItemInputAudioTranscriptionFailed(event);
|
|
503
|
+
break;
|
|
504
|
+
case 'conversation.item.truncated':
|
|
505
|
+
this.#handleConversationItemTruncated(event);
|
|
506
|
+
break;
|
|
507
|
+
case 'conversation.item.deleted':
|
|
508
|
+
this.#handleConversationItemDeleted(event);
|
|
509
|
+
break;
|
|
510
|
+
case 'response.created':
|
|
511
|
+
this.#handleResponseCreated(event);
|
|
512
|
+
break;
|
|
513
|
+
case 'response.done':
|
|
514
|
+
this.#handleResponseDone(event);
|
|
515
|
+
break;
|
|
516
|
+
case 'response.output_item.added':
|
|
517
|
+
this.#handleResponseOutputItemAdded(event);
|
|
518
|
+
break;
|
|
519
|
+
case 'response.output_item.done':
|
|
520
|
+
this.#handleResponseOutputItemDone(event);
|
|
521
|
+
break;
|
|
522
|
+
case 'response.content_part.added':
|
|
523
|
+
this.#handleResponseContentPartAdded(event);
|
|
524
|
+
break;
|
|
525
|
+
case 'response.content_part.done':
|
|
526
|
+
this.#handleResponseContentPartDone(event);
|
|
527
|
+
break;
|
|
528
|
+
case 'response.text.delta':
|
|
529
|
+
this.#handleResponseTextDelta(event);
|
|
530
|
+
break;
|
|
531
|
+
case 'response.text.done':
|
|
532
|
+
this.#handleResponseTextDone(event);
|
|
533
|
+
break;
|
|
534
|
+
case 'response.audio_transcript.delta':
|
|
535
|
+
this.#handleResponseAudioTranscriptDelta(event);
|
|
536
|
+
break;
|
|
537
|
+
case 'response.audio_transcript.done':
|
|
538
|
+
this.#handleResponseAudioTranscriptDone(event);
|
|
539
|
+
break;
|
|
540
|
+
case 'response.audio.delta':
|
|
541
|
+
this.#handleResponseAudioDelta(event);
|
|
542
|
+
break;
|
|
543
|
+
case 'response.audio.done':
|
|
544
|
+
this.#handleResponseAudioDone(event);
|
|
545
|
+
break;
|
|
546
|
+
case 'response.function_call_arguments.delta':
|
|
547
|
+
this.#handleResponseFunctionCallArgumentsDelta(event);
|
|
548
|
+
break;
|
|
549
|
+
case 'response.function_call_arguments.done':
|
|
550
|
+
this.#handleResponseFunctionCallArgumentsDone(event);
|
|
551
|
+
break;
|
|
552
|
+
case 'rate_limits.updated':
|
|
553
|
+
this.#handleRateLimitsUpdated(event);
|
|
554
|
+
break;
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
const sendTask = async () => {
|
|
559
|
+
while (this.#ws && !this.#closing && this.#ws.readyState === WebSocket.OPEN) {
|
|
560
|
+
try {
|
|
561
|
+
const event = await this.#sendQueue.get();
|
|
562
|
+
if (event.type !== 'input_audio_buffer.append') {
|
|
563
|
+
this.#logger.debug(`-> ${JSON.stringify(this.#loggableEvent(event))}`);
|
|
564
|
+
}
|
|
565
|
+
this.#ws.send(JSON.stringify(event));
|
|
566
|
+
} catch (error) {
|
|
567
|
+
this.#logger.error('Error sending event:', error);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
sendTask();
|
|
573
|
+
|
|
574
|
+
this.#ws.onclose = () => {
|
|
575
|
+
if (this.#expiresAt && Date.now() >= this.#expiresAt * 1000) {
|
|
576
|
+
this.#closing = true;
|
|
577
|
+
}
|
|
578
|
+
if (!this.#closing) {
|
|
579
|
+
reject(new Error('OpenAI Realtime connection closed unexpectedly'));
|
|
580
|
+
}
|
|
581
|
+
this.#ws = null;
|
|
582
|
+
resolve();
|
|
583
|
+
};
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
async close() {
|
|
588
|
+
if (!this.#ws) return;
|
|
589
|
+
this.#closing = true;
|
|
590
|
+
this.#ws.close();
|
|
591
|
+
await this.#task;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
#getContent(ptr: ContentPtr): RealtimeContent {
|
|
595
|
+
const response = this.#pendingResponses[ptr.response_id];
|
|
596
|
+
const output = response.output[ptr.output_index];
|
|
597
|
+
const content = output.content[ptr.content_index];
|
|
598
|
+
return content;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
#handleError(event: api_proto.ErrorEvent): void {
|
|
602
|
+
this.#logger.error(`OpenAI Realtime error ${JSON.stringify(event.error)}`);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
#handleSessionCreated(event: api_proto.SessionCreatedEvent): void {
|
|
606
|
+
this.#sessionId = event.session.id;
|
|
607
|
+
this.#expiresAt = event.session.expires_at;
|
|
608
|
+
this.#logger = this.#logger.child({ sessionId: this.#sessionId });
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
612
|
+
#handleSessionUpdated(event: api_proto.SessionUpdatedEvent): void {}
|
|
613
|
+
|
|
614
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
615
|
+
#handleConversationCreated(event: api_proto.ConversationCreatedEvent): void {}
|
|
616
|
+
|
|
617
|
+
#handleInputAudioBufferCommitted(event: api_proto.InputAudioBufferCommittedEvent): void {
|
|
618
|
+
this.emit('input_speech_committed', {
|
|
619
|
+
itemId: event.item_id,
|
|
620
|
+
} as InputSpeechCommitted);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
624
|
+
#handleInputAudioBufferCleared(event: api_proto.InputAudioBufferClearedEvent): void {}
|
|
625
|
+
|
|
626
|
+
#handleInputAudioBufferSpeechStarted(
|
|
627
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
628
|
+
event: api_proto.InputAudioBufferSpeechStartedEvent,
|
|
629
|
+
): void {
|
|
630
|
+
this.emit('input_speech_started', {
|
|
631
|
+
itemId: event.item_id,
|
|
632
|
+
} as InputSpeechStarted);
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
#handleInputAudioBufferSpeechStopped(
|
|
636
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
637
|
+
event: api_proto.InputAudioBufferSpeechStoppedEvent,
|
|
638
|
+
): void {
|
|
639
|
+
this.emit('input_speech_stopped');
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
643
|
+
#handleConversationItemCreated(event: api_proto.ConversationItemCreatedEvent): void {}
|
|
644
|
+
|
|
645
|
+
#handleConversationItemInputAudioTranscriptionCompleted(
|
|
646
|
+
event: api_proto.ConversationItemInputAudioTranscriptionCompletedEvent,
|
|
647
|
+
): void {
|
|
648
|
+
const transcript = event.transcript;
|
|
649
|
+
this.emit('input_speech_transcription_completed', {
|
|
650
|
+
itemId: event.item_id,
|
|
651
|
+
transcript: transcript,
|
|
652
|
+
} as InputSpeechTranscriptionCompleted);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
#handleConversationItemInputAudioTranscriptionFailed(
|
|
656
|
+
event: api_proto.ConversationItemInputAudioTranscriptionFailedEvent,
|
|
657
|
+
): void {
|
|
658
|
+
const error = event.error;
|
|
659
|
+
this.#logger.error(`OpenAI Realtime failed to transcribe input audio: ${error.message}`);
|
|
660
|
+
this.emit('input_speech_transcription_failed', {
|
|
661
|
+
itemId: event.item_id,
|
|
662
|
+
message: error.message,
|
|
663
|
+
} as InputSpeechTranscriptionFailed);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
667
|
+
#handleConversationItemTruncated(event: api_proto.ConversationItemTruncatedEvent): void {}
|
|
668
|
+
|
|
669
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
670
|
+
#handleConversationItemDeleted(event: api_proto.ConversationItemDeletedEvent): void {}
|
|
671
|
+
|
|
672
|
+
#handleResponseCreated(responseCreated: api_proto.ResponseCreatedEvent): void {
|
|
673
|
+
const response = responseCreated.response;
|
|
674
|
+
const doneFut = new Future();
|
|
675
|
+
const newResponse: RealtimeResponse = {
|
|
676
|
+
id: response.id,
|
|
677
|
+
status: response.status,
|
|
678
|
+
output: [],
|
|
679
|
+
doneFut: doneFut,
|
|
680
|
+
};
|
|
681
|
+
this.#pendingResponses[newResponse.id] = newResponse;
|
|
682
|
+
this.emit('response_created', newResponse);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
#handleResponseDone(event: api_proto.ResponseDoneEvent): void {
|
|
686
|
+
const responseData = event.response;
|
|
687
|
+
const responseId = responseData.id;
|
|
688
|
+
const response = this.#pendingResponses[responseId];
|
|
689
|
+
response.doneFut.resolve();
|
|
690
|
+
this.emit('response_done', response);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
#handleResponseOutputItemAdded(event: api_proto.ResponseOutputItemAddedEvent): void {
|
|
694
|
+
const responseId = event.response_id;
|
|
695
|
+
const response = this.#pendingResponses[responseId];
|
|
696
|
+
const itemData = event.item;
|
|
697
|
+
|
|
698
|
+
if (itemData.type !== 'message' && itemData.type !== 'function_call') {
|
|
699
|
+
throw new Error(`Unexpected item type: ${itemData.type}`);
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
let role: api_proto.Role;
|
|
703
|
+
if (itemData.type === 'function_call') {
|
|
704
|
+
role = 'assistant'; // function_call doesn't have a role field, defaulting it to assistant
|
|
705
|
+
} else {
|
|
706
|
+
role = itemData.role;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
const newOutput: RealtimeOutput = {
|
|
710
|
+
responseId: responseId,
|
|
711
|
+
itemId: itemData.id,
|
|
712
|
+
outputIndex: event.output_index,
|
|
713
|
+
type: itemData.type,
|
|
714
|
+
role: role,
|
|
715
|
+
content: [],
|
|
716
|
+
doneFut: new Future(),
|
|
717
|
+
};
|
|
718
|
+
response.output.push(newOutput);
|
|
719
|
+
this.emit('response_output_added', newOutput);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
#handleResponseOutputItemDone(event: api_proto.ResponseOutputItemDoneEvent): void {
|
|
723
|
+
const responseId = event.response_id;
|
|
724
|
+
const response = this.#pendingResponses[responseId];
|
|
725
|
+
const outputIndex = event.output_index;
|
|
726
|
+
const output = response.output[outputIndex];
|
|
727
|
+
|
|
728
|
+
if (output.type === 'function_call') {
|
|
729
|
+
if (!this.#fncCtx) {
|
|
730
|
+
this.#logger.error('function call received but no fncCtx is available');
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// parse the arguments and call the function inside the fnc_ctx
|
|
735
|
+
const item = event.item;
|
|
736
|
+
if (item.type !== 'function_call') {
|
|
737
|
+
throw new Error('Expected function_call item');
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
this.emit('function_call_started', {
|
|
741
|
+
callId: item.call_id,
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
const parsedArgs = JSON.parse(item.arguments);
|
|
745
|
+
|
|
746
|
+
this.#logger.debug(
|
|
747
|
+
`[Function Call ${item.call_id}] Executing ${item.name} with arguments ${parsedArgs}`,
|
|
748
|
+
);
|
|
749
|
+
|
|
750
|
+
this.#fncCtx[item.name].execute(parsedArgs).then(
|
|
751
|
+
(content) => {
|
|
752
|
+
this.#logger.debug(`[Function Call ${item.call_id}] ${item.name} returned ${content}`);
|
|
753
|
+
this.emit('function_call_completed', {
|
|
754
|
+
callId: item.call_id,
|
|
755
|
+
});
|
|
756
|
+
this.defaultConversation.item.create(
|
|
757
|
+
{
|
|
758
|
+
type: 'function_call_output',
|
|
759
|
+
call_id: item.call_id,
|
|
760
|
+
output: content,
|
|
761
|
+
},
|
|
762
|
+
output.itemId,
|
|
763
|
+
);
|
|
764
|
+
this.response.create();
|
|
765
|
+
},
|
|
766
|
+
(error) => {
|
|
767
|
+
this.#logger.error(`[Function Call ${item.call_id}] ${item.name} failed with ${error}`);
|
|
768
|
+
// TODO: send it back up as failed?
|
|
769
|
+
this.emit('function_call_failed', {
|
|
770
|
+
callId: item.call_id,
|
|
771
|
+
});
|
|
772
|
+
},
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
output.doneFut.resolve();
|
|
777
|
+
this.emit('response_output_done', output);
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
#handleResponseContentPartAdded(event: api_proto.ResponseContentPartAddedEvent): void {
|
|
781
|
+
const responseId = event.response_id;
|
|
782
|
+
const response = this.#pendingResponses[responseId];
|
|
783
|
+
const outputIndex = event.output_index;
|
|
784
|
+
const output = response.output[outputIndex];
|
|
785
|
+
|
|
786
|
+
const textStream = new AsyncIterableQueue<string>();
|
|
787
|
+
const audioStream = new AsyncIterableQueue<AudioFrame>();
|
|
788
|
+
|
|
789
|
+
const newContent: RealtimeContent = {
|
|
790
|
+
responseId: responseId,
|
|
791
|
+
itemId: event.item_id,
|
|
792
|
+
outputIndex: outputIndex,
|
|
793
|
+
contentIndex: event.content_index,
|
|
794
|
+
text: '',
|
|
795
|
+
audio: [],
|
|
796
|
+
textStream: textStream,
|
|
797
|
+
audioStream: audioStream,
|
|
798
|
+
toolCalls: [],
|
|
799
|
+
};
|
|
800
|
+
output.content.push(newContent);
|
|
801
|
+
this.emit('response_content_added', newContent);
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
#handleResponseContentPartDone(event: api_proto.ResponseContentPartDoneEvent): void {
|
|
805
|
+
const content = this.#getContent(event);
|
|
806
|
+
this.emit('response_content_done', content);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
810
|
+
#handleResponseTextDelta(event: api_proto.ResponseTextDeltaEvent): void {}
|
|
811
|
+
|
|
812
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
813
|
+
#handleResponseTextDone(event: api_proto.ResponseTextDoneEvent): void {}
|
|
814
|
+
|
|
815
|
+
#handleResponseAudioTranscriptDelta(event: api_proto.ResponseAudioTranscriptDeltaEvent): void {
|
|
816
|
+
const content = this.#getContent(event);
|
|
817
|
+
const transcript = event.delta;
|
|
818
|
+
content.text += transcript;
|
|
819
|
+
|
|
820
|
+
content.textStream.put(transcript);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
#handleResponseAudioTranscriptDone(event: api_proto.ResponseAudioTranscriptDoneEvent): void {
|
|
824
|
+
const content = this.#getContent(event);
|
|
825
|
+
content.textStream.close();
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
#handleResponseAudioDelta(event: api_proto.ResponseAudioDeltaEvent): void {
|
|
829
|
+
const content = this.#getContent(event);
|
|
830
|
+
const data = Buffer.from(event.delta, 'base64');
|
|
831
|
+
const audio = new AudioFrame(
|
|
832
|
+
new Int16Array(data.buffer),
|
|
833
|
+
api_proto.SAMPLE_RATE,
|
|
834
|
+
api_proto.NUM_CHANNELS,
|
|
835
|
+
data.length / 2,
|
|
836
|
+
);
|
|
837
|
+
content.audio.push(audio);
|
|
838
|
+
|
|
839
|
+
content.audioStream.put(audio);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
#handleResponseAudioDone(event: api_proto.ResponseAudioDoneEvent): void {
|
|
843
|
+
const content = this.#getContent(event);
|
|
844
|
+
content.audioStream.close();
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
#handleResponseFunctionCallArgumentsDelta(
|
|
848
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
849
|
+
event: api_proto.ResponseFunctionCallArgumentsDeltaEvent,
|
|
850
|
+
): void {}
|
|
851
|
+
|
|
852
|
+
#handleResponseFunctionCallArgumentsDone(
|
|
853
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
854
|
+
event: api_proto.ResponseFunctionCallArgumentsDoneEvent,
|
|
855
|
+
): void {}
|
|
856
|
+
|
|
857
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
858
|
+
#handleRateLimitsUpdated(event: api_proto.RateLimitsUpdatedEvent): void {}
|
|
859
|
+
}
|