@livekit/agents-plugin-openai 1.4.0 → 1.4.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/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/llm.cjs +2 -2
- package/dist/llm.cjs.map +1 -1
- package/dist/llm.js +2 -2
- package/dist/llm.js.map +1 -1
- package/dist/realtime/api_proto.cjs.map +1 -1
- package/dist/realtime/api_proto.d.cts +1 -1
- package/dist/realtime/api_proto.d.ts +1 -1
- package/dist/realtime/api_proto.d.ts.map +1 -1
- package/dist/realtime/api_proto.js.map +1 -1
- package/dist/stt.cjs +457 -13
- package/dist/stt.cjs.map +1 -1
- package/dist/stt.d.cts +29 -3
- package/dist/stt.d.ts +29 -3
- package/dist/stt.d.ts.map +1 -1
- package/dist/stt.js +460 -13
- package/dist/stt.js.map +1 -1
- package/dist/stt.test.cjs +59 -2
- package/dist/stt.test.cjs.map +1 -1
- package/dist/stt.test.js +61 -4
- package/dist/stt.test.js.map +1 -1
- package/dist/tts.cjs +3 -2
- package/dist/tts.cjs.map +1 -1
- package/dist/tts.d.ts.map +1 -1
- package/dist/tts.js +3 -2
- package/dist/tts.js.map +1 -1
- package/package.json +5 -5
- package/src/llm.ts +2 -2
- package/src/realtime/api_proto.ts +1 -1
- package/src/stt.test.ts +76 -4
- package/src/stt.ts +578 -11
- package/src/tts.ts +5 -2
package/src/stt.ts
CHANGED
|
@@ -1,10 +1,167 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
|
|
2
2
|
//
|
|
3
3
|
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
type APIConnectOptions,
|
|
6
|
+
Event as AsyncEvent,
|
|
7
|
+
type AudioBuffer,
|
|
8
|
+
AudioByteStream,
|
|
9
|
+
DEFAULT_API_CONNECT_OPTIONS,
|
|
10
|
+
type VAD,
|
|
11
|
+
VADEventType,
|
|
12
|
+
type VADStream,
|
|
13
|
+
mergeFrames,
|
|
14
|
+
normalizeLanguage,
|
|
15
|
+
stt,
|
|
16
|
+
} from '@livekit/agents';
|
|
5
17
|
import type { AudioFrame } from '@livekit/rtc-node';
|
|
6
18
|
import { OpenAI } from 'openai';
|
|
19
|
+
import { type MessageEvent, WebSocket } from 'ws';
|
|
20
|
+
import { z } from 'zod';
|
|
7
21
|
import type { GroqAudioModels, WhisperModels } from './models.js';
|
|
22
|
+
import type * as api_proto from './realtime/api_proto.js';
|
|
23
|
+
|
|
24
|
+
const REALTIME_SAMPLE_RATE = 24000;
|
|
25
|
+
const REALTIME_NUM_CHANNELS = 1;
|
|
26
|
+
const DEFAULT_REALTIME_MODEL = 'gpt-realtime-whisper';
|
|
27
|
+
const DEFAULT_REALTIME_TURN_DETECTION: api_proto.TurnDetectionType = {
|
|
28
|
+
type: 'server_vad',
|
|
29
|
+
threshold: 0.5,
|
|
30
|
+
prefix_padding_ms: 600,
|
|
31
|
+
silence_duration_ms: 350,
|
|
32
|
+
};
|
|
33
|
+
const REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION = new Set([DEFAULT_REALTIME_MODEL]);
|
|
34
|
+
|
|
35
|
+
const realtimeTranscriptionSpeechStartedEventSchema = z.object({
|
|
36
|
+
type: z.literal('input_audio_buffer.speech_started'),
|
|
37
|
+
item_id: z.string().optional(),
|
|
38
|
+
audio_start_ms: z.number().optional(),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const realtimeTranscriptionSpeechStoppedEventSchema = z.object({
|
|
42
|
+
type: z.literal('input_audio_buffer.speech_stopped'),
|
|
43
|
+
item_id: z.string().optional(),
|
|
44
|
+
audio_end_ms: z.number().optional(),
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
const realtimeTranscriptionDeltaEventSchema = z.object({
|
|
48
|
+
type: z.literal('conversation.item.input_audio_transcription.delta'),
|
|
49
|
+
item_id: z.string().optional(),
|
|
50
|
+
delta: z.string().optional(),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const realtimeTranscriptionCompletedEventSchema = z.object({
|
|
54
|
+
type: z.literal('conversation.item.input_audio_transcription.completed'),
|
|
55
|
+
item_id: z.string().optional(),
|
|
56
|
+
transcript: z.string().optional(),
|
|
57
|
+
usage: z
|
|
58
|
+
.object({
|
|
59
|
+
input_tokens: z.number().optional(),
|
|
60
|
+
output_tokens: z.number().optional(),
|
|
61
|
+
})
|
|
62
|
+
.passthrough()
|
|
63
|
+
.optional(),
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const realtimeTranscriptionErrorEventSchema = z.object({
|
|
67
|
+
type: z.literal('error'),
|
|
68
|
+
error: z
|
|
69
|
+
.object({
|
|
70
|
+
message: z.string().optional(),
|
|
71
|
+
})
|
|
72
|
+
.passthrough()
|
|
73
|
+
.optional(),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
const knownRealtimeTranscriptionServerEventSchema = z.discriminatedUnion('type', [
|
|
77
|
+
realtimeTranscriptionSpeechStartedEventSchema,
|
|
78
|
+
realtimeTranscriptionSpeechStoppedEventSchema,
|
|
79
|
+
realtimeTranscriptionDeltaEventSchema,
|
|
80
|
+
realtimeTranscriptionCompletedEventSchema,
|
|
81
|
+
realtimeTranscriptionErrorEventSchema,
|
|
82
|
+
]);
|
|
83
|
+
|
|
84
|
+
const knownRealtimeTranscriptionServerEventTypes = new Set([
|
|
85
|
+
'input_audio_buffer.speech_started',
|
|
86
|
+
'input_audio_buffer.speech_stopped',
|
|
87
|
+
'conversation.item.input_audio_transcription.delta',
|
|
88
|
+
'conversation.item.input_audio_transcription.completed',
|
|
89
|
+
'error',
|
|
90
|
+
]);
|
|
91
|
+
|
|
92
|
+
const unknownRealtimeTranscriptionServerEventSchema = z
|
|
93
|
+
.object({
|
|
94
|
+
type: z.string().refine((type) => !knownRealtimeTranscriptionServerEventTypes.has(type)),
|
|
95
|
+
})
|
|
96
|
+
.passthrough();
|
|
97
|
+
|
|
98
|
+
type RealtimeTranscriptionKnownServerEvent = z.infer<
|
|
99
|
+
typeof knownRealtimeTranscriptionServerEventSchema
|
|
100
|
+
>;
|
|
101
|
+
|
|
102
|
+
type RealtimeTranscriptionUnknownServerEvent = {
|
|
103
|
+
type: 'unknown';
|
|
104
|
+
event: z.infer<typeof unknownRealtimeTranscriptionServerEventSchema>;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
type RealtimeTranscriptionServerEvent =
|
|
108
|
+
| RealtimeTranscriptionKnownServerEvent
|
|
109
|
+
| RealtimeTranscriptionUnknownServerEvent;
|
|
110
|
+
|
|
111
|
+
function parseRealtimeTranscriptionServerEvent(data: string): RealtimeTranscriptionServerEvent {
|
|
112
|
+
const event = JSON.parse(data) as unknown;
|
|
113
|
+
const knownEvent = knownRealtimeTranscriptionServerEventSchema.safeParse(event);
|
|
114
|
+
if (knownEvent.success) {
|
|
115
|
+
return knownEvent.data;
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
type: 'unknown',
|
|
119
|
+
event: unknownRealtimeTranscriptionServerEventSchema.parse(event),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function _loadRealtimeVad(vad?: VAD): Promise<VAD> {
|
|
124
|
+
if (vad) return vad;
|
|
125
|
+
|
|
126
|
+
throw new Error(
|
|
127
|
+
'OpenAI realtime STT models without server-side endpointing must provide a VAD via the ' +
|
|
128
|
+
'`vad` option.',
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function _requiresRealtimeVad(
|
|
133
|
+
model: string,
|
|
134
|
+
turnDetection: api_proto.TurnDetectionType | null | undefined,
|
|
135
|
+
): boolean {
|
|
136
|
+
return turnDetection === null || REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function _normalizeRealtimeTurnDetection(
|
|
140
|
+
model: string,
|
|
141
|
+
turnDetection: api_proto.TurnDetectionType | null | undefined,
|
|
142
|
+
): api_proto.TurnDetectionType | null | undefined {
|
|
143
|
+
if (turnDetection !== null && REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model)) {
|
|
144
|
+
console.warn(
|
|
145
|
+
`Turn detection is not supported for ${model}; ignoring the provided turnDetection and ` +
|
|
146
|
+
'using plugin-side VAD commits instead.',
|
|
147
|
+
);
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
return turnDetection;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function _validateRealtimeVad(
|
|
154
|
+
model: string,
|
|
155
|
+
turnDetection: api_proto.TurnDetectionType | null | undefined,
|
|
156
|
+
vad: VAD | undefined,
|
|
157
|
+
): void {
|
|
158
|
+
if (_requiresRealtimeVad(model, turnDetection) && !vad) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
`A VAD instance is required for ${model}. Pass a VAD via the \`vad\` option so the ` +
|
|
161
|
+
'plugin can commit audio at end-of-speech.',
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
8
165
|
|
|
9
166
|
export interface STTOptions {
|
|
10
167
|
apiKey?: string;
|
|
@@ -14,24 +171,36 @@ export interface STTOptions {
|
|
|
14
171
|
model: WhisperModels | string;
|
|
15
172
|
baseURL?: string;
|
|
16
173
|
client?: OpenAI;
|
|
174
|
+
useRealtime: boolean;
|
|
175
|
+
turnDetection?: api_proto.TurnDetectionType | null;
|
|
176
|
+
noiseReductionType?: api_proto.NoiseReductionType;
|
|
177
|
+
vad?: VAD;
|
|
17
178
|
}
|
|
18
179
|
|
|
19
180
|
const defaultSTTOptions: STTOptions = {
|
|
20
181
|
apiKey: process.env.OPENAI_API_KEY,
|
|
21
182
|
language: 'en',
|
|
22
183
|
detectLanguage: false,
|
|
23
|
-
model:
|
|
184
|
+
model: DEFAULT_REALTIME_MODEL,
|
|
185
|
+
useRealtime: true,
|
|
24
186
|
};
|
|
25
187
|
|
|
188
|
+
type ResolvedSTTOptions = Omit<STTOptions, 'apiKey'> & { apiKey: string };
|
|
189
|
+
|
|
26
190
|
export class STT extends stt.STT {
|
|
27
|
-
#opts:
|
|
191
|
+
#opts: ResolvedSTTOptions;
|
|
28
192
|
#client: OpenAI;
|
|
193
|
+
#streams = new Set<SpeechStream>();
|
|
29
194
|
label = 'openai.STT';
|
|
30
195
|
|
|
31
196
|
get model(): string {
|
|
32
197
|
return this.#opts.model;
|
|
33
198
|
}
|
|
34
199
|
|
|
200
|
+
get turnDetection(): api_proto.TurnDetectionType | null | undefined {
|
|
201
|
+
return this.#opts.turnDetection;
|
|
202
|
+
}
|
|
203
|
+
|
|
35
204
|
get provider(): string {
|
|
36
205
|
try {
|
|
37
206
|
const url = new URL(this.#client.baseURL);
|
|
@@ -49,16 +218,40 @@ export class STT extends stt.STT {
|
|
|
49
218
|
* `OPENAI_API_KEY` environment variable.
|
|
50
219
|
*/
|
|
51
220
|
constructor(opts: Partial<STTOptions> = defaultSTTOptions) {
|
|
52
|
-
|
|
221
|
+
const useRealtime = opts.useRealtime ?? defaultSTTOptions.useRealtime;
|
|
222
|
+
const model = opts.model ?? (useRealtime ? DEFAULT_REALTIME_MODEL : 'whisper-1');
|
|
223
|
+
super({
|
|
224
|
+
streaming: useRealtime,
|
|
225
|
+
interimResults: useRealtime,
|
|
226
|
+
alignedTranscript: false,
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;
|
|
230
|
+
if (apiKey === undefined) {
|
|
231
|
+
throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const turnDetection = _normalizeRealtimeTurnDetection(
|
|
235
|
+
model,
|
|
236
|
+
opts.turnDetection !== undefined
|
|
237
|
+
? opts.turnDetection
|
|
238
|
+
: model === DEFAULT_REALTIME_MODEL
|
|
239
|
+
? null
|
|
240
|
+
: DEFAULT_REALTIME_TURN_DETECTION,
|
|
241
|
+
);
|
|
242
|
+
if (useRealtime) {
|
|
243
|
+
_validateRealtimeVad(model, turnDetection, opts.vad);
|
|
244
|
+
}
|
|
53
245
|
|
|
54
246
|
this.#opts = {
|
|
55
247
|
...defaultSTTOptions,
|
|
56
248
|
...opts,
|
|
249
|
+
apiKey,
|
|
57
250
|
language: normalizeLanguage(opts.language ?? defaultSTTOptions.language),
|
|
251
|
+
model,
|
|
252
|
+
useRealtime,
|
|
253
|
+
turnDetection,
|
|
58
254
|
};
|
|
59
|
-
if (this.#opts.apiKey === undefined) {
|
|
60
|
-
throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');
|
|
61
|
-
}
|
|
62
255
|
|
|
63
256
|
this.#client =
|
|
64
257
|
this.#opts.client ||
|
|
@@ -94,6 +287,7 @@ export class STT extends stt.STT {
|
|
|
94
287
|
model: 'whisper-large-v3-turbo',
|
|
95
288
|
baseURL: 'https://api.groq.com/openai/v1',
|
|
96
289
|
...opts,
|
|
290
|
+
useRealtime: false,
|
|
97
291
|
});
|
|
98
292
|
}
|
|
99
293
|
|
|
@@ -125,10 +319,11 @@ export class STT extends stt.STT {
|
|
|
125
319
|
model: 'whisper-large-v3-turbo',
|
|
126
320
|
baseURL: 'https://oai.endpoints.kepler.ai.cloud.ovh.net/v1',
|
|
127
321
|
...opts,
|
|
322
|
+
useRealtime: false,
|
|
128
323
|
});
|
|
129
324
|
}
|
|
130
325
|
|
|
131
|
-
#sanitizeOptions(language?: string):
|
|
326
|
+
#sanitizeOptions(language?: string): ResolvedSTTOptions {
|
|
132
327
|
if (language) {
|
|
133
328
|
return { ...this.#opts, language: normalizeLanguage(language) };
|
|
134
329
|
} else {
|
|
@@ -191,8 +386,380 @@ export class STT extends stt.STT {
|
|
|
191
386
|
};
|
|
192
387
|
}
|
|
193
388
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
389
|
+
updateOptions(opts: Partial<STTOptions>): void {
|
|
390
|
+
const useRealtime = opts.useRealtime ?? this.#opts.useRealtime;
|
|
391
|
+
const model = opts.model ?? this.#opts.model;
|
|
392
|
+
const turnDetection = _normalizeRealtimeTurnDetection(
|
|
393
|
+
model,
|
|
394
|
+
opts.turnDetection !== undefined
|
|
395
|
+
? opts.turnDetection
|
|
396
|
+
: opts.model === DEFAULT_REALTIME_MODEL
|
|
397
|
+
? null
|
|
398
|
+
: this.#opts.turnDetection,
|
|
399
|
+
);
|
|
400
|
+
if (useRealtime) {
|
|
401
|
+
_validateRealtimeVad(model, turnDetection, opts.vad ?? this.#opts.vad);
|
|
402
|
+
}
|
|
403
|
+
this.#opts = {
|
|
404
|
+
...this.#opts,
|
|
405
|
+
...opts,
|
|
406
|
+
apiKey: opts.apiKey ?? this.#opts.apiKey,
|
|
407
|
+
language: opts.language ? normalizeLanguage(opts.language) : this.#opts.language,
|
|
408
|
+
model,
|
|
409
|
+
useRealtime,
|
|
410
|
+
turnDetection,
|
|
411
|
+
};
|
|
412
|
+
this.updateCapabilities({
|
|
413
|
+
streaming: useRealtime,
|
|
414
|
+
interimResults: useRealtime,
|
|
415
|
+
});
|
|
416
|
+
for (const stream of this.#streams) {
|
|
417
|
+
if (stream.isClosed) {
|
|
418
|
+
this.#streams.delete(stream);
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
stream.updateOptions(this.#opts);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
stream(options: { connOptions?: APIConnectOptions } = {}): stt.SpeechStream {
|
|
426
|
+
if (!this.#opts.useRealtime) {
|
|
427
|
+
throw new Error('Streaming is not supported on OpenAI STT unless useRealtime is enabled');
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const stream = new SpeechStream(
|
|
431
|
+
this,
|
|
432
|
+
{ ...this.#opts },
|
|
433
|
+
options.connOptions ?? DEFAULT_API_CONNECT_OPTIONS,
|
|
434
|
+
() => this.#streams.delete(stream),
|
|
435
|
+
);
|
|
436
|
+
this.#streams.add(stream);
|
|
437
|
+
return stream;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
override async close(): Promise<void> {
|
|
441
|
+
for (const stream of this.#streams) {
|
|
442
|
+
stream.close();
|
|
443
|
+
}
|
|
444
|
+
this.#streams.clear();
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export class SpeechStream extends stt.SpeechStream {
|
|
449
|
+
label = 'openai.SpeechStream';
|
|
450
|
+
#options: ResolvedSTTOptions;
|
|
451
|
+
#onClose: () => void;
|
|
452
|
+
#targetTranscript = '';
|
|
453
|
+
#currentItemId = '';
|
|
454
|
+
#itemAudioTiming = new Map<string, { startMs?: number; endMs?: number }>();
|
|
455
|
+
#speaking = false;
|
|
456
|
+
|
|
457
|
+
constructor(
|
|
458
|
+
stt: STT,
|
|
459
|
+
options: ResolvedSTTOptions,
|
|
460
|
+
connOptions?: APIConnectOptions,
|
|
461
|
+
onClose: () => void = () => {},
|
|
462
|
+
) {
|
|
463
|
+
super(stt, REALTIME_SAMPLE_RATE, connOptions);
|
|
464
|
+
this.#options = options;
|
|
465
|
+
this.#onClose = onClose;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
updateOptions(options: ResolvedSTTOptions): void {
|
|
469
|
+
this.#options = { ...options };
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
get isClosed(): boolean {
|
|
473
|
+
return this.closed;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
override close(): void {
|
|
477
|
+
super.close();
|
|
478
|
+
this.#onClose();
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
protected async run(): Promise<void> {
|
|
482
|
+
_validateRealtimeVad(this.#options.model, this.#options.turnDetection, this.#options.vad);
|
|
483
|
+
const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection)
|
|
484
|
+
? await _loadRealtimeVad(this.#options.vad)
|
|
485
|
+
: undefined;
|
|
486
|
+
|
|
487
|
+
if (vad) {
|
|
488
|
+
this.#options.vad = vad;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const vadStream = vad?.stream();
|
|
492
|
+
const ws = await this.#connect();
|
|
493
|
+
const abort = () => {
|
|
494
|
+
if (ws.readyState < WebSocket.CLOSING) {
|
|
495
|
+
ws.close();
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
this.abortSignal.addEventListener('abort', abort, { once: true });
|
|
499
|
+
|
|
500
|
+
try {
|
|
501
|
+
ws.send(JSON.stringify(this.#sessionUpdateEvent()));
|
|
502
|
+
const tasks = [this.#forwardInput(ws, vadStream), this.#forwardEvents(ws)];
|
|
503
|
+
if (vadStream) {
|
|
504
|
+
tasks.push(this.#forwardVadEvents(ws, vadStream));
|
|
505
|
+
}
|
|
506
|
+
await Promise.all(tasks);
|
|
507
|
+
} finally {
|
|
508
|
+
this.abortSignal.removeEventListener('abort', abort);
|
|
509
|
+
vadStream?.close();
|
|
510
|
+
if (ws.readyState < WebSocket.CLOSING) {
|
|
511
|
+
ws.close();
|
|
512
|
+
}
|
|
513
|
+
this.#onClose();
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async #connect(): Promise<WebSocket> {
|
|
518
|
+
const ws = new WebSocket(this.#realtimeUrl(), {
|
|
519
|
+
headers: {
|
|
520
|
+
Authorization: `Bearer ${this.#options.apiKey}`,
|
|
521
|
+
},
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
await new Promise<void>((resolve, reject) => {
|
|
525
|
+
ws.onopen = () => resolve();
|
|
526
|
+
ws.onerror = (error) => reject(new Error(error.message));
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
return ws;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
#realtimeUrl(): string {
|
|
533
|
+
const url = new URL(this.#options.baseURL || 'https://api.openai.com/v1');
|
|
534
|
+
if (url.protocol === 'https:') {
|
|
535
|
+
url.protocol = 'wss:';
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const path = url.pathname.replace(/\/$/, '');
|
|
539
|
+
if (!path || path === '/v1') {
|
|
540
|
+
url.pathname = `${path}/realtime`;
|
|
541
|
+
} else if (!path.endsWith('/realtime')) {
|
|
542
|
+
url.pathname = `${path}/realtime`;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
url.searchParams.set('intent', 'transcription');
|
|
546
|
+
return url.toString();
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
#sessionUpdateEvent(): api_proto.SessionUpdateEvent {
|
|
550
|
+
const transcription: api_proto.InputAudioTranscription = {
|
|
551
|
+
model: this.#options.model,
|
|
552
|
+
...(this.#options.prompt ? { prompt: this.#options.prompt } : {}),
|
|
553
|
+
...(!this.#options.detectLanguage && this.#options.language
|
|
554
|
+
? { language: this.#options.language }
|
|
555
|
+
: {}),
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
return {
|
|
559
|
+
type: 'session.update',
|
|
560
|
+
session: {
|
|
561
|
+
type: 'transcription',
|
|
562
|
+
audio: {
|
|
563
|
+
input: {
|
|
564
|
+
format: {
|
|
565
|
+
type: 'audio/pcm',
|
|
566
|
+
rate: REALTIME_SAMPLE_RATE,
|
|
567
|
+
},
|
|
568
|
+
transcription,
|
|
569
|
+
turn_detection: this.#options.turnDetection,
|
|
570
|
+
...(this.#options.noiseReductionType
|
|
571
|
+
? { noise_reduction: { type: this.#options.noiseReductionType } }
|
|
572
|
+
: {}),
|
|
573
|
+
},
|
|
574
|
+
},
|
|
575
|
+
},
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
async #forwardInput(ws: WebSocket, vadStream?: VADStream): Promise<void> {
|
|
580
|
+
const audioStream = new AudioByteStream(
|
|
581
|
+
REALTIME_SAMPLE_RATE,
|
|
582
|
+
REALTIME_NUM_CHANNELS,
|
|
583
|
+
REALTIME_SAMPLE_RATE / 20,
|
|
584
|
+
);
|
|
585
|
+
|
|
586
|
+
for await (const item of this.input) {
|
|
587
|
+
if (item === SpeechStream.FLUSH_SENTINEL) {
|
|
588
|
+
for (const frame of audioStream.flush()) {
|
|
589
|
+
this.#sendAudioFrame(ws, frame);
|
|
590
|
+
}
|
|
591
|
+
if (this.#options.turnDetection === null) {
|
|
592
|
+
ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
|
|
593
|
+
}
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
vadStream?.pushFrame(item);
|
|
598
|
+
for (const frame of audioStream.write(item.data.buffer as ArrayBuffer)) {
|
|
599
|
+
this.#sendAudioFrame(ws, frame);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
vadStream?.endInput();
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
async #forwardVadEvents(ws: WebSocket, vadStream: VADStream): Promise<void> {
|
|
606
|
+
for await (const event of vadStream) {
|
|
607
|
+
if (event.type === VADEventType.START_OF_SPEECH) {
|
|
608
|
+
this.#emitStartOfSpeech();
|
|
609
|
+
} else if (
|
|
610
|
+
event.type === VADEventType.END_OF_SPEECH &&
|
|
611
|
+
this.#options.turnDetection === null
|
|
612
|
+
) {
|
|
613
|
+
ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
async #forwardEvents(ws: WebSocket): Promise<void> {
|
|
619
|
+
for await (const data of this.#messages(ws)) {
|
|
620
|
+
const event = parseRealtimeTranscriptionServerEvent(data);
|
|
621
|
+
switch (event.type) {
|
|
622
|
+
case 'input_audio_buffer.speech_started': {
|
|
623
|
+
const itemId = event.item_id ?? '';
|
|
624
|
+
this.#currentItemId = itemId;
|
|
625
|
+
this.#itemAudioTiming.set(itemId, {
|
|
626
|
+
startMs: event.audio_start_ms,
|
|
627
|
+
});
|
|
628
|
+
this.#emitStartOfSpeech();
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
case 'input_audio_buffer.speech_stopped': {
|
|
632
|
+
const itemId = event.item_id ?? this.#currentItemId;
|
|
633
|
+
const timing = this.#itemAudioTiming.get(itemId) ?? {};
|
|
634
|
+
timing.endMs = event.audio_end_ms;
|
|
635
|
+
this.#itemAudioTiming.set(itemId, timing);
|
|
636
|
+
break;
|
|
637
|
+
}
|
|
638
|
+
case 'conversation.item.input_audio_transcription.delta':
|
|
639
|
+
this.#currentItemId = event.item_id ?? this.#currentItemId;
|
|
640
|
+
if (event.delta) {
|
|
641
|
+
this.#targetTranscript += event.delta;
|
|
642
|
+
this.#emitStartOfSpeech();
|
|
643
|
+
this.queue.put(this.#speechEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT));
|
|
644
|
+
}
|
|
645
|
+
break;
|
|
646
|
+
case 'conversation.item.input_audio_transcription.completed': {
|
|
647
|
+
const itemId = event.item_id ?? this.#currentItemId;
|
|
648
|
+
const transcript = event.transcript ?? '';
|
|
649
|
+
if (transcript) {
|
|
650
|
+
this.#targetTranscript = transcript;
|
|
651
|
+
this.#emitStartOfSpeech();
|
|
652
|
+
this.queue.put(this.#speechEvent(stt.SpeechEventType.FINAL_TRANSCRIPT, itemId));
|
|
653
|
+
}
|
|
654
|
+
this.#emitRecognitionUsage(event, itemId);
|
|
655
|
+
this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });
|
|
656
|
+
this.#targetTranscript = '';
|
|
657
|
+
this.#currentItemId = '';
|
|
658
|
+
this.#speaking = false;
|
|
659
|
+
break;
|
|
660
|
+
}
|
|
661
|
+
case 'error': {
|
|
662
|
+
throw new Error(event.error?.message || 'OpenAI realtime transcription error');
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
async *#messages(ws: WebSocket): AsyncGenerator<string> {
|
|
669
|
+
const queue: string[] = [];
|
|
670
|
+
const messageEvent = new AsyncEvent();
|
|
671
|
+
let closed = false;
|
|
672
|
+
let error: Error | undefined;
|
|
673
|
+
|
|
674
|
+
ws.onmessage = (message: MessageEvent) => {
|
|
675
|
+
queue.push(
|
|
676
|
+
typeof message.data === 'string'
|
|
677
|
+
? message.data
|
|
678
|
+
: Buffer.from(message.data as ArrayBuffer).toString(),
|
|
679
|
+
);
|
|
680
|
+
messageEvent.set();
|
|
681
|
+
};
|
|
682
|
+
ws.onclose = () => {
|
|
683
|
+
closed = true;
|
|
684
|
+
messageEvent.set();
|
|
685
|
+
};
|
|
686
|
+
ws.onerror = (event) => {
|
|
687
|
+
error = new Error(event.message);
|
|
688
|
+
closed = true;
|
|
689
|
+
messageEvent.set();
|
|
690
|
+
};
|
|
691
|
+
|
|
692
|
+
while (!closed || queue.length > 0) {
|
|
693
|
+
if (queue.length > 0) {
|
|
694
|
+
yield queue.shift()!;
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
messageEvent.clear();
|
|
699
|
+
if (closed || queue.length > 0) continue;
|
|
700
|
+
await messageEvent.wait();
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (error) throw error;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
#sendAudioFrame(ws: WebSocket, frame: AudioFrame): void {
|
|
707
|
+
if (frame.data.byteLength === 0 || frame.samplesPerChannel === 0) {
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
ws.send(
|
|
712
|
+
JSON.stringify({
|
|
713
|
+
type: 'input_audio_buffer.append',
|
|
714
|
+
audio: Buffer.from(
|
|
715
|
+
frame.data.buffer,
|
|
716
|
+
frame.data.byteOffset,
|
|
717
|
+
frame.data.byteLength,
|
|
718
|
+
).toString('base64'),
|
|
719
|
+
}),
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
#emitStartOfSpeech(): void {
|
|
724
|
+
if (this.#speaking) return;
|
|
725
|
+
this.#speaking = true;
|
|
726
|
+
this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
#speechEvent(type: stt.SpeechEventType, requestId = this.#currentItemId): stt.SpeechEvent {
|
|
730
|
+
return {
|
|
731
|
+
type,
|
|
732
|
+
requestId,
|
|
733
|
+
alternatives: [
|
|
734
|
+
{
|
|
735
|
+
text: this.#targetTranscript,
|
|
736
|
+
language: normalizeLanguage(this.#options.language || ''),
|
|
737
|
+
startTime: 0,
|
|
738
|
+
endTime: 0,
|
|
739
|
+
confidence: 1,
|
|
740
|
+
},
|
|
741
|
+
],
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
#emitRecognitionUsage(
|
|
746
|
+
event: z.infer<typeof realtimeTranscriptionCompletedEventSchema>,
|
|
747
|
+
itemId: string,
|
|
748
|
+
): void {
|
|
749
|
+
const timing = this.#itemAudioTiming.get(itemId);
|
|
750
|
+
this.#itemAudioTiming.delete(itemId);
|
|
751
|
+
const audioDuration =
|
|
752
|
+
timing?.startMs !== undefined && timing.endMs !== undefined && timing.endMs > timing.startMs
|
|
753
|
+
? (timing.endMs - timing.startMs) / 1000
|
|
754
|
+
: 0;
|
|
755
|
+
this.queue.put({
|
|
756
|
+
type: stt.SpeechEventType.RECOGNITION_USAGE,
|
|
757
|
+
requestId: itemId,
|
|
758
|
+
recognitionUsage: {
|
|
759
|
+
audioDuration,
|
|
760
|
+
inputTokens: event.usage?.input_tokens,
|
|
761
|
+
outputTokens: event.usage?.output_tokens,
|
|
762
|
+
},
|
|
763
|
+
});
|
|
197
764
|
}
|
|
198
765
|
}
|
package/src/tts.ts
CHANGED
|
@@ -77,6 +77,9 @@ export class TTS extends tts.TTS {
|
|
|
77
77
|
connOptions?: APIConnectOptions,
|
|
78
78
|
abortSignal?: AbortSignal,
|
|
79
79
|
): ChunkedStream {
|
|
80
|
+
const signal = abortSignal
|
|
81
|
+
? AbortSignal.any([abortSignal, this.abortController.signal])
|
|
82
|
+
: this.abortController.signal;
|
|
80
83
|
return new ChunkedStream(
|
|
81
84
|
this,
|
|
82
85
|
text,
|
|
@@ -89,10 +92,10 @@ export class TTS extends tts.TTS {
|
|
|
89
92
|
response_format: 'pcm',
|
|
90
93
|
speed: this.#opts.speed,
|
|
91
94
|
},
|
|
92
|
-
{ signal
|
|
95
|
+
{ signal },
|
|
93
96
|
),
|
|
94
97
|
connOptions,
|
|
95
|
-
|
|
98
|
+
signal,
|
|
96
99
|
);
|
|
97
100
|
}
|
|
98
101
|
|