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