@livekit/agents-plugin-openai 1.4.9 → 1.5.0

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 (84) hide show
  1. package/dist/index.cjs +4 -2
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +1 -0
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +2 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/llm.cjs +8 -2
  9. package/dist/llm.cjs.map +1 -1
  10. package/dist/llm.d.cts +4 -3
  11. package/dist/llm.d.ts +4 -3
  12. package/dist/llm.d.ts.map +1 -1
  13. package/dist/llm.js +8 -2
  14. package/dist/llm.js.map +1 -1
  15. package/dist/models.cjs +12 -3
  16. package/dist/models.cjs.map +1 -1
  17. package/dist/models.d.cts +7 -1
  18. package/dist/models.d.ts +7 -1
  19. package/dist/models.d.ts.map +1 -1
  20. package/dist/models.js +11 -3
  21. package/dist/models.js.map +1 -1
  22. package/dist/realtime/api_proto.cjs.map +1 -1
  23. package/dist/realtime/api_proto.d.cts +1 -0
  24. package/dist/realtime/api_proto.d.ts +1 -0
  25. package/dist/realtime/api_proto.d.ts.map +1 -1
  26. package/dist/realtime/api_proto.js.map +1 -1
  27. package/dist/realtime/realtime_model.cjs +85 -27
  28. package/dist/realtime/realtime_model.cjs.map +1 -1
  29. package/dist/realtime/realtime_model.d.cts +2 -1
  30. package/dist/realtime/realtime_model.d.ts +2 -1
  31. package/dist/realtime/realtime_model.d.ts.map +1 -1
  32. package/dist/realtime/realtime_model.js +85 -27
  33. package/dist/realtime/realtime_model.js.map +1 -1
  34. package/dist/realtime/realtime_model.test.cjs +28 -0
  35. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  36. package/dist/realtime/realtime_model.test.js +28 -0
  37. package/dist/realtime/realtime_model.test.js.map +1 -1
  38. package/dist/responses/llm.cjs +15 -18
  39. package/dist/responses/llm.cjs.map +1 -1
  40. package/dist/responses/llm.d.cts +4 -2
  41. package/dist/responses/llm.d.ts +4 -2
  42. package/dist/responses/llm.d.ts.map +1 -1
  43. package/dist/responses/llm.js +15 -18
  44. package/dist/responses/llm.js.map +1 -1
  45. package/dist/tool_utils.cjs +53 -0
  46. package/dist/tool_utils.cjs.map +1 -0
  47. package/dist/tool_utils.d.cts +4 -0
  48. package/dist/tool_utils.d.ts +4 -0
  49. package/dist/tool_utils.d.ts.map +1 -0
  50. package/dist/tool_utils.js +29 -0
  51. package/dist/tool_utils.js.map +1 -0
  52. package/dist/tool_utils.test.cjs +77 -0
  53. package/dist/tool_utils.test.cjs.map +1 -0
  54. package/dist/tool_utils.test.d.cts +2 -0
  55. package/dist/tool_utils.test.d.ts +2 -0
  56. package/dist/tool_utils.test.d.ts.map +1 -0
  57. package/dist/tool_utils.test.js +76 -0
  58. package/dist/tool_utils.test.js.map +1 -0
  59. package/dist/tools.cjs +117 -0
  60. package/dist/tools.cjs.map +1 -0
  61. package/dist/tools.d.cts +88 -0
  62. package/dist/tools.d.ts +88 -0
  63. package/dist/tools.d.ts.map +1 -0
  64. package/dist/tools.js +90 -0
  65. package/dist/tools.js.map +1 -0
  66. package/dist/ws/llm.cjs +15 -18
  67. package/dist/ws/llm.cjs.map +1 -1
  68. package/dist/ws/llm.d.cts +5 -3
  69. package/dist/ws/llm.d.ts +5 -3
  70. package/dist/ws/llm.d.ts.map +1 -1
  71. package/dist/ws/llm.js +15 -18
  72. package/dist/ws/llm.js.map +1 -1
  73. package/package.json +7 -7
  74. package/src/index.ts +1 -0
  75. package/src/llm.ts +16 -3
  76. package/src/models.ts +18 -3
  77. package/src/realtime/api_proto.ts +1 -0
  78. package/src/realtime/realtime_model.test.ts +38 -0
  79. package/src/realtime/realtime_model.ts +104 -28
  80. package/src/responses/llm.ts +27 -23
  81. package/src/tool_utils.test.ts +84 -0
  82. package/src/tool_utils.ts +46 -0
  83. package/src/tools.ts +166 -0
  84. package/src/ws/llm.ts +25 -24
