@livekit/agents-plugin-openai 1.4.4 → 1.4.5
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/realtime/api_proto.cjs.map +1 -1
- package/dist/realtime/api_proto.d.cts +8 -2
- package/dist/realtime/api_proto.d.ts +8 -2
- package/dist/realtime/api_proto.d.ts.map +1 -1
- package/dist/realtime/api_proto.js.map +1 -1
- package/dist/realtime/realtime_model.cjs +85 -9
- package/dist/realtime/realtime_model.cjs.map +1 -1
- package/dist/realtime/realtime_model.d.cts +5 -0
- package/dist/realtime/realtime_model.d.ts +5 -0
- package/dist/realtime/realtime_model.d.ts.map +1 -1
- package/dist/realtime/realtime_model.js +85 -9
- package/dist/realtime/realtime_model.js.map +1 -1
- package/dist/realtime/realtime_model.test.cjs +236 -9
- package/dist/realtime/realtime_model.test.cjs.map +1 -1
- package/dist/realtime/realtime_model.test.js +237 -10
- package/dist/realtime/realtime_model.test.js.map +1 -1
- package/dist/responses/llm.cjs +1 -1
- package/dist/responses/llm.cjs.map +1 -1
- package/dist/responses/llm.js +1 -1
- package/dist/responses/llm.js.map +1 -1
- package/dist/ws/llm.cjs +1 -1
- package/dist/ws/llm.cjs.map +1 -1
- package/dist/ws/llm.js +1 -1
- package/dist/ws/llm.js.map +1 -1
- package/package.json +7 -7
- package/src/realtime/api_proto.ts +9 -0
- package/src/realtime/realtime_model.test.ts +321 -12
- package/src/realtime/realtime_model.ts +101 -12
- package/src/responses/llm.ts +1 -1
- package/src/ws/llm.ts +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2025 LiveKit, Inc.
|
|
2
2
|
//
|
|
3
3
|
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
import { llm } from '@livekit/agents';
|
|
4
|
+
import { APIError, Future, Task, llm, stream } from '@livekit/agents';
|
|
5
5
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
6
6
|
import type * as api_proto from './api_proto.js';
|
|
7
7
|
import {
|
|
@@ -18,6 +18,19 @@ type RealtimeSessionInternals = {
|
|
|
18
18
|
textModeRecoveryRetries: number;
|
|
19
19
|
};
|
|
20
20
|
|
|
21
|
+
type ResponseDoneSessionInternals = {
|
|
22
|
+
handleResponseDone: (event: api_proto.ResponseDoneEvent) => void;
|
|
23
|
+
on: (event: 'error', listener: (error: llm.RealtimeModelError) => void) => void;
|
|
24
|
+
currentGeneration: {
|
|
25
|
+
messageChannel: stream.StreamChannel<llm.MessageGeneration>;
|
|
26
|
+
functionChannel: stream.StreamChannel<llm.FunctionCall>;
|
|
27
|
+
messages: Map<string, never>;
|
|
28
|
+
_doneFut: Future;
|
|
29
|
+
_createdTimestamp: number;
|
|
30
|
+
_firstTokenTimestamp?: number;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
|
|
21
34
|
function createSessionForTest(): RealtimeSessionInternals {
|
|
22
35
|
const session = Object.create(RealtimeSession.prototype) as RealtimeSessionInternals;
|
|
23
36
|
session.responseCreatedFutures = {};
|
|
@@ -26,6 +39,15 @@ function createSessionForTest(): RealtimeSessionInternals {
|
|
|
26
39
|
return session;
|
|
27
40
|
}
|
|
28
41
|
|
|
42
|
+
function stubTaskRuntime(): void {
|
|
43
|
+
// Prevent background realtime tasks from opening network connections in unit tests.
|
|
44
|
+
vi.spyOn(Task, 'from').mockReturnValue({
|
|
45
|
+
cancel: vi.fn(),
|
|
46
|
+
done: true,
|
|
47
|
+
result: Promise.resolve(undefined),
|
|
48
|
+
} as unknown as Task<void>);
|
|
49
|
+
}
|
|
50
|
+
|
|
29
51
|
describe('RealtimeSession.generateReply', () => {
|
|
30
52
|
it('cancels an in-flight response when aborted before response.created', async () => {
|
|
31
53
|
const session = createSessionForTest();
|
|
@@ -43,6 +65,304 @@ describe('RealtimeSession.generateReply', () => {
|
|
|
43
65
|
});
|
|
44
66
|
});
|
|
45
67
|
|
|
68
|
+
describe('RealtimeSession response.done status handling', () => {
|
|
69
|
+
afterEach(() => {
|
|
70
|
+
vi.restoreAllMocks();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
function createResponseDoneSession(): ResponseDoneSessionInternals {
|
|
74
|
+
stubTaskRuntime();
|
|
75
|
+
|
|
76
|
+
const model = new RealtimeModel({ apiKey: 'test-key' });
|
|
77
|
+
const session = model.session() as unknown as ResponseDoneSessionInternals;
|
|
78
|
+
session.currentGeneration = {
|
|
79
|
+
messageChannel: stream.createStreamChannel<llm.MessageGeneration>(),
|
|
80
|
+
functionChannel: stream.createStreamChannel<llm.FunctionCall>(),
|
|
81
|
+
messages: new Map<string, never>(),
|
|
82
|
+
_doneFut: new Future(),
|
|
83
|
+
_createdTimestamp: Date.now(),
|
|
84
|
+
};
|
|
85
|
+
return session;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
it('emits a recoverable APIError when response.done reports failed', () => {
|
|
89
|
+
const session = createResponseDoneSession();
|
|
90
|
+
const errors: llm.RealtimeModelError[] = [];
|
|
91
|
+
session.on('error', (error) => errors.push(error));
|
|
92
|
+
|
|
93
|
+
session.handleResponseDone({
|
|
94
|
+
type: 'response.done',
|
|
95
|
+
event_id: 'evt_response_failed',
|
|
96
|
+
response: {
|
|
97
|
+
id: 'resp_failed',
|
|
98
|
+
object: 'realtime.response',
|
|
99
|
+
status: 'failed',
|
|
100
|
+
status_details: {
|
|
101
|
+
type: 'failed',
|
|
102
|
+
error: {
|
|
103
|
+
code: 'rate_limit_exceeded',
|
|
104
|
+
message: 'rate limited',
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
output: [],
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
expect(errors).toHaveLength(1);
|
|
112
|
+
expect(errors[0]!.recoverable).toBe(true);
|
|
113
|
+
expect(errors[0]!.error).toBeInstanceOf(APIError);
|
|
114
|
+
expect(errors[0]!.error.message).toBe(
|
|
115
|
+
'OpenAI Realtime API response failed with error type: unknown',
|
|
116
|
+
);
|
|
117
|
+
expect((errors[0]!.error as APIError).body).toEqual({
|
|
118
|
+
code: 'rate_limit_exceeded',
|
|
119
|
+
message: 'rate limited',
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
describe('RealtimeSession input_audio_transcription delta handling', () => {
|
|
125
|
+
type TranscriptionInternals = {
|
|
126
|
+
handleConversationItemInputAudioTranscriptionDelta: (
|
|
127
|
+
ev: api_proto.ConversationItemInputAudioTranscriptionDeltaEvent,
|
|
128
|
+
) => void;
|
|
129
|
+
handleConversationItemInputAudioTranscriptionCompleted: (
|
|
130
|
+
ev: api_proto.ConversationItemInputAudioTranscriptionCompletedEvent,
|
|
131
|
+
) => void;
|
|
132
|
+
finalizePartialOnTranscriptionFailure: (itemId: string, contentIndex: number) => void;
|
|
133
|
+
handleConversationItemDeleted: (ev: api_proto.ConversationItemDeletedEvent) => void;
|
|
134
|
+
inputTranscriptAccumulators: Map<string, Map<number, string>>;
|
|
135
|
+
audioCapableItemIds: Set<string>;
|
|
136
|
+
itemDeleteFutures: Record<string, never>;
|
|
137
|
+
remoteChatCtx: {
|
|
138
|
+
get: (id: string) => { item: llm.ChatMessage } | undefined;
|
|
139
|
+
delete: (id: string) => void;
|
|
140
|
+
};
|
|
141
|
+
on: (event: string, listener: (payload: llm.InputTranscriptionCompleted) => void) => void;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
function createTranscriptSession(opts?: {
|
|
145
|
+
chatItems?: Record<string, llm.ChatMessage>;
|
|
146
|
+
}): TranscriptionInternals {
|
|
147
|
+
const session = Object.create(RealtimeSession.prototype) as TranscriptionInternals;
|
|
148
|
+
session.inputTranscriptAccumulators = new Map<string, Map<number, string>>();
|
|
149
|
+
session.audioCapableItemIds = new Set<string>();
|
|
150
|
+
session.itemDeleteFutures = {};
|
|
151
|
+
const chatItems = new Map<string, llm.ChatMessage>(Object.entries(opts?.chatItems ?? {}));
|
|
152
|
+
session.remoteChatCtx = {
|
|
153
|
+
get: (id) => {
|
|
154
|
+
const item = chatItems.get(id);
|
|
155
|
+
return item ? { item } : undefined;
|
|
156
|
+
},
|
|
157
|
+
delete: (id) => {
|
|
158
|
+
chatItems.delete(id);
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
return session;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function delta(
|
|
165
|
+
item_id: string,
|
|
166
|
+
delta: string,
|
|
167
|
+
content_index = 0,
|
|
168
|
+
): api_proto.ConversationItemInputAudioTranscriptionDeltaEvent {
|
|
169
|
+
return {
|
|
170
|
+
type: 'conversation.item.input_audio_transcription.delta',
|
|
171
|
+
event_id: `evt_${item_id}_${delta}_${content_index}`,
|
|
172
|
+
item_id,
|
|
173
|
+
content_index,
|
|
174
|
+
delta,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function completed(
|
|
179
|
+
item_id: string,
|
|
180
|
+
transcript: string,
|
|
181
|
+
content_index = 0,
|
|
182
|
+
): api_proto.ConversationItemInputAudioTranscriptionCompletedEvent {
|
|
183
|
+
return {
|
|
184
|
+
type: 'conversation.item.input_audio_transcription.completed',
|
|
185
|
+
event_id: `evt_${item_id}_done`,
|
|
186
|
+
item_id,
|
|
187
|
+
content_index,
|
|
188
|
+
transcript,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
it('accumulates partial transcripts across delta events for the same item_id', () => {
|
|
193
|
+
const session = createTranscriptSession();
|
|
194
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
195
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
196
|
+
|
|
197
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'Hello'));
|
|
198
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', ', world'));
|
|
199
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', '!'));
|
|
200
|
+
|
|
201
|
+
expect(emissions).toEqual([
|
|
202
|
+
{ itemId: 'item_a', transcript: 'Hello', isFinal: false },
|
|
203
|
+
{ itemId: 'item_a', transcript: 'Hello, world', isFinal: false },
|
|
204
|
+
{ itemId: 'item_a', transcript: 'Hello, world!', isFinal: false },
|
|
205
|
+
]);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('keeps accumulators isolated across concurrent item_ids', () => {
|
|
209
|
+
const session = createTranscriptSession();
|
|
210
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
211
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
212
|
+
|
|
213
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'Aaa'));
|
|
214
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_b', 'Bbb'));
|
|
215
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'Aaa'));
|
|
216
|
+
|
|
217
|
+
expect(emissions).toEqual([
|
|
218
|
+
{ itemId: 'item_a', transcript: 'Aaa', isFinal: false },
|
|
219
|
+
{ itemId: 'item_b', transcript: 'Bbb', isFinal: false },
|
|
220
|
+
{ itemId: 'item_a', transcript: 'AaaAaa', isFinal: false },
|
|
221
|
+
]);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it('keeps accumulators isolated across content_index within the same item_id', () => {
|
|
225
|
+
const session = createTranscriptSession();
|
|
226
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
227
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
228
|
+
|
|
229
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'idx0-', 0));
|
|
230
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'idx1-', 1));
|
|
231
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'more0', 0));
|
|
232
|
+
|
|
233
|
+
expect(emissions).toEqual([
|
|
234
|
+
{ itemId: 'item_a', transcript: 'idx0-', isFinal: false },
|
|
235
|
+
{ itemId: 'item_a', transcript: 'idx1-', isFinal: false },
|
|
236
|
+
{ itemId: 'item_a', transcript: 'idx0-more0', isFinal: false },
|
|
237
|
+
]);
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it('clears the accumulator on .completed so a subsequent delta does not inherit prior state', () => {
|
|
241
|
+
const session = createTranscriptSession({
|
|
242
|
+
chatItems: { item_a: new llm.ChatMessage({ role: 'user', content: '', id: 'item_a' }) },
|
|
243
|
+
});
|
|
244
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
245
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
246
|
+
|
|
247
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'first turn '));
|
|
248
|
+
session.handleConversationItemInputAudioTranscriptionCompleted(
|
|
249
|
+
completed('item_a', 'first turn complete.'),
|
|
250
|
+
);
|
|
251
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'second'));
|
|
252
|
+
|
|
253
|
+
expect(session.inputTranscriptAccumulators.get('item_a')?.get(0)).toBe('second');
|
|
254
|
+
expect(emissions).toEqual([
|
|
255
|
+
{ itemId: 'item_a', transcript: 'first turn ', isFinal: false },
|
|
256
|
+
{ itemId: 'item_a', transcript: 'first turn complete.', isFinal: true },
|
|
257
|
+
{ itemId: 'item_a', transcript: 'second', isFinal: false },
|
|
258
|
+
]);
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
it('pushes the final transcript onto the matching ChatMessage exactly once on .completed', () => {
|
|
262
|
+
const chatMessage = new llm.ChatMessage({ role: 'user', content: '', id: 'item_a' });
|
|
263
|
+
const session = createTranscriptSession({ chatItems: { item_a: chatMessage } });
|
|
264
|
+
|
|
265
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'partial-only'));
|
|
266
|
+
expect(chatMessage.content).toEqual(['']);
|
|
267
|
+
|
|
268
|
+
session.handleConversationItemInputAudioTranscriptionCompleted(completed('item_a', 'final.'));
|
|
269
|
+
expect(chatMessage.content).toEqual(['', 'final.']);
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
it('emits isFinal:true on .completed even when remoteChatCtx has no matching item', () => {
|
|
273
|
+
const session = createTranscriptSession();
|
|
274
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
275
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
276
|
+
|
|
277
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'partial'));
|
|
278
|
+
session.handleConversationItemInputAudioTranscriptionCompleted(completed('item_a', 'final.'));
|
|
279
|
+
|
|
280
|
+
expect(emissions).toEqual([
|
|
281
|
+
{ itemId: 'item_a', transcript: 'partial', isFinal: false },
|
|
282
|
+
{ itemId: 'item_a', transcript: 'final.', isFinal: true },
|
|
283
|
+
]);
|
|
284
|
+
expect(session.inputTranscriptAccumulators.size).toBe(0);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it('treats .completed as a no-op cleanup when no deltas preceded it (non-streaming STT model)', () => {
|
|
288
|
+
const session = createTranscriptSession({
|
|
289
|
+
chatItems: { item_a: new llm.ChatMessage({ role: 'user', content: '', id: 'item_a' }) },
|
|
290
|
+
});
|
|
291
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
292
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
293
|
+
|
|
294
|
+
session.handleConversationItemInputAudioTranscriptionCompleted(
|
|
295
|
+
completed('item_a', 'one-shot whisper-1 transcript'),
|
|
296
|
+
);
|
|
297
|
+
|
|
298
|
+
expect(session.inputTranscriptAccumulators.size).toBe(0);
|
|
299
|
+
expect(emissions).toEqual([
|
|
300
|
+
{ itemId: 'item_a', transcript: 'one-shot whisper-1 transcript', isFinal: true },
|
|
301
|
+
]);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
it('skips emission for empty or missing deltas and does not create an accumulator', () => {
|
|
305
|
+
const session = createTranscriptSession();
|
|
306
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
307
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
308
|
+
|
|
309
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', ''));
|
|
310
|
+
session.handleConversationItemInputAudioTranscriptionDelta({
|
|
311
|
+
type: 'conversation.item.input_audio_transcription.delta',
|
|
312
|
+
event_id: 'evt_no_delta',
|
|
313
|
+
item_id: 'item_a',
|
|
314
|
+
});
|
|
315
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'real'));
|
|
316
|
+
|
|
317
|
+
expect(session.inputTranscriptAccumulators.get('item_a')?.get(0)).toBe('real');
|
|
318
|
+
expect(emissions).toEqual([{ itemId: 'item_a', transcript: 'real', isFinal: false }]);
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
it('clears the accumulator and emits a closing isFinal:true on transcription failure when partials had streamed', () => {
|
|
322
|
+
const session = createTranscriptSession();
|
|
323
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
324
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
325
|
+
|
|
326
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'partial '));
|
|
327
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'text'));
|
|
328
|
+
session.finalizePartialOnTranscriptionFailure('item_a', 0);
|
|
329
|
+
|
|
330
|
+
expect(session.inputTranscriptAccumulators.size).toBe(0);
|
|
331
|
+
expect(emissions).toEqual([
|
|
332
|
+
{ itemId: 'item_a', transcript: 'partial ', isFinal: false },
|
|
333
|
+
{ itemId: 'item_a', transcript: 'partial text', isFinal: false },
|
|
334
|
+
{ itemId: 'item_a', transcript: 'partial text', isFinal: true },
|
|
335
|
+
]);
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
it('emits nothing on transcription failure when no partials had streamed for that item', () => {
|
|
339
|
+
const session = createTranscriptSession();
|
|
340
|
+
const emissions: llm.InputTranscriptionCompleted[] = [];
|
|
341
|
+
session.on('input_audio_transcription_completed', (ev) => emissions.push(ev));
|
|
342
|
+
|
|
343
|
+
session.finalizePartialOnTranscriptionFailure('item_a', 0);
|
|
344
|
+
|
|
345
|
+
expect(emissions).toEqual([]);
|
|
346
|
+
expect(session.inputTranscriptAccumulators.size).toBe(0);
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it('clears the accumulator when the conversation item is deleted', () => {
|
|
350
|
+
const session = createTranscriptSession();
|
|
351
|
+
|
|
352
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'partial '));
|
|
353
|
+
session.handleConversationItemInputAudioTranscriptionDelta(delta('item_a', 'more', 1));
|
|
354
|
+
expect(session.inputTranscriptAccumulators.get('item_a')?.size).toBe(2);
|
|
355
|
+
|
|
356
|
+
session.handleConversationItemDeleted({
|
|
357
|
+
type: 'conversation.item.deleted',
|
|
358
|
+
event_id: 'evt_del',
|
|
359
|
+
item_id: 'item_a',
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
expect(session.inputTranscriptAccumulators.has('item_a')).toBe(false);
|
|
363
|
+
});
|
|
364
|
+
});
|
|
365
|
+
|
|
46
366
|
describe('livekitItemToOpenAIItem', () => {
|
|
47
367
|
describe('message items', () => {
|
|
48
368
|
it('should use output_text type for assistant messages', async () => {
|
|
@@ -285,17 +605,6 @@ describe('RealtimeSession.updateOptions', () => {
|
|
|
285
605
|
vi.restoreAllMocks();
|
|
286
606
|
});
|
|
287
607
|
|
|
288
|
-
const stubTaskRuntime = () => {
|
|
289
|
-
// Prevent background realtime tasks from opening network connections in unit tests.
|
|
290
|
-
vi.spyOn(llm, 'RealtimeSession', 'get');
|
|
291
|
-
const agentsModule = require('@livekit/agents') as typeof import('@livekit/agents'); // eslint-disable-line @typescript-eslint/no-var-requires
|
|
292
|
-
vi.spyOn(agentsModule.Task, 'from').mockReturnValue({
|
|
293
|
-
cancel: vi.fn(),
|
|
294
|
-
done: true,
|
|
295
|
-
result: Promise.resolve(undefined),
|
|
296
|
-
} as unknown as import('@livekit/agents').Task<void>);
|
|
297
|
-
};
|
|
298
|
-
|
|
299
608
|
it('emits session.update when toolChoice changes', () => {
|
|
300
609
|
stubTaskRuntime();
|
|
301
610
|
|
|
@@ -225,7 +225,7 @@ export class RealtimeModel extends llm.RealtimeModel {
|
|
|
225
225
|
this._options = {
|
|
226
226
|
...DEFAULT_REALTIME_MODEL_OPTIONS,
|
|
227
227
|
...optionsWithoutModalities,
|
|
228
|
-
baseURL: options.baseURL || BASE_URL,
|
|
228
|
+
baseURL: options.baseURL || process.env.OPENAI_BASE_URL || BASE_URL,
|
|
229
229
|
apiKey,
|
|
230
230
|
isAzure,
|
|
231
231
|
model: options.model || DEFAULT_REALTIME_MODEL_OPTIONS.model,
|
|
@@ -441,6 +441,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
441
441
|
private itemCreateFutures: { [id: string]: Future } = {};
|
|
442
442
|
private itemDeleteFutures: { [id: string]: Future } = {};
|
|
443
443
|
|
|
444
|
+
private inputTranscriptAccumulators = new Map<string, Map<number, string>>();
|
|
445
|
+
|
|
444
446
|
// Track items that have real server-side audio (created in current session, not restored)
|
|
445
447
|
// Items restored after reconnection are text-only and cannot be truncated
|
|
446
448
|
private audioCapableItemIds: Set<string> = new Set();
|
|
@@ -1030,6 +1032,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1030
1032
|
|
|
1031
1033
|
// Clear audio-capable item tracking - restored items are text-only on the server
|
|
1032
1034
|
this.audioCapableItemIds.clear();
|
|
1035
|
+
this.inputTranscriptAccumulators.clear();
|
|
1033
1036
|
|
|
1034
1037
|
const events: api_proto.ClientEvent[] = [];
|
|
1035
1038
|
|
|
@@ -1198,6 +1201,9 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1198
1201
|
case 'conversation.item.deleted':
|
|
1199
1202
|
this.handleConversationItemDeleted(event);
|
|
1200
1203
|
break;
|
|
1204
|
+
case 'conversation.item.input_audio_transcription.delta':
|
|
1205
|
+
this.handleConversationItemInputAudioTranscriptionDelta(event);
|
|
1206
|
+
break;
|
|
1201
1207
|
case 'conversation.item.input_audio_transcription.completed':
|
|
1202
1208
|
this.handleConversationItemInputAudioTranscriptionCompleted(event);
|
|
1203
1209
|
break;
|
|
@@ -1313,6 +1319,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1313
1319
|
}
|
|
1314
1320
|
this.itemDeleteFutures = {};
|
|
1315
1321
|
|
|
1322
|
+
this.inputTranscriptAccumulators.clear();
|
|
1323
|
+
|
|
1316
1324
|
// Clean up current generation if exists
|
|
1317
1325
|
if (this.currentGeneration) {
|
|
1318
1326
|
for (const gen of this.currentGeneration.messages.values()) {
|
|
@@ -1470,6 +1478,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1470
1478
|
|
|
1471
1479
|
// Clean up audio-capable tracking for deleted items
|
|
1472
1480
|
this.audioCapableItemIds.delete(event.item_id);
|
|
1481
|
+
this.inputTranscriptAccumulators.delete(event.item_id);
|
|
1473
1482
|
|
|
1474
1483
|
try {
|
|
1475
1484
|
this.remoteChatCtx.delete(event.item_id);
|
|
@@ -1484,26 +1493,56 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1484
1493
|
}
|
|
1485
1494
|
}
|
|
1486
1495
|
|
|
1496
|
+
private handleConversationItemInputAudioTranscriptionDelta(
|
|
1497
|
+
event: api_proto.ConversationItemInputAudioTranscriptionDeltaEvent,
|
|
1498
|
+
): void {
|
|
1499
|
+
if (!event.delta) return;
|
|
1500
|
+
|
|
1501
|
+
const contentIndex = event.content_index ?? 0;
|
|
1502
|
+
let byIndex = this.inputTranscriptAccumulators.get(event.item_id);
|
|
1503
|
+
if (!byIndex) {
|
|
1504
|
+
byIndex = new Map();
|
|
1505
|
+
this.inputTranscriptAccumulators.set(event.item_id, byIndex);
|
|
1506
|
+
}
|
|
1507
|
+
const accumulated = (byIndex.get(contentIndex) ?? '') + event.delta;
|
|
1508
|
+
byIndex.set(contentIndex, accumulated);
|
|
1509
|
+
|
|
1510
|
+
this.emit('input_audio_transcription_completed', {
|
|
1511
|
+
itemId: event.item_id,
|
|
1512
|
+
transcript: accumulated,
|
|
1513
|
+
isFinal: false,
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
private clearAccumulator(itemId: string, contentIndex: number): string | undefined {
|
|
1518
|
+
const byIndex = this.inputTranscriptAccumulators.get(itemId);
|
|
1519
|
+
if (!byIndex) return undefined;
|
|
1520
|
+
const partial = byIndex.get(contentIndex);
|
|
1521
|
+
byIndex.delete(contentIndex);
|
|
1522
|
+
if (byIndex.size === 0) this.inputTranscriptAccumulators.delete(itemId);
|
|
1523
|
+
return partial;
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1487
1526
|
private handleConversationItemInputAudioTranscriptionCompleted(
|
|
1488
1527
|
event: api_proto.ConversationItemInputAudioTranscriptionCompletedEvent,
|
|
1489
1528
|
): void {
|
|
1490
|
-
|
|
1491
|
-
if (!remoteItem) {
|
|
1492
|
-
return;
|
|
1493
|
-
}
|
|
1529
|
+
this.clearAccumulator(event.item_id, event.content_index ?? 0);
|
|
1494
1530
|
|
|
1495
|
-
const
|
|
1496
|
-
if (
|
|
1497
|
-
item.
|
|
1498
|
-
|
|
1499
|
-
|
|
1531
|
+
const remoteItem = this.remoteChatCtx.get(event.item_id);
|
|
1532
|
+
if (remoteItem) {
|
|
1533
|
+
const item = remoteItem.item;
|
|
1534
|
+
if (item instanceof llm.ChatMessage) {
|
|
1535
|
+
item.content.push(event.transcript);
|
|
1536
|
+
} else {
|
|
1537
|
+
throw new Error('item is not a chat message');
|
|
1538
|
+
}
|
|
1500
1539
|
}
|
|
1501
1540
|
|
|
1502
1541
|
this.emit('input_audio_transcription_completed', {
|
|
1503
1542
|
itemId: event.item_id,
|
|
1504
1543
|
transcript: event.transcript,
|
|
1505
1544
|
isFinal: true,
|
|
1506
|
-
}
|
|
1545
|
+
});
|
|
1507
1546
|
}
|
|
1508
1547
|
|
|
1509
1548
|
private handleConversationItemInputAudioTranscriptionFailed(
|
|
@@ -1513,6 +1552,18 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1513
1552
|
{ error: event.error },
|
|
1514
1553
|
'OpenAI Realtime API failed to transcribe input audio',
|
|
1515
1554
|
);
|
|
1555
|
+
this.finalizePartialOnTranscriptionFailure(event.item_id, event.content_index ?? 0);
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
// Close any open partial stream so consumers waiting for isFinal don't hang.
|
|
1559
|
+
private finalizePartialOnTranscriptionFailure(itemId: string, contentIndex: number): void {
|
|
1560
|
+
const partial = this.clearAccumulator(itemId, contentIndex);
|
|
1561
|
+
if (partial === undefined) return;
|
|
1562
|
+
this.emit('input_audio_transcription_completed', {
|
|
1563
|
+
itemId,
|
|
1564
|
+
transcript: partial,
|
|
1565
|
+
isFinal: true,
|
|
1566
|
+
});
|
|
1516
1567
|
}
|
|
1517
1568
|
|
|
1518
1569
|
private handleResponseContentPartAdded(event: api_proto.ResponseContentPartAddedEvent): void {
|
|
@@ -1775,7 +1826,44 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1775
1826
|
};
|
|
1776
1827
|
|
|
1777
1828
|
this.emit('metrics_collected', realtimeMetrics);
|
|
1778
|
-
|
|
1829
|
+
this.handleResponseDoneButNotComplete(_event);
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
private handleResponseDoneButNotComplete(event: api_proto.ResponseDoneEvent): void {
|
|
1833
|
+
if (event.response.status === 'completed') {
|
|
1834
|
+
return;
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
const statusDetails = event.response.status_details;
|
|
1838
|
+
if (event.response.status === 'failed') {
|
|
1839
|
+
const errorBody = statusDetails?.type === 'failed' ? statusDetails.error : undefined;
|
|
1840
|
+
const errorTypeValue = errorBody && 'type' in errorBody ? errorBody.type : undefined;
|
|
1841
|
+
const errorType = typeof errorTypeValue === 'string' ? errorTypeValue : 'unknown';
|
|
1842
|
+
|
|
1843
|
+
this.emitError({
|
|
1844
|
+
error: new APIError(`OpenAI Realtime API response failed with error type: ${errorType}`, {
|
|
1845
|
+
body: errorBody ?? null,
|
|
1846
|
+
retryable: true,
|
|
1847
|
+
}),
|
|
1848
|
+
recoverable: true,
|
|
1849
|
+
});
|
|
1850
|
+
} else if (event.response.status === 'cancelled' || event.response.status === 'incomplete') {
|
|
1851
|
+
const statusType = statusDetails?.type;
|
|
1852
|
+
const statusReason =
|
|
1853
|
+
statusDetails && 'reason' in statusDetails ? statusDetails.reason : undefined;
|
|
1854
|
+
|
|
1855
|
+
this.#logger.debug(
|
|
1856
|
+
{
|
|
1857
|
+
eventId: event.response.id,
|
|
1858
|
+
eventResponseStatus: event.response.status,
|
|
1859
|
+
eventResponseStatusType: statusType,
|
|
1860
|
+
eventResponseStatusReason: statusReason,
|
|
1861
|
+
},
|
|
1862
|
+
`OpenAI Realtime API response done but not complete with status: ${event.response.status} (type=${statusType}, reason=${statusReason})`,
|
|
1863
|
+
);
|
|
1864
|
+
} else {
|
|
1865
|
+
this.#logger.debug({ eventResponseStatus: event.response.status }, 'Unknown response status');
|
|
1866
|
+
}
|
|
1779
1867
|
}
|
|
1780
1868
|
|
|
1781
1869
|
private handleError(event: api_proto.ErrorEvent): void {
|
|
@@ -1807,6 +1895,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1807
1895
|
private emitError({ error, recoverable }: { error: Error; recoverable: boolean }): void {
|
|
1808
1896
|
// IMPORTANT: only emit error if there are listeners; otherwise emit will throw an error
|
|
1809
1897
|
this.emit('error', {
|
|
1898
|
+
type: 'realtime_model_error',
|
|
1810
1899
|
timestamp: Date.now(),
|
|
1811
1900
|
// TODO(brian): add label
|
|
1812
1901
|
label: '',
|
package/src/responses/llm.ts
CHANGED
|
@@ -182,7 +182,7 @@ class ResponsesHttpLLMStream extends llm.LLMStream {
|
|
|
182
182
|
)) as OpenAI.Responses.ResponseInputItem[];
|
|
183
183
|
|
|
184
184
|
const tools = this.toolCtx
|
|
185
|
-
?
|
|
185
|
+
? llm.sortedToolEntries(this.toolCtx).map(([name, func]) => {
|
|
186
186
|
const oaiParams = {
|
|
187
187
|
type: 'function' as const,
|
|
188
188
|
name: name,
|
package/src/ws/llm.ts
CHANGED
|
@@ -447,7 +447,7 @@ export class WSLLMStream extends llm.LLMStream {
|
|
|
447
447
|
)) as OpenAI.Responses.ResponseInputItem[];
|
|
448
448
|
|
|
449
449
|
const tools = this.toolCtx
|
|
450
|
-
?
|
|
450
|
+
? llm.sortedToolEntries(this.toolCtx).map(([name, func]) => {
|
|
451
451
|
const oaiParams = {
|
|
452
452
|
type: 'function' as const,
|
|
453
453
|
name,
|