@livekit/agents-plugin-openai 0.0.0-next-20260624041820

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