@livekit/agents-plugin-openai 1.7.1 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/realtime/gpt_live_model.cjs +883 -0
  4. package/dist/realtime/gpt_live_model.cjs.map +1 -0
  5. package/dist/realtime/gpt_live_model.d.cts +183 -0
  6. package/dist/realtime/gpt_live_model.d.ts +183 -0
  7. package/dist/realtime/gpt_live_model.d.ts.map +1 -0
  8. package/dist/realtime/gpt_live_model.js +859 -0
  9. package/dist/realtime/gpt_live_model.js.map +1 -0
  10. package/dist/realtime/gpt_live_model.test.cjs +1397 -0
  11. package/dist/realtime/gpt_live_model.test.cjs.map +1 -0
  12. package/dist/realtime/gpt_live_model.test.d.cts +2 -0
  13. package/dist/realtime/gpt_live_model.test.d.ts +2 -0
  14. package/dist/realtime/gpt_live_model.test.d.ts.map +1 -0
  15. package/dist/realtime/gpt_live_model.test.js +1398 -0
  16. package/dist/realtime/gpt_live_model.test.js.map +1 -0
  17. package/dist/realtime/gpt_live_types.cjs +17 -0
  18. package/dist/realtime/gpt_live_types.cjs.map +1 -0
  19. package/dist/realtime/gpt_live_types.d.cts +170 -0
  20. package/dist/realtime/gpt_live_types.d.ts +170 -0
  21. package/dist/realtime/gpt_live_types.d.ts.map +1 -0
  22. package/dist/realtime/gpt_live_types.js +1 -0
  23. package/dist/realtime/gpt_live_types.js.map +1 -0
  24. package/dist/realtime/index.cjs +22 -1
  25. package/dist/realtime/index.cjs.map +1 -1
  26. package/dist/realtime/index.d.cts +2 -0
  27. package/dist/realtime/index.d.ts +2 -0
  28. package/dist/realtime/index.d.ts.map +1 -1
  29. package/dist/realtime/index.js +5 -0
  30. package/dist/realtime/index.js.map +1 -1
  31. package/dist/realtime/realtime_model.cjs +4 -1
  32. package/dist/realtime/realtime_model.cjs.map +1 -1
  33. package/dist/realtime/realtime_model.d.ts.map +1 -1
  34. package/dist/realtime/realtime_model.js +4 -1
  35. package/dist/realtime/realtime_model.js.map +1 -1
  36. package/dist/realtime/realtime_model.test.cjs +29 -0
  37. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  38. package/dist/realtime/realtime_model.test.js +29 -0
  39. package/dist/realtime/realtime_model.test.js.map +1 -1
  40. package/dist/responses/llm.cjs +10 -0
  41. package/dist/responses/llm.cjs.map +1 -1
  42. package/dist/responses/llm.d.ts.map +1 -1
  43. package/dist/responses/llm.js +10 -0
  44. package/dist/responses/llm.js.map +1 -1
  45. package/dist/responses/llm.test.cjs +51 -0
  46. package/dist/responses/llm.test.cjs.map +1 -1
  47. package/dist/responses/llm.test.js +52 -1
  48. package/dist/responses/llm.test.js.map +1 -1
  49. package/dist/tool_utils.cjs +12 -8
  50. package/dist/tool_utils.cjs.map +1 -1
  51. package/dist/tool_utils.d.cts +1 -0
  52. package/dist/tool_utils.d.ts +1 -0
  53. package/dist/tool_utils.d.ts.map +1 -1
  54. package/dist/tool_utils.js +11 -8
  55. package/dist/tool_utils.js.map +1 -1
  56. package/dist/tool_utils.test.cjs +27 -0
  57. package/dist/tool_utils.test.cjs.map +1 -1
  58. package/dist/tool_utils.test.js +27 -0
  59. package/dist/tool_utils.test.js.map +1 -1
  60. package/dist/ws/llm.cjs +25 -7
  61. package/dist/ws/llm.cjs.map +1 -1
  62. package/dist/ws/llm.d.cts +2 -2
  63. package/dist/ws/llm.d.ts +2 -2
  64. package/dist/ws/llm.d.ts.map +1 -1
  65. package/dist/ws/llm.js +25 -7
  66. package/dist/ws/llm.js.map +1 -1
  67. package/dist/ws/llm.test.cjs +117 -0
  68. package/dist/ws/llm.test.cjs.map +1 -1
  69. package/dist/ws/llm.test.js +126 -3
  70. package/dist/ws/llm.test.js.map +1 -1
  71. package/dist/ws/types.cjs +12 -0
  72. package/dist/ws/types.cjs.map +1 -1
  73. package/dist/ws/types.d.cts +18 -0
  74. package/dist/ws/types.d.ts +18 -0
  75. package/dist/ws/types.d.ts.map +1 -1
  76. package/dist/ws/types.js +11 -0
  77. package/dist/ws/types.js.map +1 -1
  78. package/package.json +5 -5
  79. package/src/realtime/gpt_live_model.test.ts +1458 -0
  80. package/src/realtime/gpt_live_model.ts +1032 -0
  81. package/src/realtime/gpt_live_types.ts +140 -0
  82. package/src/realtime/index.ts +2 -0
  83. package/src/realtime/realtime_model.test.ts +32 -0
  84. package/src/realtime/realtime_model.ts +4 -1
  85. package/src/responses/llm.test.ts +55 -1
  86. package/src/responses/llm.ts +10 -0
  87. package/src/tool_utils.test.ts +30 -0
  88. package/src/tool_utils.ts +21 -18
  89. package/src/ws/llm.test.ts +141 -5
  90. package/src/ws/llm.ts +29 -8
  91. package/src/ws/types.ts +17 -0
