@livekit/agents-plugin-openai 1.9.2 → 1.9.4

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