@livekit/agents-plugin-openai 1.9.2 → 1.9.3

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.
Files changed (59) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/models.cjs.map +1 -1
  4. package/dist/models.d.cts +1 -0
  5. package/dist/models.d.ts +1 -0
  6. package/dist/models.d.ts.map +1 -1
  7. package/dist/models.js.map +1 -1
  8. package/dist/realtime/api_proto.cjs +3 -21
  9. package/dist/realtime/api_proto.cjs.map +1 -1
  10. package/dist/realtime/api_proto.d.cts +1 -504
  11. package/dist/realtime/api_proto.d.ts +1 -504
  12. package/dist/realtime/api_proto.d.ts.map +1 -1
  13. package/dist/realtime/api_proto.js +1 -12
  14. package/dist/realtime/api_proto.js.map +1 -1
  15. package/dist/realtime/gpt_live_model.cjs +7 -851
  16. package/dist/realtime/gpt_live_model.cjs.map +1 -1
  17. package/dist/realtime/gpt_live_model.d.cts +6 -178
  18. package/dist/realtime/gpt_live_model.d.ts +6 -178
  19. package/dist/realtime/gpt_live_model.d.ts.map +1 -1
  20. package/dist/realtime/gpt_live_model.js +7 -850
  21. package/dist/realtime/gpt_live_model.js.map +1 -1
  22. package/dist/realtime/gpt_live_model.test.cjs +32 -1
  23. package/dist/realtime/gpt_live_model.test.cjs.map +1 -1
  24. package/dist/realtime/gpt_live_model.test.js +32 -1
  25. package/dist/realtime/gpt_live_model.test.js.map +1 -1
  26. package/dist/realtime/gpt_live_types.cjs +6 -0
  27. package/dist/realtime/gpt_live_types.cjs.map +1 -1
  28. package/dist/realtime/gpt_live_types.d.cts +1 -169
  29. package/dist/realtime/gpt_live_types.d.ts +1 -169
  30. package/dist/realtime/gpt_live_types.d.ts.map +1 -1
  31. package/dist/realtime/gpt_live_types.js +1 -0
  32. package/dist/realtime/gpt_live_types.js.map +1 -1
  33. package/dist/realtime/index.cjs +8 -1
  34. package/dist/realtime/index.cjs.map +1 -1
  35. package/dist/realtime/index.d.cts +5 -0
  36. package/dist/realtime/index.d.ts +5 -0
  37. package/dist/realtime/index.d.ts.map +1 -1
  38. package/dist/realtime/index.js +6 -1
  39. package/dist/realtime/index.js.map +1 -1
  40. package/dist/realtime/realtime_model.cjs +3 -1890
  41. package/dist/realtime/realtime_model.cjs.map +1 -1
  42. package/dist/realtime/realtime_model.d.cts +1 -236
  43. package/dist/realtime/realtime_model.d.ts +1 -236
  44. package/dist/realtime/realtime_model.d.ts.map +1 -1
  45. package/dist/realtime/realtime_model.js +1 -1886
  46. package/dist/realtime/realtime_model.js.map +1 -1
  47. package/dist/realtime/realtime_model.test.cjs +11 -1141
  48. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  49. package/dist/realtime/realtime_model.test.js +16 -1147
  50. package/dist/realtime/realtime_model.test.js.map +1 -1
  51. package/package.json +5 -6
  52. package/src/models.ts +2 -0
  53. package/src/realtime/api_proto.ts +2 -715
  54. package/src/realtime/gpt_live_model.test.ts +42 -1
  55. package/src/realtime/gpt_live_model.ts +17 -1030
  56. package/src/realtime/gpt_live_types.ts +1 -136
  57. package/src/realtime/index.ts +7 -0
  58. package/src/realtime/realtime_model.test.ts +17 -1454
  59. package/src/realtime/realtime_model.ts +2 -2408