@@ -0,0 +1,859 @@
1
+ import {
2
+ APIConnectionError,
3
+ APIError,
4
+ APITimeoutError,
5
+ AudioByteStream,
6
+ DEFAULT_API_CONNECT_OPTIONS,
7
+ Future,
8
+ intervalForRetry,
9
+ llm,
10
+ log,
11
+ shortuuid
12
+ } from "@livekit/agents";
13
+ import { AudioFrame, AudioResampler } from "@livekit/rtc-node";
14
+ import { ReadableStream } from "node:stream/web";
15
+ import { setTimeout as delay } from "node:timers/promises";
16
+ import WebSocket from "ws";
17
+ import { toResponsesTool } from "../tool_utils.js";
18
+ const SAMPLE_RATE = 24e3;
19
+ const MIN_SILENCE_DURATION = 800;
20
+ const DEFAULT_MODEL = "gpt-live-1";
21
+ const DEFAULT_BACKEND_MODEL = "gpt-5.6-luna";
22
+ const SPEAK_NOW = "Do not wait for the caller to speak first. After that, pause and listen.";
23
+ const ASK_INSTRUCTED = `Immediately follow the instruction below. ${SPEAK_NOW}`;
24
+ const ASK_TYPED = `Reply to the caller now, don't repeat what they said. ${SPEAK_NOW}`;
25
+ const ASK_BARE = `Reply to the caller now. ${SPEAK_NOW}`;
26
+ const SESSION_CLOSE_TIMEOUT = 5e3;
27
+ const FATAL_ERROR_CODES = /* @__PURE__ */ new Set([
28
+ "insufficient_quota",
29
+ "invalid_api_key",
30
+ "account_deactivated",
31
+ "billing_hard_limit_reached"
32
+ ]);
33
+ class GPTLiveModel extends llm.DuplexModel {
34
+ /** @internal */
35
+ _opts;
36
+ /** Configure a voice model. Throws when no OpenAI API key is available. */
37
+ constructor(options = {}) {
38
+ super({
39
+ userTranscription: true,
40
+ autoToolReplyGeneration: true,
41
+ midSessionChatCtxUpdate: false,
42
+ midSessionInstructionsUpdate: false,
43
+ midSessionToolsUpdate: (options.delegation ?? "responses") === "responses"
44
+ });
45
+ const apiKey = options.apiKey ?? process.env.OPENAI_API_KEY;
46
+ if (!apiKey) {
47
+ throw new Error("OpenAI API key is required: pass apiKey or set OPENAI_API_KEY");
48
+ }
49
+ this._opts = {
50
+ model: options.model ?? DEFAULT_MODEL,
51
+ voice: options.voice ?? "marin",
52
+ delegation: options.delegation ?? "responses",
53
+ responsesOptions: { ...options.responsesOptions },
54
+ apiKey,
55
+ baseURL: options.baseURL ?? process.env.OPENAI_BASE_URL ?? "https://api.openai.com/v1",
56
+ maxSessionDuration: options.maxSessionDuration ?? null,
57
+ connOptions: { ...options.connOptions ?? DEFAULT_API_CONNECT_OPTIONS }
58
+ };
59
+ }
60
+ /** Voice model identifier used for sessions and metrics. */
61
+ get model() {
62
+ return this._opts.model;
63
+ }
64
+ /** Host of the configured API endpoint. */
65
+ get provider() {
66
+ return new URL(this._opts.baseURL).host;
67
+ }
68
+ /** Keep output active through short pauses in speech. */
69
+ audioGate() {
70
+ return new llm.FixedGate(6e-4, { minSilenceDuration: MIN_SILENCE_DURATION });
71
+ }
72
+ /** Create a connection that starts after the framework configures the session. */
73
+ session() {
74
+ return new GPTLiveSession(this);
75
+ }
76
+ /** The model owns no shared resources. Close each session to release its connection. */
77
+ async close() {
78
+ }
79
+ }
80
+ class GPTLiveSession extends llm.DuplexSession {
81
+ opts;
82
+ logger = log();
83
+ debug = Number(process.env.LK_OPENAI_DEBUG ?? 0) !== 0;
84
+ history = llm.ChatContext.empty();
85
+ speech = /* @__PURE__ */ new Map();
86
+ delegatedResponses = /* @__PURE__ */ new Map();
87
+ callToDelegation = /* @__PURE__ */ new Map();
88
+ delegationIds = /* @__PURE__ */ new Set();
89
+ bstream = new AudioByteStream(SAMPLE_RATE, 1, SAMPLE_RATE / 10);
90
+ inputResampler;
91
+ inputRate;
92
+ _tools = llm.ToolContext.empty();
93
+ instructions;
94
+ askedItemId;
95
+ _sessionId;
96
+ usageSeconds = 0;
97
+ sessionStartSent = false;
98
+ sessionStarted = false;
99
+ closing = false;
100
+ audioClosed = false;
101
+ queued = [];
102
+ ws;
103
+ connectionDone;
104
+ connectionDraining = false;
105
+ requestConnectionClose;
106
+ shutdown = new AbortController();
107
+ mainTask;
108
+ audioController;
109
+ output = new ReadableStream({
110
+ start: (controller) => {
111
+ this.audioController = controller;
112
+ },
113
+ cancel: () => {
114
+ this.audioClosed = true;
115
+ }
116
+ });
117
+ /** Create a session using a copy of the model configuration. */
118
+ constructor(model) {
119
+ super(model);
120
+ this.opts = { ...model._opts, responsesOptions: { ...model._opts.responsesOptions } };
121
+ this.mainTask = Promise.resolve().then(() => this.main()).catch((error) => {
122
+ this.logger.error({ "lk.pii.error": error }, "GPT-Live session failed");
123
+ });
124
+ }
125
+ /** Provider session identifier. Changes when a replacement connection starts. */
126
+ get sessionId() {
127
+ return this._sessionId;
128
+ }
129
+ /** Mono 24 kHz PCM output, retained across reconnects and closed on shutdown. */
130
+ get audioStream() {
131
+ return this.output;
132
+ }
133
+ /** Copy of the tools available to the backend Responses model. */
134
+ get tools() {
135
+ return this._tools.copy();
136
+ }
137
+ /** Queue a wire event. Commands wait for session.started before being sent. */
138
+ sendEvent(event) {
139
+ this.queueEvent(event, true);
140
+ }
141
+ queueEvent(event, replayOnReconnect, context) {
142
+ if (this.closing) return;
143
+ this.queued.push({ event, replayOnReconnect, context });
144
+ this.flushQueued();
145
+ }
146
+ flushQueued() {
147
+ var _a;
148
+ if (this.connectionDraining || !this.sessionStarted || ((_a = this.ws) == null ? void 0 : _a.readyState) !== WebSocket.OPEN)
149
+ return;
150
+ while (this.queued.length) {
151
+ const { event, context } = this.queued.shift();
152
+ if (context !== void 0)
153
+ this.history.insert(new llm.ChatMessage({ role: "developer", content: [context] }));
154
+ this.wsSend(this.ws, event);
155
+ }
156
+ }
157
+ wsSend(ws, event) {
158
+ this.emit("openai_client_event_queued", event);
159
+ if (this.debug && event.type !== "session.input_audio.append")
160
+ this.logger.debug({ "lk.pii.event": event }, "GPT-Live client event");
161
+ const done = this.connectionDone;
162
+ try {
163
+ ws.send(JSON.stringify(event), (error) => {
164
+ if (error) done == null ? void 0 : done.resolve(new APIConnectionError({ message: "GPT-Live send failed" }));
165
+ });
166
+ } catch {
167
+ done == null ? void 0 : done.resolve(new APIConnectionError({ message: "GPT-Live send failed" }));
168
+ }
169
+ }
170
+ buildDelegation() {
171
+ if (this.opts.delegation === "client") return { type: "client" };
172
+ const opts = this.opts.responsesOptions;
173
+ const tools = this.buildTools();
174
+ return {
175
+ type: "responses",
176
+ responses: {
177
+ model: opts.model ?? DEFAULT_BACKEND_MODEL,
178
+ instructions: opts.instructions,
179
+ tools: tools.length ? tools : void 0,
180
+ tool_choice: opts.toolChoice !== void 0 ? toToolChoice(opts.toolChoice) : void 0,
181
+ parallel_tool_calls: opts.parallelToolCalls,
182
+ reasoning: opts.reasoning,
183
+ text: opts.text,
184
+ service_tier: opts.serviceTier,
185
+ max_output_tokens: opts.maxOutputTokens
186
+ }
187
+ };
188
+ }
189
+ buildTools() {
190
+ return this._tools.flatten().flatMap((tool) => {
191
+ const converted = toResponsesTool(tool, false);
192
+ if (converted) return [converted];
193
+ this.logger.debug({ "lk.pii.tool": tool.id }, "GPT-Live delegation ignores unsupported tool");
194
+ return [];
195
+ });
196
+ }
197
+ sessionStartEvent() {
198
+ const items = this.history.items.flatMap((item) => {
199
+ const rendered = renderItem(item);
200
+ if (!rendered) return [];
201
+ const [role, text] = rendered;
202
+ return [
203
+ {
204
+ type: "message",
205
+ role,
206
+ content: [{ type: role === "assistant" ? "output_text" : "input_text", text }]
207
+ }
208
+ ];
209
+ });
210
+ if (items.length > 128) {
211
+ this.logger.warn(
212
+ { dropped: items.length - 128, kept: 128 },
213
+ "GPT-Live startup history exceeds the message limit; dropping the oldest"
214
+ );
215
+ }
216
+ return {
217
+ type: "session.start",
218
+ event_id: shortuuid("session_start_"),
219
+ session: {
220
+ model: this.opts.model,
221
+ instructions: this.instructions,
222
+ input: items.length ? items.slice(-128) : void 0,
223
+ audio: {
224
+ format: { type: "audio/pcm", rate: SAMPLE_RATE },
225
+ output: { voice: this.opts.voice }
226
+ },
227
+ delegation: this.buildDelegation()
228
+ }
229
+ };
230
+ }
231
+ sendDelegationUpdate(responses) {
232
+ if (this.opts.delegation !== "responses" || !this.sessionStartSent) return;
233
+ this.queueEvent(
234
+ {
235
+ type: "session.update",
236
+ event_id: shortuuid("delegation_update_"),
237
+ session: { delegation: { type: "responses", responses } }
238
+ },
239
+ false
240
+ );
241
+ }
242
+ async main() {
243
+ let retries = 0;
244
+ let reconnecting = false;
245
+ try {
246
+ while (!this.closing) {
247
+ try {
248
+ await this.runConnection(
249
+ () => {
250
+ if (reconnecting) {
251
+ this.queued = this.queued.filter((command) => command.replayOnReconnect);
252
+ this.resetInputAudio();
253
+ this.endSpeech("user");
254
+ this.speech.clear();
255
+ this.delegatedResponses.clear();
256
+ this.callToDelegation.clear();
257
+ this.delegationIds.clear();
258
+ this.usageSeconds = 0;
259
+ this._sessionId = void 0;
260
+ }
261
+ },
262
+ () => {
263
+ retries = 0;
264
+ if (reconnecting) this.emit("session_reconnected", {});
265
+ }
266
+ );
267
+ } catch (error) {
268
+ if (this.closing) break;
269
+ const err = error instanceof APIError ? error : new APIConnectionError({
270
+ message: "GPT-Live session failed",
271
+ options: { retryable: false }
272
+ });
273
+ const recoverable = err.retryable && retries < this.opts.connOptions.maxRetry;
274
+ this.emitError(err, recoverable);
275
+ if (!recoverable) throw err;
276
+ await delay(intervalForRetry(this.opts.connOptions, retries++), void 0, {
277
+ signal: this.shutdown.signal
278
+ }).catch((error2) => {
279
+ if (!this.closing) throw error2;
280
+ });
281
+ } finally {
282
+ this.sessionStartSent = false;
283
+ this.sessionStarted = false;
284
+ }
285
+ reconnecting = true;
286
+ }
287
+ } finally {
288
+ this.endSpeech("user");
289
+ this.delegationIds.clear();
290
+ this.resetInputAudio();
291
+ if (!this.audioClosed) {
292
+ this.audioClosed = true;
293
+ this.audioController.close();
294
+ }
295
+ }
296
+ }
297
+ async runConnection(onOpen, onStarted) {
298
+ const url = new URL(this.opts.baseURL);
299
+ url.protocol = url.protocol === "https:" ? "wss:" : url.protocol === "http:" ? "ws:" : url.protocol;
300
+ url.pathname = url.pathname.replace(/\/$/, "");
301
+ if (!url.pathname.endsWith("/live/sessions")) url.pathname += "/live/sessions";
302
+ url.search = "";
303
+ url.hash = "";
304
+ const done = new Future();
305
+ this.connectionDone = done;
306
+ const startTime = performance.now();
307
+ const ws = new WebSocket(url, {
308
+ headers: {
309
+ "User-Agent": "LiveKit Agents",
310
+ Authorization: `Bearer ${this.opts.apiKey}`
311
+ },
312
+ handshakeTimeout: this.opts.connOptions.timeoutMs
313
+ });
314
+ this.ws = ws;
315
+ let recycleTimer;
316
+ let startupTimer;
317
+ let closeTimer;
318
+ const requestClose = () => {
319
+ if (this.connectionDraining || done.done) return;
320
+ this.connectionDraining = true;
321
+ if (this.sessionStarted && ws.readyState === WebSocket.OPEN) {
322
+ closeTimer = setTimeout(() => done.resolve(void 0), SESSION_CLOSE_TIMEOUT);
323
+ this.wsSend(ws, { type: "session.close" });
324
+ } else {
325
+ done.resolve(void 0);
326
+ }
327
+ };
328
+ this.requestConnectionClose = requestClose;
329
+ const closed = new Future();
330
+ ws.once("close", () => closed.resolve());
331
+ ws.on("open", () => {
332
+ this._reportConnectionAcquired(performance.now() - startTime);
333
+ onOpen();
334
+ void Promise.race([this._configured.wait(), done.await]).then(() => {
335
+ if (this.closing || done.done) return;
336
+ this.sessionStartSent = true;
337
+ startupTimer = setTimeout(
338
+ () => done.resolve(new APITimeoutError({ message: "GPT-Live session start timed out" })),
339
+ this.opts.connOptions.timeoutMs
340
+ );
341
+ this.wsSend(ws, this.sessionStartEvent());
342
+ }).catch((error) => done.resolve(error));
343
+ });
344
+ ws.on(
345
+ "error",
346
+ () => done.resolve(new APIConnectionError({ message: "GPT-Live connection failed" }))
347
+ );
348
+ ws.on(
349
+ "close",
350
+ () => done.resolve(
351
+ this.closing || this.connectionDraining ? void 0 : new APIConnectionError({ message: "OpenAI Live API connection closed unexpectedly" })
352
+ )
353
+ );
354
+ ws.on("message", (data, isBinary) => {
355
+ var _a;
356
+ if (isBinary || done.done) return;
357
+ try {
358
+ const event = JSON.parse(data.toString());
359
+ if (event.type === "session.delegation.created" && ((_a = event.delegation) == null ? void 0 : _a.id))
360
+ this.delegationIds.add(event.delegation.id);
361
+ this.emit("openai_server_event_received", event);
362
+ if (this.debug && event.type !== "session.output_audio.delta")
363
+ this.logger.debug({ "lk.pii.event": event }, "GPT-Live server event");
364
+ if (this.closing && event.type !== "session.usage.updated" && event.type !== "session.closed")
365
+ return;
366
+ const started = event.type === "session.started" && !this.sessionStarted;
367
+ this.handleEvent(event);
368
+ if (started) {
369
+ clearTimeout(startupTimer);
370
+ onStarted();
371
+ if (this.opts.maxSessionDuration !== null) {
372
+ recycleTimer = setTimeout(requestClose, this.opts.maxSessionDuration);
373
+ }
374
+ }
375
+ } catch (error) {
376
+ if (error instanceof APIError && !error.retryable) done.resolve(error);
377
+ else this.logger.error({ "lk.pii.error": error }, "Failed to handle GPT-Live event");
378
+ }
379
+ });
380
+ try {
381
+ const error = await done.await;
382
+ if (error) throw error;
383
+ } finally {
384
+ this.sessionStartSent = false;
385
+ this.sessionStarted = false;
386
+ clearTimeout(recycleTimer);
387
+ clearTimeout(startupTimer);
388
+ clearTimeout(closeTimer);
389
+ this.connectionDraining = false;
390
+ this.requestConnectionClose = void 0;
391
+ this.ws = void 0;
392
+ this.connectionDone = void 0;
393
+ ws.terminate();
394
+ await closed.await;
395
+ }
396
+ }
397
+ handleEvent(event) {
398
+ var _a, _b, _c, _d, _e;
399
+ switch (event.type) {
400
+ case "session.started":
401
+ this._sessionId = ((_a = event.session) == null ? void 0 : _a.id) ?? this._sessionId;
402
+ this.sessionStarted = true;
403
+ this.flushQueued();
404
+ break;
405
+ case "session.output_audio.delta": {
406
+ const data = Buffer.from(event.delta ?? "", "base64");
407
+ if (!data.length || this.audioClosed) break;
408
+ const samples = new Int16Array(data.length / 2);
409
+ for (let i = 0; i < samples.length; i++) samples[i] = data.readInt16LE(i * 2);
410
+ this.audioController.enqueue({
411
+ frame: new AudioFrame(samples, SAMPLE_RATE, 1, samples.length)
412
+ });
413
+ break;
414
+ }
415
+ case "session.input_transcript.delta":
416
+ case "session.output_transcript.delta":
417
+ this.handleTranscript(
418
+ event.type === "session.input_transcript.delta" ? "user" : "assistant",
419
+ event
420
+ );
421
+ break;
422
+ case "session.delegation.created": {
423
+ const delegation = event.delegation;
424
+ if (!(delegation == null ? void 0 : delegation.id))
425
+ this.logger.warn("GPT-Live delegation has no id; nothing can answer it");
426
+ else if (delegation.target === "client")
427
+ this.emit("delegation_created", {
428
+ id: delegation.id,
429
+ pendingTranscript: ((_b = this.speech.get("user")) == null ? void 0 : _b.text) ?? ""
430
+ });
431
+ break;
432
+ }
433
+ case "response.event":
434
+ this.handleResponseEvent(event.delegation_id ?? null, event.event ?? { type: "" });
435
+ break;
436
+ case "session.usage.updated":
437
+ case "session.closed":
438
+ if (event.type === "session.closed")
439
+ this.logger.debug(
440
+ { reason: event.reason ?? null, sessionId: this._sessionId },
441
+ "GPT-Live session closed"
442
+ );
443
+ if (((_c = event.context_window) == null ? void 0 : _c.usage_ratio) != null)
444
+ this.logger.debug(
445
+ { usageRatio: event.context_window.usage_ratio },
446
+ "GPT-Live context window utilization"
447
+ );
448
+ this.handleUsage((_d = event.usage) == null ? void 0 : _d.seconds);
449
+ if (event.type === "session.closed") (_e = this.connectionDone) == null ? void 0 : _e.resolve(void 0);
450
+ break;
451
+ case "error": {
452
+ const error = event.error ?? {};
453
+ const recoverable = !FATAL_ERROR_CODES.has(error.code || error.type || "");
454
+ this.logger.error({ "lk.pii.error": error }, "GPT-Live returned an error");
455
+ const apiError = new APIError("GPT-Live returned an error", {
456
+ retryable: recoverable
457
+ });
458
+ if (!recoverable) throw apiError;
459
+ this.emitError(apiError, true);
460
+ break;
461
+ }
462
+ default:
463
+ this.logger.debug({ "lk.pii.type": event.type }, "GPT-Live acknowledged a command");
464
+ }
465
+ }
466
+ handleTranscript(role, event) {
467
+ if (!event.delta) return;
468
+ let speech = this.speech.get(role);
469
+ if ((speech == null ? void 0 : speech.endMs) !== void 0 && event.start_ms != null && event.start_ms - speech.endMs > MIN_SILENCE_DURATION) {
470
+ this.endSpeech(role);
471
+ speech = void 0;
472
+ }
473
+ if (!speech) {
474
+ speech = { messageId: shortuuid("speech_"), text: "", startedAt: Date.now(), quietMs: 0 };
475
+ this.speech.set(role, speech);
476
+ this.history.insert(
477
+ new llm.ChatMessage({
478
+ id: speech.messageId,
479
+ role,
480
+ content: [""],
481
+ transcriptConfidence: role === "user" ? 1 : void 0
482
+ })
483
+ );
484
+ if (role === "user") this.emit("input_speech_started", {});
485
+ }
486
+ speech.text += event.delta;
487
+ speech.quietMs = 0;
488
+ if (event.end_ms != null) speech.endMs = Math.max(speech.endMs ?? 0, event.end_ms);
489
+ const message = this.history.getById(speech.messageId);
490
+ if ((message == null ? void 0 : message.type) === "message") message.content[0] = speech.text;
491
+ if (role === "user") {
492
+ this.emit("input_audio_transcription_completed", {
493
+ itemId: speech.messageId,
494
+ transcript: speech.text,
495
+ isFinal: false,
496
+ turnStartedAt: speech.startedAt
497
+ });
498
+ } else {
499
+ this.emit("transcript_delta", {
500
+ text: event.delta,
501
+ startMs: event.start_ms ?? void 0,
502
+ endMs: event.end_ms ?? void 0
503
+ });
504
+ }
505
+ }
506
+ endSpeech(role) {
507
+ const speech = this.speech.get(role);
508
+ this.speech.delete(role);
509
+ if (!speech || role !== "user") return;
510
+ this.emit("input_audio_transcription_completed", {
511
+ itemId: speech.messageId,
512
+ transcript: speech.text,
513
+ isFinal: true,
514
+ turnStartedAt: speech.startedAt
515
+ });
516
+ this.emit("input_speech_stopped", {
517
+ userTranscriptionEnabled: false
518
+ });
519
+ }
520
+ handleResponseEvent(delegationId, event) {
521
+ var _a, _b;
522
+ switch (event.type) {
523
+ case "response.created":
524
+ this.delegatedResponses.set(delegationId, {
525
+ callIds: /* @__PURE__ */ new Set(),
526
+ returned: /* @__PURE__ */ new Set(),
527
+ completed: false
528
+ });
529
+ break;
530
+ case "response.output_item.done": {
531
+ const item = event.item;
532
+ if (!item || item.type !== "function_call") return;
533
+ if (!item.call_id || !item.name || item.arguments == null) {
534
+ this.logger.warn(
535
+ { "lk.pii.call_id": item.call_id, "lk.pii.name": item.name },
536
+ "GPT-Live dropping function call with missing fields"
537
+ );
538
+ return;
539
+ }
540
+ let pending = this.delegatedResponses.get(delegationId);
541
+ if (!pending) {
542
+ this.logger.warn(
543
+ { "lk.pii.call_id": item.call_id, "lk.pii.delegation_id": delegationId },
544
+ "GPT-Live function call outside a known response"
545
+ );
546
+ pending = { callIds: /* @__PURE__ */ new Set(), returned: /* @__PURE__ */ new Set(), completed: true };
547
+ this.delegatedResponses.set(delegationId, pending);
548
+ }
549
+ pending.callIds.add(item.call_id);
550
+ this.callToDelegation.set(item.call_id, delegationId);
551
+ const call = new llm.FunctionCall({
552
+ id: item.id ?? shortuuid("fc_"),
553
+ callId: item.call_id,
554
+ name: item.name,
555
+ args: item.arguments
556
+ });
557
+ this.history.insert(call);
558
+ this.emit("function_call", call);
559
+ break;
560
+ }
561
+ case "response.completed": {
562
+ this.handleResponseUsage(event.response);
563
+ const pending = this.delegatedResponses.get(delegationId);
564
+ if (pending) {
565
+ pending.completed = true;
566
+ this.maybeContinueResponse(delegationId);
567
+ }
568
+ break;
569
+ }
570
+ case "response.failed":
571
+ case "response.incomplete": {
572
+ this.handleResponseUsage(event.response);
573
+ this.logger.warn(
574
+ {
575
+ type: event.type,
576
+ "lk.pii.delegation_id": delegationId,
577
+ "lk.pii.error": (_a = event.response) == null ? void 0 : _a.error,
578
+ "lk.pii.incomplete_details": (_b = event.response) == null ? void 0 : _b.incomplete_details
579
+ },
580
+ "GPT-Live backend response did not complete"
581
+ );
582
+ const pending = this.delegatedResponses.get(delegationId);
583
+ for (const callId of (pending == null ? void 0 : pending.callIds) ?? []) this.callToDelegation.delete(callId);
584
+ this.delegatedResponses.delete(delegationId);
585
+ break;
586
+ }
587
+ }
588
+ }
589
+ handleResponseUsage(response) {
590
+ var _a, _b, _c;
591
+ const usage = response == null ? void 0 : response.usage;
592
+ if (usage) {
593
+ const metric = {
594
+ type: "llm_metrics",
595
+ label: this.duplexModel.label(),
596
+ requestId: (response == null ? void 0 : response.id) ?? "",
597
+ timestamp: Date.now(),
598
+ durationMs: 0,
599
+ ttftMs: -1,
600
+ cancelled: false,
601
+ tokensPerSecond: 0,
602
+ promptTokens: usage.input_tokens ?? 0,
603
+ promptCachedTokens: ((_a = usage.input_tokens_details) == null ? void 0 : _a.cached_tokens) ?? 0,
604
+ cacheCreationTokens: ((_b = usage.input_tokens_details) == null ? void 0 : _b.cache_write_tokens) ?? 0,
605
+ completionTokens: usage.output_tokens ?? 0,
606
+ reasoningTokens: ((_c = usage.output_tokens_details) == null ? void 0 : _c.reasoning_tokens) ?? 0,
607
+ totalTokens: usage.total_tokens ?? 0,
608
+ metadata: {
609
+ modelName: (response == null ? void 0 : response.model) || this.opts.responsesOptions.model || DEFAULT_BACKEND_MODEL,
610
+ modelProvider: this.duplexModel.provider
611
+ }
612
+ };
613
+ this.emit("metrics_collected", metric);
614
+ }
615
+ }
616
+ maybeContinueResponse(delegationId) {
617
+ const pending = this.delegatedResponses.get(delegationId);
618
+ if (!(pending == null ? void 0 : pending.completed) || [...pending.callIds].some((id) => !pending.returned.has(id))) return;
619
+ this.delegatedResponses.delete(delegationId);
620
+ if (!pending.callIds.size) return;
621
+ for (const callId of pending.callIds) this.callToDelegation.delete(callId);
622
+ this.queueEvent(
623
+ {
624
+ type: "response.create",
625
+ event_id: shortuuid("response_create_")
626
+ },
627
+ false
628
+ );
629
+ }
630
+ handleUsage(seconds) {
631
+ if (seconds === void 0 || !Number.isFinite(seconds) || seconds < this.usageSeconds) return;
632
+ const previous = this.usageSeconds;
633
+ this.usageSeconds = seconds;
634
+ this.emit("metrics_collected", {
635
+ type: "realtime_model_metrics",
636
+ label: this.duplexModel.label(),
637
+ requestId: this._sessionId ?? "",
638
+ timestamp: Date.now(),
639
+ durationMs: 0,
640
+ ttftMs: -1,
641
+ cancelled: false,
642
+ sessionDurationMs: Math.max(0, seconds - previous) * 1e3,
643
+ inputTokens: 0,
644
+ outputTokens: 0,
645
+ totalTokens: 0,
646
+ tokensPerSecond: 0,
647
+ inputTokenDetails: { audioTokens: 0, textTokens: 0, imageTokens: 0, cachedTokens: 0 },
648
+ outputTokenDetails: { audioTokens: 0, textTokens: 0, imageTokens: 0 },
649
+ metadata: { modelName: this.duplexModel.model, modelProvider: this.duplexModel.provider }
650
+ });
651
+ }
652
+ emitError(error, recoverable) {
653
+ this.emit("error", {
654
+ type: "realtime_model_error",
655
+ timestamp: Date.now(),
656
+ label: this.duplexModel.label(),
657
+ error,
658
+ recoverable
659
+ });
660
+ }
661
+ /** Buffer microphone audio, mixing to mono and resampling to 24 kHz as needed. */
662
+ pushAudio(frame) {
663
+ var _a;
664
+ if (this.closing) return;
665
+ const speech = this.speech.get("user");
666
+ if (speech) {
667
+ speech.quietMs += Math.round(frame.samplesPerChannel / frame.sampleRate * 1e3);
668
+ if (speech.quietMs >= MIN_SILENCE_DURATION) this.endSpeech("user");
669
+ }
670
+ if (frame.channels !== 1) {
671
+ const mono = new Int16Array(frame.samplesPerChannel);
672
+ for (let i = 0; i < mono.length; i++) {
673
+ let sum = 0;
674
+ for (let channel = 0; channel < frame.channels; channel++)
675
+ sum += frame.data[i * frame.channels + channel];
676
+ mono[i] = Math.round(sum / frame.channels);
677
+ }
678
+ frame = new AudioFrame(mono, frame.sampleRate, 1, mono.length);
679
+ }
680
+ if (this.inputRate !== frame.sampleRate) {
681
+ (_a = this.inputResampler) == null ? void 0 : _a.close();
682
+ this.inputResampler = frame.sampleRate === SAMPLE_RATE ? void 0 : new AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);
683
+ this.inputRate = frame.sampleRate;
684
+ }
685
+ for (const resampled of this.inputResampler ? this.inputResampler.push(frame) : [frame]) {
686
+ for (const chunk of this.bstream.write(resampled.data)) {
687
+ this.sendEvent({
688
+ type: "session.input_audio.append",
689
+ audio: Buffer.from(
690
+ chunk.data.buffer,
691
+ chunk.data.byteOffset,
692
+ chunk.data.byteLength
693
+ ).toString("base64")
694
+ });
695
+ }
696
+ }
697
+ }
698
+ resetInputAudio() {
699
+ var _a;
700
+ this.bstream.flush();
701
+ (_a = this.inputResampler) == null ? void 0 : _a.close();
702
+ this.inputResampler = void 0;
703
+ this.inputRate = void 0;
704
+ }
705
+ /** Add a standing rule retained in reconnect history. The service caps each append at 500 tokens. */
706
+ appendInstructions(text, options = {}) {
707
+ this.append("session.instructions.append", text, options.delegationId ?? null, {
708
+ persist: true
709
+ });
710
+ }
711
+ /** Add silent context retained in reconnect history. The service caps each append at 500 tokens. */
712
+ appendThinking(text, options = {}) {
713
+ this.append("session.thinking.append", text, options.delegationId ?? null, { persist: true });
714
+ }
715
+ /** Give the model text to paraphrase aloud, or answer a client delegation. Capped at 500 tokens by the service. */
716
+ appendCommentary(text, options = {}) {
717
+ this.append("session.commentary.append", text, options.delegationId ?? null);
718
+ }
719
+ append(type, content, delegationId, options = {}) {
720
+ if (delegationId !== null && !this.delegationIds.has(delegationId)) {
721
+ this.logger.debug("GPT-Live ignoring append for an inactive delegation");
722
+ return;
723
+ }
724
+ this.queueEvent(
725
+ {
726
+ type,
727
+ event_id: shortuuid("append_"),
728
+ delegation_id: delegationId,
729
+ content
730
+ },
731
+ delegationId === null && (options.replayOnReconnect ?? true),
732
+ options.persist ? content : void 0
733
+ );
734
+ }
735
+ /** Replace microphone input with silence while the model continues speaking. */
736
+ muteInput() {
737
+ this.sendEvent({
738
+ type: "session.input_audio.mute",
739
+ event_id: shortuuid("mute_")
740
+ });
741
+ }
742
+ /** Restore microphone input. */
743
+ unmuteInput() {
744
+ this.sendEvent({
745
+ type: "session.input_audio.unmute",
746
+ event_id: shortuuid("unmute_")
747
+ });
748
+ }
749
+ /** Drain final provider usage, then close the transport and output stream. */
750
+ async closeConnection() {
751
+ var _a;
752
+ if (!this.closing) {
753
+ this.closing = true;
754
+ this.shutdown.abort();
755
+ (_a = this.requestConnectionClose) == null ? void 0 : _a.call(this);
756
+ }
757
+ await this.mainTask;
758
+ }
759
+ /** Set the initial voice instructions. Changes after session.start are rejected. */
760
+ async _updateInstructions(instructions) {
761
+ if (this.sessionStartSent && instructions !== this.instructions) {
762
+ throw new llm.RealtimeError(
763
+ "gpt-live voice instructions are immutable after session start; use appendInstructions for a standing rule"
764
+ );
765
+ }
766
+ this.instructions = instructions;
767
+ }
768
+ /** Update backend tools. Client delegation requires an empty tool context. */
769
+ async _updateTools(tools) {
770
+ if (this.opts.delegation === "client" && tools.flatten().length) {
771
+ throw new llm.RealtimeError(
772
+ `gpt-live client delegation has no tool channel, so the model can never call ${tools.flatten().map((tool) => tool.id).sort().join(
773
+ ", "
774
+ )}. Leave the agent's tools empty and answer delegation_created with appendCommentary, or pass delegation="responses" to run tools on the backend model.`
775
+ );
776
+ }
777
+ this._tools = tools.copy();
778
+ this.sendDelegationUpdate({ tools: this.buildTools() });
779
+ }
780
+ /** Retain framework chat items for reconnects and send their context or tool results. */
781
+ async _appendItems(items) {
782
+ var _a;
783
+ this.history.insert(items);
784
+ if (!this.sessionStartSent) return;
785
+ const outputs = [];
786
+ const lines = [];
787
+ for (const item of items) {
788
+ if (item.type === "message" && (item.role === "system" || item.role === "developer")) {
789
+ if (item.textContent)
790
+ this.append("session.instructions.append", item.textContent, null, {
791
+ replayOnReconnect: false
792
+ });
793
+ } else if (item.type === "function_call_output" && this.callToDelegation.has(item.callId)) {
794
+ outputs.push({ output: item, delegationId: this.callToDelegation.get(item.callId) });
795
+ } else {
796
+ const rendered = renderItem(item);
797
+ if (rendered) lines.push(`${rendered[0]}: ${rendered[1]}`);
798
+ }
799
+ }
800
+ if (lines.length)
801
+ this.append("session.thinking.append", lines.join("\n"), null, { replayOnReconnect: false });
802
+ for (const { output, delegationId } of outputs) {
803
+ this.queueEvent(
804
+ {
805
+ type: "response.item.create",
806
+ event_id: shortuuid("tool_output_"),
807
+ item: { type: "function_call_output", call_id: output.callId, output: output.output }
808
+ },
809
+ false
810
+ );
811
+ (_a = this.delegatedResponses.get(delegationId)) == null ? void 0 : _a.returned.add(output.callId);
812
+ this.maybeContinueResponse(delegationId);
813
+ }
814
+ }
815
+ /** Prompt an immediate spoken reply to instructions or the newest typed user message. */
816
+ _generateReply(instructions) {
817
+ if (instructions !== void 0) {
818
+ this.appendCommentary(`${ASK_INSTRUCTED}
819
+
820
+ ${instructions}`);
821
+ return;
822
+ }
823
+ const newest = this.history.items.at(-1);
824
+ const typed = (newest == null ? void 0 : newest.type) === "message" && newest.role === "user" && newest.transcriptConfidence === void 0 && newest.id !== this.askedItemId ? newest.textContent : void 0;
825
+ this.askedItemId = newest == null ? void 0 : newest.id;
826
+ this.appendCommentary(typed ? `${ASK_TYPED}
827
+
828
+ ${typed}` : ASK_BARE);
829
+ }
830
+ /** Update backend tool selection for this session and future reconnects. */
831
+ _updateOptions(options) {
832
+ if (options.toolChoice !== void 0) {
833
+ this.opts.responsesOptions.toolChoice = options.toolChoice;
834
+ this.sendDelegationUpdate({ tool_choice: toToolChoice(options.toolChoice) });
835
+ }
836
+ }
837
+ }
838
+ function toToolChoice(choice) {
839
+ return typeof choice === "string" ? choice : (choice == null ? void 0 : choice.type) === "function" ? { type: "function", name: choice.function.name } : "auto";
840
+ }
841
+ function renderItem(item) {
842
+ if (item.type === "message") {
843
+ if (item.textContent)
844
+ return [item.role === "system" ? "developer" : item.role, item.textContent];
845
+ } else if (item.type === "function_call") {
846
+ return ["developer", `Called tool ${item.name} with ${item.args}`];
847
+ } else if (item.type === "function_call_output") {
848
+ return [
849
+ "developer",
850
+ `Tool ${item.name || item.callId} ${item.isError ? "failed with" : "returned"} ${item.output}`
851
+ ];
852
+ }
853
+ return void 0;
854
+ }
855
+ export {
856
+ GPTLiveModel,
857
+ GPTLiveSession
858
+ };
859
+ //# sourceMappingURL=gpt_live_model.js.map