@@ -24,10 +24,13 @@ const SAMPLE_RATE = 24e3;
24
24
  const NUM_CHANNELS = 1;
25
25
  const BASE_URL = "https://api.openai.com/v1";
26
26
  const MOCK_AUDIO_ID_PREFIX = "lk_mock_audio_item_";
27
+ class DiscardedGeneration {
28
+ discarded = true;
29
+ }
27
30
  class CreateResponseHandle {
28
31
  instructions;
29
32
  doneFut;
30
- // TODO(shubhra): add timeout
33
+ timeout;
31
34
  constructor({ instructions }) {
32
35
  this.instructions = instructions;
33
36
  this.doneFut = new Future();
@@ -263,7 +266,7 @@ function processBaseURL({
263
266
  return url.toString();
264
267
  }
265
268
  class RealtimeSession extends llm.RealtimeSession {
266
- _tools = {};
269
+ _tools = llm.ToolContext.empty();
267
270
  remoteChatCtx = new llm.RemoteChatContext();
268
271
  messageChannel = new Queue();
269
272
  inputResampler;
@@ -275,6 +278,7 @@ class RealtimeSession extends llm.RealtimeSession {
275
278
  _options;
276
279
  currentGeneration;
277
280
  responseCreatedFutures = {};
281
+ discardedEventIds = /* @__PURE__ */ new Set();
278
282
  textModeRecoveryRetries = 0;
279
283
  itemCreateFutures = {};
280
284
  itemDeleteFutures = {};
@@ -359,7 +363,7 @@ class RealtimeSession extends llm.RealtimeSession {
359
363
  return this.remoteChatCtx.toChatCtx();
360
364
  }
361
365
  get tools() {
362
- return { ...this._tools };
366
+ return this._tools.copy();
363
367
  }
364
368
  async updateChatCtx(_chatCtx) {
365
369
  const unlock = await this.updateChatCtxLock.lock();
@@ -497,34 +501,31 @@ class RealtimeSession extends llm.RealtimeSession {
497
501
  throw new Error("Tools are missing in the session update event");
498
502
  }
499
503
  const retainedToolNames = new Set(ev.session.tools.map((tool) => tool.name));
500
- const retainedTools = Object.fromEntries(
501
- Object.entries(_tools).filter(
502
- ([name, tool]) => llm.isFunctionTool(tool) && retainedToolNames.has(name)
503
- )
504
+ const retainedEntries = _tools.tools.filter(
505
+ (entry) => !llm.isFunctionTool(entry) || retainedToolNames.has(entry.name)
504
506
  );
505
- this._tools = retainedTools;
507
+ this._tools = new llm.ToolContext(retainedEntries);
506
508
  unlock();
507
509
  }
508
510
  createToolsUpdateEvent(_tools) {
509
511
  const oaiTools = [];
510
- for (const [name, tool] of Object.entries(_tools)) {
511
- if (!llm.isFunctionTool(tool)) {
512
- this.#logger.error({ name, tool }, "OpenAI Realtime API doesn't support this tool type");
513
- continue;
514
- }
515
- const { parameters: toolParameters, description } = tool;
512
+ for (const t of _tools.flatten()) {
513
+ if (!llm.isFunctionTool(t)) continue;
516
514
  try {
517
515
  const parameters = llm.toJsonSchema(
518
- toolParameters
516
+ t.parameters
519
517
  );
520
518
  oaiTools.push({
521
- name,
522
- description,
519
+ name: t.name,
520
+ description: t.description,
523
521
  parameters,
524
522
  type: "function"
525
523
  });
526
524
  } catch (e) {
527
- this.#logger.error({ name, tool }, "OpenAI Realtime API doesn't support this tool type");
525
+ this.#logger.error(
526
+ { name: t.name, tool: t },
527
+ "OpenAI Realtime API doesn't support this tool type"
528
+ );
528
529
  continue;
529
530
  }
530
531
  }
@@ -598,7 +599,15 @@ class RealtimeSession extends llm.RealtimeSession {
598
599
  }
599
600
  async generateReply(instructions, options = {}) {
600
601
  var _a, _b, _c;
601
- const handle = this.createResponse({ instructions, userInitiated: true });
602
+ let responseInstructions = instructions;
603
+ if (instructions && this.instructions) {
604
+ responseInstructions = `${this.instructions}
605
+ ${instructions}`;
606
+ }
607
+ const handle = this.createResponse({
608
+ instructions: responseInstructions,
609
+ userInitiated: true
610
+ });
602
611
  this.textModeRecoveryRetries = 0;
603
612
  const onAbort = () => {
604
613
  var _a2;
@@ -607,7 +616,9 @@ class RealtimeSession extends llm.RealtimeSession {
607
616
  )) == null ? void 0 : _a2[0];
608
617
  if (eventId) {
609
618
  delete this.responseCreatedFutures[eventId];
619
+ this.discardedEventIds.add(eventId);
610
620
  }
621
+ if (handle.timeout) clearTimeout(handle.timeout);
611
622
  if (!handle.doneFut.done) {
612
623
  handle.doneFut.reject(new Error("generateReply aborted"));
613
624
  this.sendEvent({
@@ -754,13 +765,15 @@ class RealtimeSession extends llm.RealtimeSession {
754
765
  if (!handle.doneFut.done) {
755
766
  handle.doneFut.reject(new Error("Session reconnected"));
756
767
  }
768
+ if (handle.timeout) clearTimeout(handle.timeout);
757
769
  }
758
770
  this.responseCreatedFutures = {};
771
+ this.discardedEventIds.clear();
759
772
  this.audioCapableItemIds.clear();
760
773
  this.inputTranscriptAccumulators.clear();
761
774
  const events = [];
762
775
  events.push(this.createSessionUpdateEvent());
763
- if (Object.keys(this._tools).length > 0) {
776
+ if (Object.keys(this._tools.functionTools).length > 0) {
764
777
  events.push(this.createToolsUpdateEvent(this._tools));
765
778
  }
766
779
  const chatCtx = this.chatCtx.copy({
@@ -965,8 +978,13 @@ class RealtimeSession extends llm.RealtimeSession {
965
978
  });
966
979
  try {
967
980
  const result = await Promise.race([wsTask.result, sendTask.result, waitReconnectTask.result]);
968
- if (waitReconnectTask.done && this.currentGeneration) {
969
- await this.currentGeneration._doneFut.await;
981
+ const currentGeneration = this.currentGeneration;
982
+ if (waitReconnectTask.done && currentGeneration) {
983
+ if (currentGeneration instanceof DiscardedGeneration) {
984
+ this.currentGeneration = void 0;
985
+ } else {
986
+ await currentGeneration._doneFut.await;
987
+ }
970
988
  }
971
989
  if (result instanceof Error) {
972
990
  throw result;
@@ -984,6 +1002,7 @@ class RealtimeSession extends llm.RealtimeSession {
984
1002
  if (!handle.doneFut.done) {
985
1003
  handle.doneFut.reject(new Error("Session closed"));
986
1004
  }
1005
+ if (handle.timeout) clearTimeout(handle.timeout);
987
1006
  }
988
1007
  this.responseCreatedFutures = {};
989
1008
  for (const fut of Object.values(this.itemCreateFutures)) {
@@ -999,7 +1018,9 @@ class RealtimeSession extends llm.RealtimeSession {
999
1018
  }
1000
1019
  this.itemDeleteFutures = {};
1001
1020
  this.inputTranscriptAccumulators.clear();
1002
- if (this.currentGeneration) {
1021
+ if (this.currentGeneration instanceof DiscardedGeneration) {
1022
+ this.currentGeneration = void 0;
1023
+ } else if (this.currentGeneration) {
1003
1024
  for (const gen of this.currentGeneration.messages.values()) {
1004
1025
  gen.textChannel.close();
1005
1026
  gen.audioChannel.close();
@@ -1030,24 +1051,36 @@ class RealtimeSession extends llm.RealtimeSession {
1030
1051
  if (!event.response.id) {
1031
1052
  throw new Error("response.id is missing");
1032
1053
  }
1033
- this.currentGeneration = {
1054
+ const clientEventId = (_a = event.response.metadata) == null ? void 0 : _a.client_event_id;
1055
+ if (clientEventId && this.discardedEventIds.has(clientEventId)) {
1056
+ this.discardedEventIds.delete(clientEventId);
1057
+ this.sendEvent({
1058
+ type: "response.cancel",
1059
+ response_id: event.response.id
1060
+ });
1061
+ this.currentGeneration = new DiscardedGeneration();
1062
+ this.#logger.warn("discarding response that arrived after it was timed out or interrupted");
1063
+ return;
1064
+ }
1065
+ const currentGeneration = {
1034
1066
  messageChannel: stream.createStreamChannel(),
1035
1067
  functionChannel: stream.createStreamChannel(),
1036
1068
  messages: /* @__PURE__ */ new Map(),
1037
1069
  _doneFut: new Future(),
1038
1070
  _createdTimestamp: Date.now()
1039
1071
  };
1072
+ this.currentGeneration = currentGeneration;
1040
1073
  const generationEv = {
1041
- messageStream: this.currentGeneration.messageChannel.stream(),
1042
- functionStream: this.currentGeneration.functionChannel.stream(),
1074
+ messageStream: currentGeneration.messageChannel.stream(),
1075
+ functionStream: currentGeneration.functionChannel.stream(),
1043
1076
  userInitiated: false,
1044
1077
  responseId: event.response.id
1045
1078
  };
1046
- const clientEventId = (_a = event.response.metadata) == null ? void 0 : _a.client_event_id;
1047
1079
  if (clientEventId) {
1048
1080
  const handle = this.responseCreatedFutures[clientEventId];
1049
1081
  if (handle) {
1050
1082
  delete this.responseCreatedFutures[clientEventId];
1083
+ if (handle.timeout) clearTimeout(handle.timeout);
1051
1084
  generationEv.userInitiated = true;
1052
1085
  if (!handle.doneFut.done) {
1053
1086
  handle.doneFut.resolve(generationEv);
@@ -1057,6 +1090,7 @@ class RealtimeSession extends llm.RealtimeSession {
1057
1090
  this.emit("generation_created", generationEv);
1058
1091
  }
1059
1092
  handleResponseOutputItemAdded(event) {
1093
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1060
1094
  if (!this.currentGeneration) {
1061
1095
  throw new Error("currentGeneration is not set");
1062
1096
  }
@@ -1190,6 +1224,7 @@ class RealtimeSession extends llm.RealtimeSession {
1190
1224
  });
1191
1225
  }
1192
1226
  handleResponseContentPartAdded(event) {
1227
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1193
1228
  if (!this.currentGeneration) {
1194
1229
  throw new Error("currentGeneration is not set");
1195
1230
  }
@@ -1216,6 +1251,7 @@ class RealtimeSession extends llm.RealtimeSession {
1216
1251
  }
1217
1252
  }
1218
1253
  handleResponseContentPartDone(event) {
1254
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1219
1255
  if (!event.part) {
1220
1256
  return;
1221
1257
  }
@@ -1227,6 +1263,7 @@ class RealtimeSession extends llm.RealtimeSession {
1227
1263
  }
1228
1264
  }
1229
1265
  handleResponseTextDelta(event) {
1266
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1230
1267
  if (!this.currentGeneration) {
1231
1268
  throw new Error("currentGeneration is not set");
1232
1269
  }
@@ -1241,11 +1278,13 @@ class RealtimeSession extends llm.RealtimeSession {
1241
1278
  itemGeneration.audioTranscript += event.delta;
1242
1279
  }
1243
1280
  handleResponseTextDone(_event) {
1281
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1244
1282
  if (!this.currentGeneration) {
1245
1283
  throw new Error("currentGeneration is not set");
1246
1284
  }
1247
1285
  }
1248
1286
  handleResponseAudioTranscriptDelta(event) {
1287
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1249
1288
  if (!this.currentGeneration) {
1250
1289
  throw new Error("currentGeneration is not set");
1251
1290
  }
@@ -1263,6 +1302,7 @@ class RealtimeSession extends llm.RealtimeSession {
1263
1302
  }
1264
1303
  }
1265
1304
  handleResponseAudioDelta(event) {
1305
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1266
1306
  if (!this.currentGeneration) {
1267
1307
  throw new Error("currentGeneration is not set");
1268
1308
  }
@@ -1292,16 +1332,19 @@ class RealtimeSession extends llm.RealtimeSession {
1292
1332
  );
1293
1333
  }
1294
1334
  handleResponseAudioTranscriptDone(_event) {
1335
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1295
1336
  if (!this.currentGeneration) {
1296
1337
  throw new Error("currentGeneration is not set");
1297
1338
  }
1298
1339
  }
1299
1340
  handleResponseAudioDone(_event) {
1341
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1300
1342
  if (!this.currentGeneration) {
1301
1343
  throw new Error("currentGeneration is not set");
1302
1344
  }
1303
1345
  }
1304
1346
  handleResponseOutputItemDone(event) {
1347
+ if (this.currentGeneration instanceof DiscardedGeneration) return;
1305
1348
  if (!this.currentGeneration) {
1306
1349
  throw new Error("currentGeneration is not set");
1307
1350
  }
@@ -1333,6 +1376,10 @@ class RealtimeSession extends llm.RealtimeSession {
1333
1376
  }
1334
1377
  handleResponseDone(_event) {
1335
1378
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
1379
+ if (this.currentGeneration instanceof DiscardedGeneration) {
1380
+ this.currentGeneration = void 0;
1381
+ return;
1382
+ }
1336
1383
  if (!this.currentGeneration) {
1337
1384
  return;
1338
1385
  }
@@ -1445,6 +1492,7 @@ class RealtimeSession extends llm.RealtimeSession {
1445
1492
  const handle = this.responseCreatedFutures[eventId];
1446
1493
  if (handle) {
1447
1494
  delete this.responseCreatedFutures[eventId];
1495
+ if (handle.timeout) clearTimeout(handle.timeout);
1448
1496
  if (!handle.doneFut.done) {
1449
1497
  handle.doneFut.reject(new Error(event.error.message));
1450
1498
  }
@@ -1481,8 +1529,18 @@ class RealtimeSession extends llm.RealtimeSession {
1481
1529
  handle.instructions = instructions;
1482
1530
  }
1483
1531
  const eventId = shortuuid("response_create_");
1532
+ this.discardedEventIds ??= /* @__PURE__ */ new Set();
1484
1533
  if (userInitiated) {
1485
1534
  this.responseCreatedFutures[eventId] = handle;
1535
+ handle.timeout = setTimeout(() => {
1536
+ if (this.responseCreatedFutures[eventId] === handle) {
1537
+ delete this.responseCreatedFutures[eventId];
1538
+ }
1539
+ if (!handle.doneFut.done) {
1540
+ this.discardedEventIds.add(eventId);
1541
+ handle.doneFut.reject(new Error("generateReply timed out."));
1542
+ }
1543
+ }, 1e4);
1486
1544
  }
1487
1545
  const response = {};
1488
1546
  if (instructions) response.instructions = instructions;