@livekit/agents-plugin-openai 1.9.2 → 1.9.4

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