@@ -1,1887 +1,2 @@
1
- import {
2
- APIConnectionError,
3
- APIError,
4
- AudioByteStream,
5
- DEFAULT_API_CONNECT_OPTIONS,
6
- Future,
7
- Queue,
8
- Task,
9
- cancelAndWait,
10
- createTimedString,
11
- delay,
12
- isAPIError,
13
- llm,
14
- log,
15
- shortuuid,
16
- stream
17
- } from "@livekit/agents";
18
- import { Mutex } from "@livekit/mutex";
19
- import { AudioFrame, combineAudioFrames } from "@livekit/rtc-node";
20
- import { WebSocket } from "ws";
21
- import * as api_proto from "./api_proto.js";
22
- const lkOaiDebug = process.env.LK_OPENAI_DEBUG ? Number(process.env.LK_OPENAI_DEBUG) : 0;
23
- const SAMPLE_RATE = 24e3;
24
- const NUM_CHANNELS = 1;
25
- const BASE_URL = "https://api.openai.com/v1";
26
- const MOCK_AUDIO_ID_PREFIX = "lk_mock_audio_item_";
27
- class DiscardedGeneration {
28
- discarded = true;
29
- }
30
- const FATAL_ERROR_CODES = /* @__PURE__ */ new Set([
31
- "insufficient_quota",
32
- "invalid_api_key",
33
- "account_deactivated",
34
- "billing_hard_limit_reached"
35
- ]);
36
- function isFatalError(error) {
37
- if (error === null || typeof error !== "object") return false;
38
- const { code, type } = error;
39
- const errorCode = typeof code === "string" && code.length > 0 ? code : type;
40
- return typeof errorCode === "string" && FATAL_ERROR_CODES.has(errorCode);
41
- }
42
- class CreateResponseHandle {
43
- instructions;
44
- doneFut;
45
- timeout;
46
- constructor({ instructions }) {
47
- this.instructions = instructions;
48
- this.doneFut = new Future();
49
- }
50
- }
51
- const DEFAULT_FIRST_RETRY_INTERVAL_MS = 100;
52
- const DEFAULT_TURN_DETECTION = {
53
- type: "semantic_vad",
54
- eagerness: "medium",
55
- create_response: true,
56
- interrupt_response: true
57
- };
58
- const DEFAULT_INPUT_AUDIO_TRANSCRIPTION = {
59
- model: "gpt-4o-mini-transcribe"
60
- };
61
- const DEFAULT_TOOL_CHOICE = "auto";
62
- const DEFAULT_MAX_RESPONSE_OUTPUT_TOKENS = "inf";
63
- const AZURE_DEFAULT_INPUT_AUDIO_TRANSCRIPTION = {
64
- model: "whisper-1"
65
- };
66
- const AZURE_DEFAULT_TURN_DETECTION = {
67
- type: "server_vad",
68
- threshold: 0.5,
69
- prefix_padding_ms: 300,
70
- silence_duration_ms: 200,
71
- create_response: true
72
- };
73
- const DEFAULT_MAX_SESSION_DURATION = 20 * 60 * 1e3;
74
- const DEFAULT_REALTIME_MODEL_OPTIONS = {
75
- model: "gpt-realtime",
76
- voice: "marin",
77
- inputAudioTranscription: DEFAULT_INPUT_AUDIO_TRANSCRIPTION,
78
- inputAudioNoiseReduction: void 0,
79
- turnDetection: DEFAULT_TURN_DETECTION,
80
- toolChoice: DEFAULT_TOOL_CHOICE,
81
- maxResponseOutputTokens: DEFAULT_MAX_RESPONSE_OUTPUT_TOKENS,
82
- maxSessionDuration: DEFAULT_MAX_SESSION_DURATION,
83
- connOptions: DEFAULT_API_CONNECT_OPTIONS,
84
- modalities: ["text", "audio"],
85
- tracing: void 0
86
- };
87
- class RealtimeModel extends llm.RealtimeModel {
88
- sampleRate = api_proto.SAMPLE_RATE;
89
- numChannels = api_proto.NUM_CHANNELS;
90
- inFrameSize = api_proto.IN_FRAME_SIZE;
91
- outFrameSize = api_proto.OUT_FRAME_SIZE;
92
- /* @internal */
93
- _options;
94
- get model() {
95
- return this._options.model;
96
- }
97
- get provider() {
98
- try {
99
- const url = new URL(this._options.baseURL);
100
- return url.host;
101
- } catch {
102
- return "api.openai.com";
103
- }
104
- }
105
- label() {
106
- return "openai.RealtimeModel";
107
- }
108
- constructor(options = {}) {
109
- const modalities = options.modalities || DEFAULT_REALTIME_MODEL_OPTIONS.modalities;
110
- super({
111
- messageTruncation: true,
112
- turnDetection: options.turnDetection !== null,
113
- userTranscription: options.inputAudioTranscription !== null,
114
- autoToolReplyGeneration: false,
115
- audioOutput: modalities.includes("audio"),
116
- manualFunctionCalls: true,
117
- midSessionChatCtxUpdate: true,
118
- midSessionInstructionsUpdate: true,
119
- midSessionToolsUpdate: true,
120
- perResponseToolChoice: true
121
- });
122
- const isAzure = !!(options.apiVersion || options.entraToken || options.azureDeployment);
123
- if (options.apiKey === "" && !isAzure) {
124
- throw new Error(
125
- "OpenAI API key is required, either using the argument or by setting the OPENAI_API_KEY environment variable"
126
- );
127
- }
128
- const apiKey = options.apiKey || process.env.OPENAI_API_KEY;
129
- if (!apiKey && !isAzure) {
130
- throw new Error(
131
- "OpenAI API key is required, either using the argument or by setting the OPENAI_API_KEY environment variable"
132
- );
133
- }
134
- if (!options.baseURL && isAzure) {
135
- const azureEndpoint = process.env.AZURE_OPENAI_ENDPOINT;
136
- if (!azureEndpoint) {
137
- throw new Error(
138
- "Missing Azure endpoint. Please pass base_url or set AZURE_OPENAI_ENDPOINT environment variable."
139
- );
140
- }
141
- options.baseURL = `${azureEndpoint.replace(/\/$/, "")}/openai`;
142
- }
143
- const { modalities: _, ...optionsWithoutModalities } = options;
144
- this._options = {
145
- ...DEFAULT_REALTIME_MODEL_OPTIONS,
146
- ...optionsWithoutModalities,
147
- baseURL: options.baseURL || process.env.OPENAI_BASE_URL || BASE_URL,
148
- apiKey,
149
- isAzure,
150
- model: options.model || DEFAULT_REALTIME_MODEL_OPTIONS.model,
151
- modalities
152
- };
153
- }
154
- /**
155
- * Create a RealtimeModel instance configured for Azure OpenAI Service.
156
- *
157
- * @param azureDeployment - The name of your Azure OpenAI deployment.
158
- * @param azureEndpoint - The endpoint URL for your Azure OpenAI resource. If undefined, will attempt to read from the environment variable AZURE_OPENAI_ENDPOINT.
159
- * @param apiVersion - **Deprecated.** API version for legacy Azure OpenAI preview models. Will be removed on April 30, 2026. Omit for GA models.
160
- * @param apiKey - Azure OpenAI API key. If undefined, will attempt to read from the environment variable AZURE_OPENAI_API_KEY.
161
- * @param entraToken - Azure Entra authentication token. Required if not using API key authentication.
162
- * @param baseURL - Base URL for the API endpoint. If undefined, constructed from the azure_endpoint.
163
- * @param voice - Voice setting for audio outputs. Defaults to "marin".
164
- * @param inputAudioTranscription - Options for transcribing input audio. Defaults to @see DEFAULT_INPUT_AUDIO_TRANSCRIPTION.
165
- * @param inputAudioNoiseReduction - Options for noise reduction. Defaults to undefined.
166
- * @param turnDetection - Options for server-based voice activity detection (VAD). Defaults to @see DEFAULT_SERVER_VAD_OPTIONS.
167
- * @param speed - Speed of the audio output. Defaults to 1.0.
168
- * @param tracing - Tracing configuration. Defaults to undefined.
169
- *
170
- * @returns A RealtimeModel instance configured for Azure OpenAI Service.
171
- *
172
- * @throws Error if required Azure parameters are missing or invalid.
173
- */
174
- static withAzure({
175
- azureDeployment,
176
- azureEndpoint,
177
- apiVersion,
178
- apiKey,
179
- entraToken,
180
- baseURL,
181
- voice = "marin",
182
- temperature,
183
- // eslint-disable-line @typescript-eslint/no-unused-vars
184
- inputAudioTranscription = AZURE_DEFAULT_INPUT_AUDIO_TRANSCRIPTION,
185
- inputAudioNoiseReduction,
186
- turnDetection = AZURE_DEFAULT_TURN_DETECTION,
187
- speed,
188
- tracing
189
- }) {
190
- apiKey = apiKey || process.env.AZURE_OPENAI_API_KEY;
191
- if (!apiKey && !entraToken) {
192
- throw new Error(
193
- "Missing credentials. Please pass one of `apiKey`, `entraToken`, or the `AZURE_OPENAI_API_KEY` environment variable."
194
- );
195
- }
196
- apiVersion = apiVersion || process.env.OPENAI_API_VERSION;
197
- if (apiVersion) {
198
- log().warn(
199
- "The `apiVersion` parameter for Azure OpenAI Realtime is deprecated and will be removed on April 30, 2026. Please use the newer Azure OpenAI Realtime API without specifying an API version."
200
- );
201
- }
202
- if (!baseURL) {
203
- azureEndpoint = azureEndpoint || process.env.AZURE_OPENAI_ENDPOINT;
204
- if (!azureEndpoint) {
205
- throw new Error(
206
- "Missing Azure endpoint. Please pass the `azure_endpoint` parameter or set the `AZURE_OPENAI_ENDPOINT` environment variable."
207
- );
208
- }
209
- baseURL = `${azureEndpoint.replace(/\/$/, "")}/openai`;
210
- }
211
- return new RealtimeModel({
212
- voice,
213
- inputAudioTranscription,
214
- inputAudioNoiseReduction,
215
- turnDetection,
216
- speed,
217
- tracing,
218
- apiKey,
219
- azureDeployment,
220
- apiVersion,
221
- entraToken,
222
- baseURL
223
- });
224
- }
225
- session() {
226
- return new RealtimeSession(this);
227
- }
228
- async close() {
229
- return;
230
- }
231
- }
232
- function normalizeAzureClientEvent(event) {
233
- const item = event["item"];
234
- if (!item) return;
235
- const content = item["content"];
236
- if (!content) return;
237
- for (const contentPart of content) {
238
- if (contentPart["type"] === "output_text") {
239
- contentPart["type"] = "text";
240
- }
241
- }
242
- }
243
- function processBaseURL({
244
- baseURL,
245
- model,
246
- isAzure = false,
247
- azureDeployment,
248
- apiVersion
249
- }) {
250
- const url = new URL(baseURL);
251
- if (url.protocol === "https:") {
252
- url.protocol = "wss:";
253
- } else if (url.protocol === "http:") {
254
- url.protocol = "ws:";
255
- }
256
- const pathStripped = url.pathname.replace(/\/$/, "");
257
- if (isAzure) {
258
- if (["", "/openai"].includes(pathStripped)) {
259
- url.pathname = pathStripped + (apiVersion ? "/realtime" : "/v1/realtime");
260
- } else if (pathStripped === "/openai/v1") {
261
- url.pathname = "/openai/v1/realtime";
262
- }
263
- } else if (!url.pathname || ["", "/v1", "/openai", "/openai/v1"].includes(pathStripped)) {
264
- url.pathname = pathStripped + "/realtime";
265
- }
266
- if (isAzure) {
267
- url.searchParams.delete("api-version");
268
- }
269
- const queryParams = {};
270
- if (isAzure && apiVersion) {
271
- queryParams["api-version"] = apiVersion;
272
- if (azureDeployment) {
273
- queryParams["deployment"] = azureDeployment;
274
- }
275
- } else if (isAzure) {
276
- if (!url.searchParams.has("model") && azureDeployment) {
277
- queryParams["model"] = azureDeployment;
278
- }
279
- } else {
280
- if (!url.searchParams.has("model")) {
281
- queryParams["model"] = model;
282
- }
283
- }
284
- for (const [key, value] of Object.entries(queryParams)) {
285
- url.searchParams.set(key, value);
286
- }
287
- return url.toString();
288
- }
289
- class RealtimeSession extends llm.RealtimeSession {
290
- _tools = llm.ToolContext.empty();
291
- remoteChatCtx = new llm.RemoteChatContext();
292
- messageChannel = new Queue();
293
- inputResampler;
294
- instructions;
295
- oaiRealtimeModel;
296
- // Ref: python livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/realtime_model.py - 795-797 lines
297
- // per-session copy of options so updateOptions can diff against the session's
298
- // own state instead of the shared model-level state.
299
- _options;
300
- currentGeneration;
301
- responseCreatedFutures = {};
302
- discardedEventIds = /* @__PURE__ */ new Set();
303
- textModeRecoveryRetries = 0;
304
- itemCreateFutures = {};
305
- itemDeleteFutures = {};
306
- chatCtxEventFutures = {};
307
- sentChatCtxEvents = {};
308
- replayItemCreateEventIds = {};
309
- replayItemCreateEventItems = {};
310
- inputTranscriptAccumulators = /* @__PURE__ */ new Map();
311
- // Track items that have real server-side audio (created in current session, not restored)
312
- // Items restored after reconnection are text-only and cannot be truncated
313
- audioCapableItemIds = /* @__PURE__ */ new Set();
314
- updateChatCtxLock = new Mutex();
315
- updateFuncCtxLock = new Mutex();
316
- // 100ms chunks
317
- bstream = new AudioByteStream(SAMPLE_RATE, NUM_CHANNELS, SAMPLE_RATE / 10);
318
- pushedDurationMs = 0;
319
- #logger = log();
320
- #task;
321
- #closed = false;
322
- constructor(realtimeModel) {
323
- super(realtimeModel);
324
- this.oaiRealtimeModel = realtimeModel;
325
- this._options = { ...realtimeModel._options };
326
- this.#task = Task.from(({ signal }) => this.#mainTask(signal));
327
- this.sendEvent(this.createSessionUpdateEvent());
328
- }
329
- hasInflightResponse() {
330
- return this.currentGeneration !== void 0 || Object.keys(this.responseCreatedFutures).length > 0;
331
- }
332
- sendEvent(command) {
333
- this.messageChannel.put(command);
334
- }
335
- createSessionUpdateEvent() {
336
- const opts = this._options;
337
- const maxOutputTokens = opts.maxResponseOutputTokens === Infinity ? "inf" : opts.maxResponseOutputTokens;
338
- if (opts.isAzure && opts.apiVersion) {
339
- const modalities = opts.modalities.includes("audio") ? ["text", "audio"] : ["text"];
340
- return {
341
- type: "session.update",
342
- session: {
343
- model: opts.model,
344
- voice: opts.voice,
345
- input_audio_format: "pcm16",
346
- output_audio_format: "pcm16",
347
- modalities,
348
- turn_detection: opts.turnDetection,
349
- input_audio_transcription: opts.inputAudioTranscription,
350
- tool_choice: toOaiToolChoice(opts.toolChoice),
351
- max_response_output_tokens: maxOutputTokens,
352
- speed: opts.speed,
353
- instructions: this.instructions
354
- }
355
- };
356
- }
357
- const audioFormat = { type: "audio/pcm", rate: SAMPLE_RATE };
358
- const modality = opts.modalities.includes("audio") ? "audio" : "text";
359
- const includeReasoning = opts.reasoning && opts.model.startsWith("gpt-realtime-2");
360
- return {
361
- type: "session.update",
362
- session: {
363
- type: "realtime",
364
- model: opts.model,
365
- output_modalities: [modality],
366
- audio: {
367
- input: {
368
- format: audioFormat,
369
- noise_reduction: opts.inputAudioNoiseReduction,
370
- transcription: opts.inputAudioTranscription,
371
- turn_detection: opts.turnDetection
372
- },
373
- output: {
374
- format: audioFormat,
375
- speed: opts.speed,
376
- voice: opts.voice
377
- }
378
- },
379
- max_output_tokens: maxOutputTokens,
380
- tool_choice: toOaiToolChoice(opts.toolChoice),
381
- tracing: opts.tracing,
382
- instructions: this.instructions,
383
- ...includeReasoning ? { reasoning: opts.reasoning } : {}
384
- }
385
- };
386
- }
387
- get chatCtx() {
388
- return this.remoteChatCtx.toChatCtx();
389
- }
390
- get tools() {
391
- return this._tools.copy();
392
- }
393
- async updateChatCtx(_chatCtx) {
394
- const unlock = await this.updateChatCtxLock.lock();
395
- try {
396
- const validation = llm.validateChatContextStructure(_chatCtx);
397
- const blockingErrors = validation.issues.filter(
398
- (issue) => issue.severity === "error" && issue.code !== "timestamp_order"
399
- );
400
- const timestampOrderIssue = validation.issues.find(
401
- (issue) => issue.code === "timestamp_order"
402
- );
403
- if (blockingErrors.length > 0) {
404
- this.#logger.error(
405
- { issues: validation.issues, blockingErrors },
406
- "Invalid chat context supplied to updateChatCtx"
407
- );
408
- throw new Error(
409
- `Invalid chat context: ${validation.errors} errors, ${validation.warnings} warnings`
410
- );
411
- }
412
- if (timestampOrderIssue) {
413
- this.#logger.warn(
414
- { timestampOrderIssue },
415
- "Proceeding with non-monotonic createdAt ordering in realtime chat context"
416
- );
417
- }
418
- if (lkOaiDebug > 0 && validation.warnings > 0) {
419
- this.#logger.debug(
420
- {
421
- warnings: validation.warnings,
422
- issues: validation.issues
423
- },
424
- "Chat context warnings detected before realtime update"
425
- );
426
- }
427
- const events = await this.createChatCtxUpdateEvents(_chatCtx);
428
- const futures = [];
429
- const ownedCreateFutures = {};
430
- const ownedDeleteFutures = {};
431
- const ownedEventFutures = {};
432
- this.sentChatCtxEvents = {};
433
- const cleanupFutures = () => {
434
- for (const [itemId, future] of Object.entries(ownedDeleteFutures)) {
435
- if (this.itemDeleteFutures[itemId] === future) {
436
- delete this.itemDeleteFutures[itemId];
437
- }
438
- }
439
- for (const [itemId, future] of Object.entries(ownedCreateFutures)) {
440
- if (this.itemCreateFutures[itemId] === future) {
441
- delete this.itemCreateFutures[itemId];
442
- }
443
- }
444
- for (const [eventId, future] of Object.entries(ownedEventFutures)) {
445
- if (this.chatCtxEventFutures[eventId] === future) {
446
- delete this.chatCtxEventFutures[eventId];
447
- }
448
- }
449
- };
450
- for (const event of events) {
451
- let future;
452
- if (event.type === "conversation.item.create") {
453
- future = new Future();
454
- futures.push(future);
455
- this.itemCreateFutures[event.item.id] = future;
456
- ownedCreateFutures[event.item.id] = future;
457
- } else if (event.type == "conversation.item.delete") {
458
- const existingDeleteFuture = this.itemDeleteFutures[event.item_id];
459
- if (existingDeleteFuture) {
460
- futures.push(existingDeleteFuture);
461
- continue;
462
- }
463
- future = new Future();
464
- futures.push(future);
465
- this.itemDeleteFutures[event.item_id] = future;
466
- ownedDeleteFutures[event.item_id] = future;
467
- } else {
468
- continue;
469
- }
470
- if (event.event_id) {
471
- this.chatCtxEventFutures[event.event_id] = future;
472
- ownedEventFutures[event.event_id] = future;
473
- }
474
- this.sendEvent(event);
475
- }
476
- if (futures.length === 0) {
477
- return;
478
- }
479
- const timeoutController = new AbortController();
480
- const timeoutPromise = delay(5e3, { signal: timeoutController.signal }).then(() => {
481
- throw new llm.RealtimeError("update_chat_ctx timed out.");
482
- });
483
- try {
484
- const results = await Promise.race([
485
- Promise.allSettled(futures.map((fut) => fut.await)),
486
- timeoutPromise
487
- ]);
488
- const rejected = results.filter((result) => result.status === "rejected");
489
- if (rejected.length > 0) {
490
- this.#logger.warn(
491
- { errors: rejected.map((result) => String(result.reason)) },
492
- `${this.oaiRealtimeModel.label()} rejected part of a chat context update`
493
- );
494
- }
495
- } finally {
496
- cleanupFutures();
497
- this.sentChatCtxEvents = {};
498
- if (!timeoutController.signal.aborted) {
499
- timeoutController.abort();
500
- }
501
- }
502
- } catch (e) {
503
- this.#logger.error(e.message);
504
- throw e;
505
- } finally {
506
- unlock();
507
- }
508
- }
509
- async createChatCtxUpdateEvents(chatCtx, addMockAudio = false) {
510
- const newChatCtx = chatCtx.copy({
511
- excludeHandoff: true,
512
- excludeConfigUpdate: true
513
- });
514
- if (addMockAudio) {
515
- newChatCtx.items.push(createMockAudioItem());
516
- } else {
517
- newChatCtx.items = newChatCtx.items.filter(
518
- (item) => !item.id.startsWith(MOCK_AUDIO_ID_PREFIX)
519
- );
520
- }
521
- const events = [];
522
- const remoteCtx = this.chatCtx;
523
- const remoteIds = new Set(remoteCtx.items.map((item) => item.id));
524
- newChatCtx.items = newChatCtx.items.filter(
525
- (item) => item.type !== "message" || item.content.length > 0 || remoteIds.has(item.id)
526
- );
527
- const diffOps = llm.computeChatCtxDiff(remoteCtx, newChatCtx);
528
- for (const op of diffOps.toRemove) {
529
- events.push({
530
- type: "conversation.item.delete",
531
- item_id: op,
532
- event_id: shortuuid("chat_ctx_delete_")
533
- });
534
- }
535
- const createItem = async (previousId, id) => {
536
- const chatItem = newChatCtx.getById(id);
537
- if (!chatItem) {
538
- throw new Error(`Chat item ${id} not found`);
539
- }
540
- events.push({
541
- type: "conversation.item.create",
542
- item: await livekitItemToOpenAIItem(chatItem),
543
- previous_item_id: previousId ?? void 0,
544
- event_id: shortuuid("chat_ctx_create_")
545
- });
546
- };
547
- const isContentEmpty = (id) => {
548
- const remoteItem = remoteCtx.getById(id);
549
- return (remoteItem == null ? void 0 : remoteItem.type) === "message" && remoteItem.content.length === 0;
550
- };
551
- for (const [previousId, id] of diffOps.toCreate) {
552
- await createItem(previousId, id);
553
- }
554
- for (const [previousId, id] of diffOps.toUpdate) {
555
- if (isContentEmpty(id)) {
556
- continue;
557
- }
558
- events.push({
559
- type: "conversation.item.delete",
560
- item_id: id,
561
- event_id: shortuuid("chat_ctx_delete_")
562
- });
563
- await createItem(previousId, id);
564
- }
565
- return events;
566
- }
567
- async updateTools(_tools) {
568
- const unlock = await this.updateFuncCtxLock.lock();
569
- const ev = this.createToolsUpdateEvent(_tools);
570
- this.sendEvent(ev);
571
- if (!ev.session.tools) {
572
- throw new Error("Tools are missing in the session update event");
573
- }
574
- const retainedToolNames = new Set(ev.session.tools.map((tool) => tool.name));
575
- const retainedEntries = _tools.tools.filter(
576
- (entry) => !llm.isFunctionTool(entry) || retainedToolNames.has(entry.name)
577
- );
578
- this._tools = new llm.ToolContext(retainedEntries);
579
- unlock();
580
- }
581
- createToolsUpdateEvent(_tools) {
582
- const oaiTools = [];
583
- for (const t of _tools.flatten()) {
584
- if (!llm.isFunctionTool(t)) continue;
585
- try {
586
- const parameters = llm.toJsonSchema(
587
- t.parameters
588
- );
589
- oaiTools.push({
590
- name: t.name,
591
- description: t.description,
592
- parameters,
593
- type: "function"
594
- });
595
- } catch (e) {
596
- this.#logger.error(
597
- { name: t.name, tool: t },
598
- "OpenAI Realtime API doesn't support this tool type"
599
- );
600
- continue;
601
- }
602
- }
603
- const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
604
- return {
605
- type: "session.update",
606
- session: {
607
- ...!isLegacyAzure && { type: "realtime" },
608
- model: this._options.model,
609
- tools: oaiTools
610
- },
611
- event_id: shortuuid("tools_update_")
612
- };
613
- }
614
- async updateInstructions(_instructions) {
615
- const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
616
- const eventId = shortuuid("instructions_update_");
617
- this.sendEvent({
618
- type: "session.update",
619
- session: {
620
- ...!isLegacyAzure && { type: "realtime" },
621
- instructions: _instructions
622
- },
623
- event_id: eventId
624
- });
625
- this.instructions = _instructions;
626
- }
627
- updateOptions({ toolChoice }) {
628
- const currentToolChoice = toOaiToolChoice(this._options.toolChoice);
629
- const nextToolChoice = toOaiToolChoice(toolChoice);
630
- if (currentToolChoice === nextToolChoice) {
631
- this._options.toolChoice = toolChoice;
632
- return;
633
- }
634
- const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
635
- const options = {
636
- ...!isLegacyAzure && { type: "realtime" }
637
- };
638
- this._options.toolChoice = toolChoice;
639
- options.tool_choice = toOaiToolChoice(toolChoice);
640
- this.sendEvent({
641
- type: "session.update",
642
- session: options,
643
- event_id: shortuuid("options_update_")
644
- });
645
- }
646
- pushAudio(frame) {
647
- for (const f of this.resampleAudio(frame)) {
648
- for (const nf of this.bstream.write(f.data.buffer)) {
649
- this.sendEvent({
650
- type: "input_audio_buffer.append",
651
- audio: Buffer.from(nf.data.buffer).toString("base64")
652
- });
653
- this.pushedDurationMs += nf.samplesPerChannel / nf.sampleRate * 1e3;
654
- }
655
- }
656
- }
657
- async commitAudio() {
658
- if (this.pushedDurationMs > 100) {
659
- this.sendEvent({
660
- type: "input_audio_buffer.commit"
661
- });
662
- this.pushedDurationMs = 0;
663
- }
664
- }
665
- async clearAudio() {
666
- this.sendEvent({
667
- type: "input_audio_buffer.clear"
668
- });
669
- this.pushedDurationMs = 0;
670
- }
671
- async generateReply(instructions, options = {}) {
672
- var _a, _b, _c;
673
- let responseInstructions = instructions;
674
- if (instructions && this.instructions) {
675
- responseInstructions = `${this.instructions}
676
- ${instructions}`;
677
- }
678
- const handle = this.createResponse({
679
- instructions: responseInstructions,
680
- userInitiated: true
681
- });
682
- this.textModeRecoveryRetries = 0;
683
- const onAbort = () => {
684
- var _a2;
685
- const eventId = (_a2 = Object.entries(this.responseCreatedFutures).find(
686
- ([, pendingHandle]) => pendingHandle === handle
687
- )) == null ? void 0 : _a2[0];
688
- if (eventId) {
689
- delete this.responseCreatedFutures[eventId];
690
- this.discardedEventIds.add(eventId);
691
- }
692
- if (handle.timeout) clearTimeout(handle.timeout);
693
- if (!handle.doneFut.done) {
694
- handle.doneFut.reject(new Error("generateReply aborted"));
695
- this.sendEvent({
696
- type: "response.cancel"
697
- });
698
- }
699
- };
700
- if ((_a = options.signal) == null ? void 0 : _a.aborted) {
701
- onAbort();
702
- } else {
703
- (_b = options.signal) == null ? void 0 : _b.addEventListener("abort", onAbort, { once: true });
704
- }
705
- try {
706
- return await handle.doneFut.await;
707
- } finally {
708
- (_c = options.signal) == null ? void 0 : _c.removeEventListener("abort", onAbort);
709
- }
710
- }
711
- async interrupt() {
712
- if (!this.hasInflightResponse()) {
713
- return;
714
- }
715
- this.sendEvent({
716
- type: "response.cancel"
717
- });
718
- }
719
- async truncate(_options) {
720
- const hasAudioModality = !_options.modalities || _options.modalities.includes("audio");
721
- const hasServerSideAudio = this.audioCapableItemIds.has(_options.messageId);
722
- if (hasAudioModality && hasServerSideAudio) {
723
- const audioEndMs = Number.isFinite(_options.audioEndMs) ? Math.max(0, Math.floor(_options.audioEndMs)) : 0;
724
- if (audioEndMs > 0) {
725
- this.sendEvent({
726
- type: "conversation.item.truncate",
727
- content_index: 0,
728
- item_id: _options.messageId,
729
- audio_end_ms: audioEndMs
730
- });
731
- } else {
732
- this.sendEvent({
733
- type: "conversation.item.delete",
734
- item_id: _options.messageId,
735
- event_id: shortuuid("chat_ctx_delete_")
736
- });
737
- }
738
- } else if (_options.audioTranscript !== void 0) {
739
- const chatCtx = this.chatCtx.copy();
740
- const idx = chatCtx.indexById(_options.messageId);
741
- if (idx !== void 0) {
742
- const item = chatCtx.items[idx];
743
- if (item && item.type === "message") {
744
- const newItem = llm.ChatMessage.create({
745
- ...item,
746
- content: [_options.audioTranscript]
747
- });
748
- chatCtx.items[idx] = newItem;
749
- const events = await this.createChatCtxUpdateEvents(chatCtx);
750
- for (const ev of events) {
751
- this.sendEvent(ev);
752
- }
753
- }
754
- }
755
- }
756
- }
757
- loggableEvent(event) {
758
- const untypedEvent = {};
759
- for (const [key, value] of Object.entries(event)) {
760
- if (value !== void 0) {
761
- untypedEvent[key] = value;
762
- }
763
- }
764
- if (untypedEvent.audio && typeof untypedEvent.audio === "string") {
765
- return { ...untypedEvent, audio: "..." };
766
- }
767
- if (untypedEvent.delta && typeof untypedEvent.delta === "string" && event.type === "response.audio.delta") {
768
- return { ...untypedEvent, delta: "..." };
769
- }
770
- return untypedEvent;
771
- }
772
- closeCurrentGeneration(reason = "provider abandonment") {
773
- if (this.currentGeneration instanceof DiscardedGeneration) {
774
- this.currentGeneration = void 0;
775
- return;
776
- }
777
- if (!this.currentGeneration) return;
778
- for (const gen of this.currentGeneration.messages.values()) {
779
- gen.textChannel.close();
780
- gen.audioChannel.close();
781
- if (!gen.modalities.done) {
782
- gen.modalities.resolve(this._options.modalities);
783
- }
784
- }
785
- this.currentGeneration.messages.clear();
786
- this.currentGeneration.messageChannel.close();
787
- this.currentGeneration.functionChannel.close();
788
- if (!this.currentGeneration._doneFut.done) {
789
- this.currentGeneration._doneFut.resolve();
790
- }
791
- this.#logger.warn(`In-progress generation discarded due to ${reason}`);
792
- this.currentGeneration = void 0;
793
- }
794
- rejectResponseCreatedFutures(reason) {
795
- for (const handle of Object.values(this.responseCreatedFutures)) {
796
- if (!handle.doneFut.done) {
797
- handle.doneFut.reject(new Error(reason));
798
- }
799
- if (handle.timeout) clearTimeout(handle.timeout);
800
- }
801
- this.responseCreatedFutures = {};
802
- }
803
- async createWsConn() {
804
- const headers = {
805
- "User-Agent": "LiveKit-Agents-JS"
806
- };
807
- if (this._options.isAzure) {
808
- if (this._options.entraToken) {
809
- headers.Authorization = `Bearer ${this._options.entraToken}`;
810
- } else if (this._options.apiKey) {
811
- headers["api-key"] = this._options.apiKey;
812
- } else {
813
- throw new Error("Microsoft API key or entraToken is required");
814
- }
815
- } else {
816
- if (!this._options.apiKey) {
817
- throw new Error(
818
- "OpenAI API key is required but not set. Check OPENAI_API_KEY environment variable."
819
- );
820
- }
821
- headers.Authorization = `Bearer ${this._options.apiKey}`;
822
- }
823
- const url = processBaseURL({
824
- baseURL: this._options.baseURL,
825
- model: this._options.model,
826
- isAzure: this._options.isAzure,
827
- apiVersion: this._options.apiVersion,
828
- azureDeployment: this._options.azureDeployment
829
- });
830
- if (lkOaiDebug) {
831
- this.#logger.debug(`Connecting to OpenAI Realtime API at ${url}`);
832
- }
833
- return new Promise((resolve, reject) => {
834
- const ws = new WebSocket(url, { headers });
835
- let waiting = true;
836
- const timeout = setTimeout(() => {
837
- ws.close();
838
- reject(new Error("WebSocket connection timeout"));
839
- }, this._options.connOptions.timeoutMs);
840
- ws.once("open", () => {
841
- if (!waiting) return;
842
- waiting = false;
843
- clearTimeout(timeout);
844
- resolve(ws);
845
- });
846
- ws.once("close", () => {
847
- if (!waiting) return;
848
- waiting = false;
849
- clearTimeout(timeout);
850
- reject(new Error("OpenAI Realtime API connection closed"));
851
- });
852
- });
853
- }
854
- async #mainTask(signal) {
855
- let reconnecting = false;
856
- let numRetries = 0;
857
- let wsConn = null;
858
- const maxRetries = this._options.connOptions.maxRetry;
859
- const reconnect = async () => {
860
- this.#logger.debug(
861
- {
862
- maxSessionDuration: this._options.maxSessionDuration
863
- },
864
- "Reconnecting to OpenAI Realtime API"
865
- );
866
- this.rejectResponseCreatedFutures("Session reconnected");
867
- this.discardedEventIds.clear();
868
- this.closeCurrentGeneration("session reconnection");
869
- this.audioCapableItemIds.clear();
870
- this.resetInputTurnState();
871
- const events = [];
872
- events.push(this.createSessionUpdateEvent());
873
- if (Object.keys(this._tools.functionTools).length > 0) {
874
- events.push(this.createToolsUpdateEvent(this._tools));
875
- }
876
- const fullChatCtx = this.chatCtx;
877
- const chatCtx = fullChatCtx.copy({
878
- excludeInstructions: true,
879
- excludeEmptyMessage: true
880
- });
881
- const oldChatCtx = this.remoteChatCtx;
882
- this.remoteChatCtx = new llm.RemoteChatContext();
883
- const replayEvents = await this.createChatCtxUpdateEvents(chatCtx);
884
- events.push(...replayEvents);
885
- const availableItemIds = new Set(
886
- replayEvents.filter((event) => event.type === "conversation.item.create").map((event) => event.item.id)
887
- );
888
- this.replayItemCreateEventIds = {};
889
- this.replayItemCreateEventItems = {};
890
- for (const event of replayEvents) {
891
- if (event.type === "conversation.item.create" && event.event_id && this.itemCreateFutures[event.item.id]) {
892
- (this.replayItemCreateEventIds[event.item.id] ??= []).push(event.event_id);
893
- this.replayItemCreateEventItems[event.event_id] = event.item.id;
894
- }
895
- }
896
- for (const [eventId, event] of Object.entries(this.sentChatCtxEvents)) {
897
- const future = this.chatCtxEventFutures[eventId];
898
- if (!future || future.done) continue;
899
- if (event.type === "conversation.item.create") {
900
- let previousItemId = event.previous_item_id;
901
- if (previousItemId && !availableItemIds.has(previousItemId)) {
902
- const previousIndex = fullChatCtx.indexById(previousItemId);
903
- previousItemId = void 0;
904
- if (previousIndex !== void 0) {
905
- for (let i = previousIndex - 1; i >= 0; i--) {
906
- const candidateId = fullChatCtx.items[i].id;
907
- if (availableItemIds.has(candidateId)) {
908
- previousItemId = candidateId;
909
- break;
910
- }
911
- }
912
- }
913
- }
914
- events.push({ ...event, previous_item_id: previousItemId });
915
- availableItemIds.add(event.item.id);
916
- } else {
917
- events.push(event);
918
- }
919
- }
920
- try {
921
- for (const ev of events) {
922
- this.emit("openai_client_event_queued", ev);
923
- if (this._options.isAzure && this._options.apiVersion) {
924
- normalizeAzureClientEvent(ev);
925
- }
926
- wsConn.send(JSON.stringify(ev));
927
- }
928
- } catch (error) {
929
- this.remoteChatCtx = oldChatCtx;
930
- throw new APIConnectionError({
931
- message: "Failed to send message to OpenAI Realtime API during session re-connection"
932
- });
933
- }
934
- this.#logger.debug("Reconnected to OpenAI Realtime API");
935
- this.emit("session_reconnected", {});
936
- };
937
- reconnecting = false;
938
- try {
939
- while (!this.#closed && !signal.aborted) {
940
- this.#logger.debug("Creating WebSocket connection to OpenAI Realtime API");
941
- wsConn = await this.createWsConn();
942
- if (signal.aborted) break;
943
- try {
944
- if (reconnecting) {
945
- await reconnect();
946
- if (signal.aborted) break;
947
- numRetries = 0;
948
- }
949
- await this.runWs(wsConn);
950
- if (signal.aborted) break;
951
- } catch (error) {
952
- if (!isAPIError(error)) {
953
- this.emitError({ error, recoverable: false });
954
- throw error;
955
- }
956
- if (maxRetries === 0 || !error.retryable) {
957
- this.emitError({ error, recoverable: false });
958
- throw error;
959
- }
960
- if (numRetries === maxRetries) {
961
- this.emitError({ error, recoverable: false });
962
- throw new APIConnectionError({
963
- message: `OpenAI Realtime API connection failed after ${numRetries} attempts`,
964
- options: {
965
- body: error,
966
- retryable: false
967
- }
968
- });
969
- }
970
- this.emitError({ error, recoverable: true });
971
- const retryInterval = numRetries === 0 ? DEFAULT_FIRST_RETRY_INTERVAL_MS : this._options.connOptions.retryIntervalMs;
972
- this.#logger.warn(
973
- {
974
- attempt: numRetries,
975
- maxRetries,
976
- error
977
- },
978
- `OpenAI Realtime API connection failed, retrying in ${retryInterval / 1e3}s`
979
- );
980
- await delay(retryInterval);
981
- numRetries++;
982
- }
983
- reconnecting = true;
984
- }
985
- } finally {
986
- this.closeCurrentGeneration("session close");
987
- this.rejectResponseCreatedFutures("Realtime session closed");
988
- }
989
- }
990
- async runWs(wsConn) {
991
- const forwardEvents = async (signal) => {
992
- const abortFuture = new Future();
993
- signal.addEventListener("abort", () => abortFuture.resolve());
994
- while (!this.#closed && wsConn.readyState === WebSocket.OPEN && !signal.aborted) {
995
- try {
996
- const event = await Promise.race([this.messageChannel.get(), abortFuture.await]);
997
- if (signal.aborted || abortFuture.done || event === void 0) {
998
- break;
999
- }
1000
- if (lkOaiDebug && event.type !== "input_audio_buffer.append") {
1001
- this.#logger.debug(
1002
- {
1003
- eventType: event.type,
1004
- "lk.pii.event": this.loggableEvent(event)
1005
- },
1006
- "sent OpenAI Realtime client event"
1007
- );
1008
- }
1009
- this.emit("openai_client_event_queued", event);
1010
- if (this._options.isAzure && this._options.apiVersion) {
1011
- normalizeAzureClientEvent(event);
1012
- }
1013
- wsConn.send(JSON.stringify(event));
1014
- if (event.event_id && this.chatCtxEventFutures[event.event_id]) {
1015
- this.sentChatCtxEvents[event.event_id] = event;
1016
- }
1017
- } catch (error) {
1018
- break;
1019
- }
1020
- }
1021
- wsConn.close();
1022
- };
1023
- const wsCloseFuture = new Future();
1024
- wsConn.onerror = (error) => {
1025
- wsCloseFuture.resolve(new APIConnectionError({ message: error.message }));
1026
- };
1027
- wsConn.onclose = () => {
1028
- wsCloseFuture.resolve();
1029
- };
1030
- wsConn.onmessage = (message) => {
1031
- const event = JSON.parse(message.data);
1032
- this.emit("openai_server_event_received", event);
1033
- if (lkOaiDebug) {
1034
- this.#logger.debug(
1035
- {
1036
- eventType: event.type,
1037
- "lk.pii.event": this.loggableEvent(event)
1038
- },
1039
- "received OpenAI Realtime server event"
1040
- );
1041
- }
1042
- try {
1043
- switch (event.type) {
1044
- case "input_audio_buffer.speech_started":
1045
- this.handleInputAudioBufferSpeechStarted(event);
1046
- break;
1047
- case "input_audio_buffer.speech_stopped":
1048
- this.handleInputAudioBufferSpeechStopped(event);
1049
- break;
1050
- case "response.created":
1051
- this.handleResponseCreated(event);
1052
- break;
1053
- case "response.output_item.added":
1054
- this.handleResponseOutputItemAdded(event);
1055
- break;
1056
- case "conversation.item.added":
1057
- case "conversation.item.created":
1058
- this.handleConversationItemCreated(event);
1059
- break;
1060
- case "conversation.item.deleted":
1061
- this.handleConversationItemDeleted(event);
1062
- break;
1063
- case "conversation.item.input_audio_transcription.delta":
1064
- this.handleConversationItemInputAudioTranscriptionDelta(event);
1065
- break;
1066
- case "conversation.item.input_audio_transcription.completed":
1067
- this.handleConversationItemInputAudioTranscriptionCompleted(event);
1068
- break;
1069
- case "conversation.item.input_audio_transcription.failed":
1070
- this.handleConversationItemInputAudioTranscriptionFailed(event);
1071
- break;
1072
- case "response.content_part.added":
1073
- this.handleResponseContentPartAdded(event);
1074
- break;
1075
- case "response.content_part.done":
1076
- this.handleResponseContentPartDone(event);
1077
- break;
1078
- case "response.output_text.delta":
1079
- case "response.text.delta":
1080
- this.handleResponseTextDelta(event);
1081
- break;
1082
- case "response.output_text.done":
1083
- case "response.text.done":
1084
- this.handleResponseTextDone(event);
1085
- break;
1086
- case "response.output_audio_transcript.delta":
1087
- case "response.audio_transcript.delta":
1088
- this.handleResponseAudioTranscriptDelta(event);
1089
- break;
1090
- case "response.output_audio.delta":
1091
- case "response.audio.delta":
1092
- this.handleResponseAudioDelta(event);
1093
- break;
1094
- case "response.output_audio_transcript.done":
1095
- case "response.audio_transcript.done":
1096
- this.handleResponseAudioTranscriptDone(event);
1097
- break;
1098
- case "response.output_audio.done":
1099
- case "response.audio.done":
1100
- this.handleResponseAudioDone(event);
1101
- break;
1102
- case "response.output_item.done":
1103
- this.handleResponseOutputItemDone(event);
1104
- break;
1105
- case "response.done":
1106
- this.handleResponseDone(event);
1107
- break;
1108
- case "error":
1109
- this.handleError(event);
1110
- break;
1111
- default:
1112
- if (lkOaiDebug) {
1113
- this.#logger.debug(`unhandled event: ${event.type}`);
1114
- }
1115
- break;
1116
- }
1117
- } catch (error) {
1118
- if (isAPIError(error) && !error.retryable) {
1119
- wsCloseFuture.resolve(error);
1120
- wsConn.close();
1121
- return;
1122
- }
1123
- this.#logger.error(
1124
- {
1125
- error,
1126
- "lk.pii.event": event
1127
- },
1128
- "Failed to handle OpenAI Realtime API event"
1129
- );
1130
- }
1131
- };
1132
- const sendTask = Task.from(({ signal }) => forwardEvents(signal));
1133
- const wsTask = Task.from(({ signal }) => {
1134
- const abortPromise = new Promise((resolve) => {
1135
- signal.addEventListener("abort", () => {
1136
- resolve();
1137
- });
1138
- });
1139
- return Promise.race([wsCloseFuture.await, abortPromise]);
1140
- });
1141
- const waitReconnectTask = Task.from(async ({ signal }) => {
1142
- await delay(this._options.maxSessionDuration, { signal });
1143
- return new APIConnectionError({
1144
- message: "OpenAI Realtime API connection timeout"
1145
- });
1146
- });
1147
- try {
1148
- const result = await Promise.race([wsTask.result, sendTask.result, waitReconnectTask.result]);
1149
- const currentGeneration = this.currentGeneration;
1150
- if (waitReconnectTask.done && currentGeneration) {
1151
- if (currentGeneration instanceof DiscardedGeneration) {
1152
- this.currentGeneration = void 0;
1153
- } else {
1154
- await currentGeneration._doneFut.await;
1155
- }
1156
- }
1157
- if (result instanceof Error) {
1158
- throw result;
1159
- }
1160
- } finally {
1161
- await cancelAndWait([wsTask, sendTask, waitReconnectTask], 2e3);
1162
- wsConn.close();
1163
- }
1164
- }
1165
- async close() {
1166
- this.resetInputTurnState();
1167
- super.close();
1168
- this.#closed = true;
1169
- await this.#task;
1170
- this.rejectResponseCreatedFutures("Session closed");
1171
- for (const fut of Object.values(this.itemCreateFutures)) {
1172
- if (!fut.done) {
1173
- fut.reject(new Error("Session closed"));
1174
- }
1175
- }
1176
- this.itemCreateFutures = {};
1177
- for (const fut of Object.values(this.itemDeleteFutures)) {
1178
- if (!fut.done) {
1179
- fut.reject(new Error("Session closed"));
1180
- }
1181
- }
1182
- this.itemDeleteFutures = {};
1183
- this.replayItemCreateEventIds = {};
1184
- this.replayItemCreateEventItems = {};
1185
- this.inputTranscriptAccumulators.clear();
1186
- this.closeCurrentGeneration("Session closed");
1187
- this.messageChannel.items.length = 0;
1188
- }
1189
- resetInputTurnState() {
1190
- this.inputTranscriptAccumulators.clear();
1191
- }
1192
- handleInputAudioBufferSpeechStarted(_event) {
1193
- this.emit("input_speech_started", {});
1194
- }
1195
- handleInputAudioBufferSpeechStopped(_event) {
1196
- this.emit("input_speech_stopped", {
1197
- userTranscriptionEnabled: this._options.inputAudioTranscription !== null
1198
- });
1199
- }
1200
- handleResponseCreated(event) {
1201
- var _a;
1202
- if (!event.response.id) {
1203
- throw new Error("response.id is missing");
1204
- }
1205
- const clientEventId = (_a = event.response.metadata) == null ? void 0 : _a.client_event_id;
1206
- if (clientEventId && this.discardedEventIds.has(clientEventId)) {
1207
- this.discardedEventIds.delete(clientEventId);
1208
- this.sendEvent({
1209
- type: "response.cancel",
1210
- response_id: event.response.id
1211
- });
1212
- this.currentGeneration = new DiscardedGeneration();
1213
- this.#logger.warn("discarding response that arrived after it was timed out or interrupted");
1214
- return;
1215
- }
1216
- const currentGeneration = {
1217
- messageChannel: stream.createStreamChannel(),
1218
- functionChannel: stream.createStreamChannel(),
1219
- messages: /* @__PURE__ */ new Map(),
1220
- _doneFut: new Future(),
1221
- _createdTimestamp: Date.now()
1222
- };
1223
- this.currentGeneration = currentGeneration;
1224
- const generationEv = {
1225
- messageStream: currentGeneration.messageChannel.stream(),
1226
- functionStream: currentGeneration.functionChannel.stream(),
1227
- userInitiated: false,
1228
- responseId: event.response.id
1229
- };
1230
- if (clientEventId) {
1231
- const handle = this.responseCreatedFutures[clientEventId];
1232
- if (handle) {
1233
- delete this.responseCreatedFutures[clientEventId];
1234
- if (handle.timeout) clearTimeout(handle.timeout);
1235
- generationEv.userInitiated = true;
1236
- if (!handle.doneFut.done) {
1237
- handle.doneFut.resolve(generationEv);
1238
- }
1239
- }
1240
- }
1241
- this.emit("generation_created", generationEv);
1242
- }
1243
- handleResponseOutputItemAdded(event) {
1244
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1245
- if (!this.currentGeneration) {
1246
- throw new Error("currentGeneration is not set");
1247
- }
1248
- if (!event.item.type) {
1249
- throw new Error("item.type is not set");
1250
- }
1251
- const itemType = event.item.type;
1252
- if (itemType !== "message") {
1253
- this.textModeRecoveryRetries = 0;
1254
- return;
1255
- }
1256
- const itemId = event.item.id;
1257
- if (!itemId) {
1258
- throw new Error("item.id is not set");
1259
- }
1260
- const modalitiesFut = new Future();
1261
- const itemGeneration = {
1262
- messageId: itemId,
1263
- textChannel: stream.createStreamChannel(),
1264
- audioChannel: stream.createStreamChannel(),
1265
- audioTranscript: "",
1266
- modalities: modalitiesFut
1267
- };
1268
- if (!this.oaiRealtimeModel.capabilities.audioOutput) {
1269
- itemGeneration.audioChannel.close();
1270
- modalitiesFut.resolve(["text"]);
1271
- }
1272
- this.currentGeneration.messageChannel.write({
1273
- messageId: itemId,
1274
- textStream: itemGeneration.textChannel.stream(),
1275
- audioStream: itemGeneration.audioChannel.stream(),
1276
- modalities: modalitiesFut.await
1277
- });
1278
- this.currentGeneration.messages.set(itemId, itemGeneration);
1279
- }
1280
- handleConversationItemCreated(event) {
1281
- if (!event.item.id) {
1282
- throw new Error("item.id is not set");
1283
- }
1284
- const serverEventType = event.type;
1285
- const incomingItem = openAIItemToLivekitItem(event.item);
1286
- const existingItem = this.remoteChatCtx.get(event.item.id);
1287
- const replayConfirmation = this.consumeReplayItemCreate(event.item.id);
1288
- const pendingCreateFuture = replayConfirmation ? void 0 : this.itemCreateFutures[event.item.id];
1289
- if (existingItem && serverEventType === "conversation.item.added" && !pendingCreateFuture) {
1290
- return;
1291
- }
1292
- try {
1293
- this.remoteChatCtx.insert(event.previous_item_id, incomingItem);
1294
- } catch (error) {
1295
- this.#logger.error({ error, itemId: event.item.id }, "failed to insert conversation item");
1296
- }
1297
- const fut = pendingCreateFuture;
1298
- if (fut) {
1299
- if (!fut.done) fut.resolve();
1300
- delete this.itemCreateFutures[event.item.id];
1301
- }
1302
- }
1303
- handleConversationItemDeleted(event) {
1304
- if (!event.item_id) {
1305
- throw new Error("item_id is not set");
1306
- }
1307
- this.audioCapableItemIds.delete(event.item_id);
1308
- this.inputTranscriptAccumulators.delete(event.item_id);
1309
- try {
1310
- this.remoteChatCtx.delete(event.item_id);
1311
- } catch (error) {
1312
- this.#logger.error({ error, itemId: event.item_id }, "failed to delete conversation item");
1313
- }
1314
- const fut = this.itemDeleteFutures[event.item_id];
1315
- if (fut) {
1316
- if (!fut.done) fut.resolve();
1317
- delete this.itemDeleteFutures[event.item_id];
1318
- }
1319
- }
1320
- handleConversationItemInputAudioTranscriptionDelta(event) {
1321
- if (!event.delta) return;
1322
- const contentIndex = event.content_index ?? 0;
1323
- let byIndex = this.inputTranscriptAccumulators.get(event.item_id);
1324
- if (!byIndex) {
1325
- byIndex = /* @__PURE__ */ new Map();
1326
- this.inputTranscriptAccumulators.set(event.item_id, byIndex);
1327
- }
1328
- const accumulated = (byIndex.get(contentIndex) ?? "") + event.delta;
1329
- byIndex.set(contentIndex, accumulated);
1330
- this.emit("input_audio_transcription_completed", {
1331
- itemId: event.item_id,
1332
- transcript: accumulated,
1333
- isFinal: false
1334
- });
1335
- }
1336
- clearAccumulator(itemId, contentIndex) {
1337
- const byIndex = this.inputTranscriptAccumulators.get(itemId);
1338
- if (!byIndex) return void 0;
1339
- const partial = byIndex.get(contentIndex);
1340
- byIndex.delete(contentIndex);
1341
- if (byIndex.size === 0) this.inputTranscriptAccumulators.delete(itemId);
1342
- return partial;
1343
- }
1344
- handleConversationItemInputAudioTranscriptionCompleted(event) {
1345
- if (event.status === "in_progress") {
1346
- this.emit("input_audio_transcription_completed", {
1347
- itemId: event.item_id,
1348
- transcript: event.transcript,
1349
- isFinal: false
1350
- });
1351
- return;
1352
- }
1353
- this.clearAccumulator(event.item_id, event.content_index ?? 0);
1354
- const remoteItem = this.remoteChatCtx.get(event.item_id);
1355
- if (remoteItem) {
1356
- const item = remoteItem.item;
1357
- if (item instanceof llm.ChatMessage) {
1358
- item.content.push(event.transcript);
1359
- } else {
1360
- throw new Error("item is not a chat message");
1361
- }
1362
- }
1363
- this.emit("input_audio_transcription_completed", {
1364
- itemId: event.item_id,
1365
- transcript: event.transcript,
1366
- isFinal: true
1367
- });
1368
- }
1369
- handleConversationItemInputAudioTranscriptionFailed(event) {
1370
- this.#logger.error(
1371
- { error: event.error },
1372
- "OpenAI Realtime API failed to transcribe input audio"
1373
- );
1374
- this.finalizePartialOnTranscriptionFailure(event.item_id, event.content_index ?? 0);
1375
- }
1376
- // Close any open partial stream so consumers waiting for isFinal don't hang.
1377
- finalizePartialOnTranscriptionFailure(itemId, contentIndex) {
1378
- const partial = this.clearAccumulator(itemId, contentIndex);
1379
- if (partial === void 0) return;
1380
- this.emit("input_audio_transcription_completed", {
1381
- itemId,
1382
- transcript: partial,
1383
- isFinal: true
1384
- });
1385
- }
1386
- handleResponseContentPartAdded(event) {
1387
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1388
- if (!this.currentGeneration) {
1389
- throw new Error("currentGeneration is not set");
1390
- }
1391
- const itemId = event.item_id;
1392
- const itemType = event.part.type;
1393
- const itemGeneration = this.currentGeneration.messages.get(itemId);
1394
- if (!itemGeneration) {
1395
- this.#logger.warn(`itemGeneration not found for itemId=${itemId}`);
1396
- return;
1397
- }
1398
- const isTextType = itemType === "text" || itemType === "output_text";
1399
- if (isTextType && this.oaiRealtimeModel.capabilities.audioOutput) {
1400
- this.#logger.warn("Text response received from OpenAI Realtime API in audio modality.");
1401
- }
1402
- if (!itemGeneration.modalities.done) {
1403
- const modalityResult = isTextType ? ["text"] : ["audio", "text"];
1404
- itemGeneration.modalities.resolve(modalityResult);
1405
- if (!isTextType) {
1406
- this.audioCapableItemIds.add(itemId);
1407
- }
1408
- }
1409
- if (this.currentGeneration._firstTokenTimestamp === void 0) {
1410
- this.currentGeneration._firstTokenTimestamp = Date.now();
1411
- }
1412
- }
1413
- handleResponseContentPartDone(event) {
1414
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1415
- if (!event.part) {
1416
- return;
1417
- }
1418
- if (event.part.type !== "text") {
1419
- return;
1420
- }
1421
- if (!this.currentGeneration) {
1422
- throw new Error("currentGeneration is not set");
1423
- }
1424
- }
1425
- handleResponseTextDelta(event) {
1426
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1427
- if (!this.currentGeneration) {
1428
- throw new Error("currentGeneration is not set");
1429
- }
1430
- const itemGeneration = this.currentGeneration.messages.get(event.item_id);
1431
- if (!itemGeneration) {
1432
- throw new Error("itemGeneration is not set");
1433
- }
1434
- if (!this.oaiRealtimeModel.capabilities.audioOutput && !this.currentGeneration._firstTokenTimestamp) {
1435
- this.currentGeneration._firstTokenTimestamp = Date.now();
1436
- }
1437
- itemGeneration.textChannel.write(event.delta);
1438
- itemGeneration.audioTranscript += event.delta;
1439
- }
1440
- handleResponseTextDone(_event) {
1441
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1442
- if (!this.currentGeneration) {
1443
- throw new Error("currentGeneration is not set");
1444
- }
1445
- }
1446
- handleResponseAudioTranscriptDelta(event) {
1447
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1448
- if (!this.currentGeneration) {
1449
- throw new Error("currentGeneration is not set");
1450
- }
1451
- const itemId = event.item_id;
1452
- let delta = event.delta;
1453
- if (event.start_time !== void 0) {
1454
- delta = createTimedString({ text: event.delta, startTime: event.start_time });
1455
- }
1456
- const itemGeneration = this.currentGeneration.messages.get(itemId);
1457
- if (!itemGeneration) {
1458
- throw new Error("itemGeneration is not set");
1459
- } else {
1460
- itemGeneration.textChannel.write(delta);
1461
- itemGeneration.audioTranscript += event.delta;
1462
- }
1463
- }
1464
- handleResponseAudioDelta(event) {
1465
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1466
- if (!this.currentGeneration) {
1467
- throw new Error("currentGeneration is not set");
1468
- }
1469
- const itemGeneration = this.currentGeneration.messages.get(event.item_id);
1470
- if (!itemGeneration) {
1471
- throw new Error("itemGeneration is not set");
1472
- }
1473
- if (this.currentGeneration._firstTokenTimestamp === void 0) {
1474
- this.currentGeneration._firstTokenTimestamp = Date.now();
1475
- }
1476
- if (!itemGeneration.modalities.done) {
1477
- itemGeneration.modalities.resolve(["audio", "text"]);
1478
- }
1479
- const binaryString = atob(event.delta);
1480
- const len = binaryString.length;
1481
- const bytes = new Uint8Array(len);
1482
- for (let i = 0; i < len; i++) {
1483
- bytes[i] = binaryString.charCodeAt(i);
1484
- }
1485
- itemGeneration.audioChannel.write(
1486
- new AudioFrame(
1487
- new Int16Array(bytes.buffer),
1488
- api_proto.SAMPLE_RATE,
1489
- api_proto.NUM_CHANNELS,
1490
- bytes.length / 2
1491
- )
1492
- );
1493
- }
1494
- handleResponseAudioTranscriptDone(_event) {
1495
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1496
- if (!this.currentGeneration) {
1497
- throw new Error("currentGeneration is not set");
1498
- }
1499
- }
1500
- handleResponseAudioDone(_event) {
1501
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1502
- if (!this.currentGeneration) {
1503
- throw new Error("currentGeneration is not set");
1504
- }
1505
- }
1506
- handleResponseOutputItemDone(event) {
1507
- if (event.item.type === "function_call") {
1508
- const remoteItem = this.remoteChatCtx.get(event.item.id);
1509
- if ((remoteItem == null ? void 0 : remoteItem.item) instanceof llm.FunctionCall) {
1510
- remoteItem.item.args = event.item.arguments;
1511
- }
1512
- }
1513
- if (this.currentGeneration instanceof DiscardedGeneration) return;
1514
- if (!this.currentGeneration) {
1515
- throw new Error("currentGeneration is not set");
1516
- }
1517
- const itemId = event.item.id;
1518
- const itemType = event.item.type;
1519
- if (itemType === "function_call") {
1520
- const item = event.item;
1521
- if (!item.call_id || !item.name || !item.arguments) {
1522
- throw new Error("item is not a function call");
1523
- }
1524
- this.currentGeneration.functionChannel.write(
1525
- llm.FunctionCall.create({
1526
- callId: item.call_id,
1527
- name: item.name,
1528
- args: item.arguments
1529
- })
1530
- );
1531
- } else if (itemType === "message") {
1532
- const itemGeneration = this.currentGeneration.messages.get(itemId);
1533
- if (!itemGeneration) {
1534
- return;
1535
- }
1536
- itemGeneration.textChannel.close();
1537
- itemGeneration.audioChannel.close();
1538
- if (!itemGeneration.modalities.done) {
1539
- itemGeneration.modalities.resolve(this._options.modalities);
1540
- }
1541
- }
1542
- }
1543
- handleResponseDone(_event) {
1544
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
1545
- if (this.currentGeneration instanceof DiscardedGeneration) {
1546
- this.currentGeneration = void 0;
1547
- return;
1548
- }
1549
- if (!this.currentGeneration) {
1550
- return;
1551
- }
1552
- const createdTimestamp = this.currentGeneration._createdTimestamp;
1553
- const firstTokenTimestamp = this.currentGeneration._firstTokenTimestamp;
1554
- this.#logger.debug(
1555
- {
1556
- messageCount: this.currentGeneration.messages.size
1557
- },
1558
- "Closing generation channels in handleResponseDone"
1559
- );
1560
- for (const generation of this.currentGeneration.messages.values()) {
1561
- generation.textChannel.close();
1562
- generation.audioChannel.close();
1563
- if (!generation.modalities.done) {
1564
- generation.modalities.resolve(this._options.modalities);
1565
- }
1566
- }
1567
- this.currentGeneration.functionChannel.close();
1568
- this.currentGeneration.messageChannel.close();
1569
- for (const itemId of this.currentGeneration.messages.keys()) {
1570
- const remoteItem = this.remoteChatCtx.get(itemId);
1571
- if (remoteItem && remoteItem.item instanceof llm.ChatMessage) {
1572
- remoteItem.item.content.push(this.currentGeneration.messages.get(itemId).audioTranscript);
1573
- }
1574
- }
1575
- this.currentGeneration._doneFut.resolve();
1576
- this.currentGeneration = void 0;
1577
- const usage = _event.response.usage;
1578
- const ttftMs = firstTokenTimestamp ? firstTokenTimestamp - createdTimestamp : -1;
1579
- const durationMs = Date.now() - createdTimestamp;
1580
- const realtimeMetrics = {
1581
- type: "realtime_model_metrics",
1582
- timestamp: createdTimestamp,
1583
- requestId: _event.response.id || "",
1584
- ttftMs,
1585
- durationMs,
1586
- cancelled: _event.response.status === "cancelled",
1587
- label: "openai_realtime",
1588
- inputTokens: (usage == null ? void 0 : usage.input_tokens) ?? 0,
1589
- outputTokens: (usage == null ? void 0 : usage.output_tokens) ?? 0,
1590
- totalTokens: (usage == null ? void 0 : usage.total_tokens) ?? 0,
1591
- tokensPerSecond: durationMs > 0 ? ((usage == null ? void 0 : usage.output_tokens) ?? 0) / (durationMs / 1e3) : 0,
1592
- inputTokenDetails: {
1593
- audioTokens: ((_a = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _a.audio_tokens) ?? 0,
1594
- textTokens: ((_b = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _b.text_tokens) ?? 0,
1595
- imageTokens: 0,
1596
- // Not supported yet
1597
- cachedTokens: ((_c = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _c.cached_tokens) ?? 0,
1598
- cachedTokensDetails: ((_d = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _d.cached_tokens_details) ? {
1599
- audioTokens: ((_f = (_e = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _e.cached_tokens_details) == null ? void 0 : _f.audio_tokens) ?? 0,
1600
- textTokens: ((_h = (_g = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _g.cached_tokens_details) == null ? void 0 : _h.text_tokens) ?? 0,
1601
- imageTokens: ((_j = (_i = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _i.cached_tokens_details) == null ? void 0 : _j.image_tokens) ?? 0
1602
- } : void 0
1603
- },
1604
- outputTokenDetails: {
1605
- textTokens: ((_k = usage == null ? void 0 : usage.output_token_details) == null ? void 0 : _k.text_tokens) ?? 0,
1606
- audioTokens: ((_l = usage == null ? void 0 : usage.output_token_details) == null ? void 0 : _l.audio_tokens) ?? 0,
1607
- imageTokens: 0
1608
- }
1609
- };
1610
- this.emit("metrics_collected", realtimeMetrics);
1611
- this.handleResponseDoneButNotComplete(_event);
1612
- }
1613
- handleResponseDoneButNotComplete(event) {
1614
- if (event.response.status === "completed") {
1615
- return;
1616
- }
1617
- const statusDetails = event.response.status_details;
1618
- if (event.response.status === "failed") {
1619
- const errorBody = typeof statusDetails !== "string" && (statusDetails == null ? void 0 : statusDetails.type) === "failed" ? statusDetails.error : void 0;
1620
- const errorTypeValue = errorBody && "type" in errorBody ? errorBody.type : void 0;
1621
- const errorType = typeof errorTypeValue === "string" ? errorTypeValue : "unknown";
1622
- const recoverable = !isFatalError(errorBody);
1623
- const error = new APIError(
1624
- `OpenAI Realtime API response failed with error type: ${errorType}`,
1625
- {
1626
- body: errorBody ?? null,
1627
- retryable: recoverable
1628
- }
1629
- );
1630
- if (!recoverable) {
1631
- throw error;
1632
- }
1633
- this.emitError({ error, recoverable: true });
1634
- } else if (event.response.status === "cancelled" || event.response.status === "incomplete") {
1635
- let statusType;
1636
- let statusReason;
1637
- if (typeof statusDetails === "string") {
1638
- statusType = statusDetails;
1639
- } else {
1640
- statusType = statusDetails == null ? void 0 : statusDetails.type;
1641
- statusReason = statusDetails && "reason" in statusDetails ? statusDetails.reason : void 0;
1642
- }
1643
- this.#logger.debug(
1644
- {
1645
- eventId: event.response.id,
1646
- eventResponseStatus: event.response.status,
1647
- eventResponseStatusType: statusType,
1648
- eventResponseStatusReason: statusReason
1649
- },
1650
- `OpenAI Realtime API response done but not complete with status: ${event.response.status} (type=${statusType}, reason=${statusReason})`
1651
- );
1652
- } else {
1653
- this.#logger.debug({ eventResponseStatus: event.response.status }, "Unknown response status");
1654
- }
1655
- }
1656
- handleError(event) {
1657
- const eventId = event.error.event_id;
1658
- if (eventId) {
1659
- const replayItemId = this.replayItemCreateEventItems[eventId];
1660
- if (replayItemId) {
1661
- this.consumeReplayItemCreate(replayItemId, eventId);
1662
- }
1663
- const future = this.chatCtxEventFutures[eventId];
1664
- if (future) {
1665
- delete this.chatCtxEventFutures[eventId];
1666
- if (!future.done) future.reject(new Error(event.error.message));
1667
- if (!isFatalError(event.error)) return;
1668
- }
1669
- }
1670
- if (event.error.message.startsWith("Cancellation failed")) {
1671
- return;
1672
- }
1673
- this.#logger.error({ error: event.error }, "OpenAI Realtime API returned an error");
1674
- if (eventId) {
1675
- const handle = this.responseCreatedFutures[eventId];
1676
- if (handle) {
1677
- delete this.responseCreatedFutures[eventId];
1678
- if (handle.timeout) clearTimeout(handle.timeout);
1679
- if (!handle.doneFut.done) {
1680
- handle.doneFut.reject(new Error(event.error.message));
1681
- }
1682
- }
1683
- }
1684
- const recoverable = !isFatalError(event.error);
1685
- const error = new APIError(event.error.message, {
1686
- body: event.error,
1687
- retryable: recoverable
1688
- });
1689
- if (!recoverable) {
1690
- throw error;
1691
- }
1692
- this.emitError({ error, recoverable: true });
1693
- }
1694
- consumeReplayItemCreate(itemId, eventId) {
1695
- const eventIds = this.replayItemCreateEventIds[itemId];
1696
- if (!(eventIds == null ? void 0 : eventIds.length)) return false;
1697
- const index = eventId ? eventIds.indexOf(eventId) : 0;
1698
- if (index === -1) return false;
1699
- const [consumedEventId] = eventIds.splice(index, 1);
1700
- if (consumedEventId) delete this.replayItemCreateEventItems[consumedEventId];
1701
- if (eventIds.length === 0) delete this.replayItemCreateEventIds[itemId];
1702
- return true;
1703
- }
1704
- emitError({ error, recoverable }) {
1705
- this.emit("error", {
1706
- type: "realtime_model_error",
1707
- timestamp: Date.now(),
1708
- // TODO(brian): add label
1709
- label: "",
1710
- error,
1711
- recoverable
1712
- });
1713
- }
1714
- *resampleAudio(frame) {
1715
- yield frame;
1716
- }
1717
- createResponse({
1718
- userInitiated,
1719
- instructions,
1720
- oldHandle
1721
- }) {
1722
- const handle = oldHandle || new CreateResponseHandle({ instructions });
1723
- if (oldHandle && instructions) {
1724
- handle.instructions = instructions;
1725
- }
1726
- const eventId = shortuuid("response_create_");
1727
- this.discardedEventIds ??= /* @__PURE__ */ new Set();
1728
- if (userInitiated) {
1729
- this.responseCreatedFutures[eventId] = handle;
1730
- handle.timeout = setTimeout(() => {
1731
- if (this.responseCreatedFutures[eventId] === handle) {
1732
- delete this.responseCreatedFutures[eventId];
1733
- }
1734
- if (!handle.doneFut.done) {
1735
- this.discardedEventIds.add(eventId);
1736
- handle.doneFut.reject(new Error("generateReply timed out."));
1737
- }
1738
- }, 1e4);
1739
- }
1740
- const response = {};
1741
- if (instructions) response.instructions = instructions;
1742
- if (userInitiated) response.metadata = { client_event_id: eventId };
1743
- this.sendEvent({
1744
- type: "response.create",
1745
- event_id: eventId,
1746
- response: Object.keys(response).length > 0 ? response : void 0
1747
- });
1748
- return handle;
1749
- }
1750
- }
1751
- async function livekitItemToOpenAIItem(item) {
1752
- switch (item.type) {
1753
- case "function_call":
1754
- return {
1755
- id: item.id,
1756
- type: "function_call",
1757
- call_id: item.callId,
1758
- name: item.name,
1759
- arguments: item.args
1760
- };
1761
- case "function_call_output":
1762
- return {
1763
- id: item.id,
1764
- type: "function_call_output",
1765
- call_id: item.callId,
1766
- output: item.output
1767
- };
1768
- case "message":
1769
- const role = item.role === "developer" ? "system" : item.role;
1770
- const contentList = [];
1771
- for (const c of item.content) {
1772
- if (typeof c === "string") {
1773
- contentList.push({
1774
- type: role === "assistant" ? "output_text" : "input_text",
1775
- text: c
1776
- });
1777
- } else if (c.type === "image_content") {
1778
- if (role !== "user") continue;
1779
- const serialized = await llm.serializeImage(c);
1780
- if (serialized.externalUrl) {
1781
- log().warn("External URL is not supported for input_image in realtime API");
1782
- continue;
1783
- }
1784
- if (!serialized.base64Data) {
1785
- log().warn("Serialized image has no data bytes");
1786
- continue;
1787
- }
1788
- contentList.push({
1789
- type: "input_image",
1790
- image_url: `data:${serialized.mimeType};base64,${serialized.base64Data}`
1791
- });
1792
- } else if (c.type === "audio_content") {
1793
- if (role === "user") {
1794
- const encodedAudio = Buffer.from(combineAudioFrames(c.frame).data).toString("base64");
1795
- contentList.push({
1796
- type: "input_audio",
1797
- audio: encodedAudio
1798
- });
1799
- }
1800
- }
1801
- }
1802
- return {
1803
- id: item.id,
1804
- type: "message",
1805
- role,
1806
- content: contentList
1807
- };
1808
- default:
1809
- throw new Error(`Unsupported item type: ${item.type}`);
1810
- }
1811
- }
1812
- function openAIItemToLivekitItem(item) {
1813
- if (!item.id) {
1814
- throw new Error("item.id is not set");
1815
- }
1816
- switch (item.type) {
1817
- case "function_call":
1818
- return llm.FunctionCall.create({
1819
- id: item.id,
1820
- callId: item.call_id,
1821
- name: item.name,
1822
- args: item.arguments
1823
- });
1824
- case "function_call_output":
1825
- return llm.FunctionCallOutput.create({
1826
- id: item.id,
1827
- callId: item.call_id,
1828
- output: item.output,
1829
- isError: false
1830
- });
1831
- case "message":
1832
- const content = [];
1833
- const contents = Array.isArray(item.content) ? item.content : [item.content];
1834
- for (const c of contents) {
1835
- if (c.type === "text" || c.type === "input_text" || c.type === "output_text") {
1836
- content.push(c.text);
1837
- } else if (c.type === "input_image" && c.image_url) {
1838
- content.push(
1839
- llm.createImageContent({ image: c.image_url })
1840
- );
1841
- }
1842
- }
1843
- return llm.ChatMessage.create({
1844
- id: item.id,
1845
- role: item.role,
1846
- content
1847
- });
1848
- }
1849
- }
1850
- function createMockAudioItem(durationSeconds = 2) {
1851
- const audioData = Buffer.alloc(durationSeconds * SAMPLE_RATE);
1852
- return llm.ChatMessage.create({
1853
- id: shortuuid(MOCK_AUDIO_ID_PREFIX),
1854
- role: "user",
1855
- content: [
1856
- {
1857
- type: "audio_content",
1858
- frame: [
1859
- new AudioFrame(
1860
- new Int16Array(audioData.buffer),
1861
- SAMPLE_RATE,
1862
- NUM_CHANNELS,
1863
- audioData.length / 2
1864
- )
1865
- ]
1866
- }
1867
- ]
1868
- });
1869
- }
1870
- function toOaiToolChoice(toolChoice) {
1871
- if (typeof toolChoice === "string") {
1872
- return toolChoice;
1873
- }
1874
- if ((toolChoice == null ? void 0 : toolChoice.type) === "function") {
1875
- return toolChoice.function.name;
1876
- }
1877
- return "auto";
1878
- }
1879
- export {
1880
- DiscardedGeneration,
1881
- RealtimeModel,
1882
- RealtimeSession,
1883
- isFatalError,
1884
- livekitItemToOpenAIItem,
1885
- processBaseURL
1886
- };
1
+ export * from "@livekit/agents/llm/openai_realtime/realtime_model";
1887
2
  //# sourceMappingURL=realtime_model.js.map