@livekit/agents-plugin-openai 1.3.0 → 1.3.3

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.
@@ -415,6 +415,10 @@ export class RealtimeSession extends llm.RealtimeSession {
415
415
  private inputResampler?: AudioResampler;
416
416
  private instructions?: string;
417
417
  private oaiRealtimeModel: RealtimeModel;
418
+ // Ref: python livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/realtime_model.py - 795-797 lines
419
+ // per-session copy of options so updateOptions can diff against the session's
420
+ // own state instead of the shared model-level state.
421
+ private _options: RealtimeOptions;
418
422
  private currentGeneration?: ResponseGeneration;
419
423
  private responseCreatedFutures: { [id: string]: CreateResponseHandle } = {};
420
424
 
@@ -443,6 +447,12 @@ export class RealtimeSession extends llm.RealtimeSession {
443
447
  super(realtimeModel);
444
448
 
445
449
  this.oaiRealtimeModel = realtimeModel;
450
+ // Ref: python livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/realtime_model.py - 796-797 lines
451
+ // Shallow copy (equivalent to Python's `dataclasses.replace`) so each
452
+ // session has independent option state. Without this, updateOptions would
453
+ // mutate the shared model._options before computing its diff, causing the
454
+ // diff to always see "no change" and never send session.update.
455
+ this._options = { ...realtimeModel._options };
446
456
 
447
457
  this.#task = Task.from(({ signal }) => this.#mainTask(signal));
448
458
 
@@ -460,7 +470,7 @@ export class RealtimeSession extends llm.RealtimeSession {
460
470
  }
461
471
 
462
472
  private createSessionUpdateEvent(): api_proto.SessionUpdateEvent {
463
- const opts = this.oaiRealtimeModel._options;
473
+ const opts = this._options;
464
474
  const maxOutputTokens =
465
475
  opts.maxResponseOutputTokens === Infinity ? 'inf' : opts.maxResponseOutputTokens;
466
476
 
@@ -722,13 +732,12 @@ export class RealtimeSession extends llm.RealtimeSession {
722
732
  }
723
733
  }
724
734
 
725
- const isLegacyAzure =
726
- this.oaiRealtimeModel._options.isAzure && !!this.oaiRealtimeModel._options.apiVersion;
735
+ const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
727
736
  return {
728
737
  type: 'session.update',
729
738
  session: {
730
739
  ...(!isLegacyAzure && { type: 'realtime' }),
731
- model: this.oaiRealtimeModel._options.model,
740
+ model: this._options.model,
732
741
  tools: oaiTools,
733
742
  },
734
743
  event_id: shortuuid('tools_update_'),
@@ -736,8 +745,7 @@ export class RealtimeSession extends llm.RealtimeSession {
736
745
  }
737
746
 
738
747
  async updateInstructions(_instructions: string): Promise<void> {
739
- const isLegacyAzure =
740
- this.oaiRealtimeModel._options.isAzure && !!this.oaiRealtimeModel._options.apiVersion;
748
+ const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
741
749
  const eventId = shortuuid('instructions_update_');
742
750
  this.sendEvent({
743
751
  type: 'session.update',
@@ -751,20 +759,19 @@ export class RealtimeSession extends llm.RealtimeSession {
751
759
  }
752
760
 
753
761
  updateOptions({ toolChoice }: { toolChoice?: llm.ToolChoice }): void {
754
- const currentToolChoice = toOaiToolChoice(this.oaiRealtimeModel._options.toolChoice);
762
+ const currentToolChoice = toOaiToolChoice(this._options.toolChoice);
755
763
  const nextToolChoice = toOaiToolChoice(toolChoice);
756
764
  if (currentToolChoice === nextToolChoice) {
757
- this.oaiRealtimeModel._options.toolChoice = toolChoice;
765
+ this._options.toolChoice = toolChoice;
758
766
  return;
759
767
  }
760
768
 
761
- const isLegacyAzure =
762
- this.oaiRealtimeModel._options.isAzure && !!this.oaiRealtimeModel._options.apiVersion;
769
+ const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
763
770
  const options: api_proto.SessionUpdateEvent['session'] = {
764
771
  ...(!isLegacyAzure && { type: 'realtime' }),
765
772
  };
766
773
 
767
- this.oaiRealtimeModel._options.toolChoice = toolChoice;
774
+ this._options.toolChoice = toolChoice;
768
775
  options.tool_choice = toOaiToolChoice(toolChoice);
769
776
 
770
777
  // TODO(brian): add other options here
@@ -889,32 +896,32 @@ export class RealtimeSession extends llm.RealtimeSession {
889
896
  'User-Agent': 'LiveKit-Agents-JS',
890
897
  };
891
898
 
892
- if (this.oaiRealtimeModel._options.isAzure) {
899
+ if (this._options.isAzure) {
893
900
  // Microsoft API has two ways of authentication
894
901
  // 1. Entra token set as `Bearer` token
895
902
  // 2. API key set as `api_key` header (also accepts query string)
896
- if (this.oaiRealtimeModel._options.entraToken) {
897
- headers.Authorization = `Bearer ${this.oaiRealtimeModel._options.entraToken}`;
898
- } else if (this.oaiRealtimeModel._options.apiKey) {
899
- headers['api-key'] = this.oaiRealtimeModel._options.apiKey;
903
+ if (this._options.entraToken) {
904
+ headers.Authorization = `Bearer ${this._options.entraToken}`;
905
+ } else if (this._options.apiKey) {
906
+ headers['api-key'] = this._options.apiKey;
900
907
  } else {
901
908
  throw new Error('Microsoft API key or entraToken is required');
902
909
  }
903
910
  } else {
904
- if (!this.oaiRealtimeModel._options.apiKey) {
911
+ if (!this._options.apiKey) {
905
912
  throw new Error(
906
913
  'OpenAI API key is required but not set. Check OPENAI_API_KEY environment variable.',
907
914
  );
908
915
  }
909
- headers.Authorization = `Bearer ${this.oaiRealtimeModel._options.apiKey}`;
916
+ headers.Authorization = `Bearer ${this._options.apiKey}`;
910
917
  }
911
918
 
912
919
  const url = processBaseURL({
913
- baseURL: this.oaiRealtimeModel._options.baseURL,
914
- model: this.oaiRealtimeModel._options.model,
915
- isAzure: this.oaiRealtimeModel._options.isAzure,
916
- apiVersion: this.oaiRealtimeModel._options.apiVersion,
917
- azureDeployment: this.oaiRealtimeModel._options.azureDeployment,
920
+ baseURL: this._options.baseURL,
921
+ model: this._options.model,
922
+ isAzure: this._options.isAzure,
923
+ apiVersion: this._options.apiVersion,
924
+ azureDeployment: this._options.azureDeployment,
918
925
  });
919
926
 
920
927
  if (lkOaiDebug) {
@@ -928,7 +935,7 @@ export class RealtimeSession extends llm.RealtimeSession {
928
935
  const timeout = setTimeout(() => {
929
936
  ws.close();
930
937
  reject(new Error('WebSocket connection timeout'));
931
- }, this.oaiRealtimeModel._options.connOptions.timeoutMs);
938
+ }, this._options.connOptions.timeoutMs);
932
939
 
933
940
  ws.once('open', () => {
934
941
  if (!waiting) return;
@@ -950,12 +957,12 @@ export class RealtimeSession extends llm.RealtimeSession {
950
957
  let reconnecting = false;
951
958
  let numRetries = 0;
952
959
  let wsConn: WebSocket | null = null;
953
- const maxRetries = this.oaiRealtimeModel._options.connOptions.maxRetry;
960
+ const maxRetries = this._options.connOptions.maxRetry;
954
961
 
955
962
  const reconnect = async () => {
956
963
  this.#logger.debug(
957
964
  {
958
- maxSessionDuration: this.oaiRealtimeModel._options.maxSessionDuration,
965
+ maxSessionDuration: this._options.maxSessionDuration,
959
966
  },
960
967
  'Reconnecting to OpenAI Realtime API',
961
968
  );
@@ -1005,7 +1012,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1005
1012
  try {
1006
1013
  for (const ev of events) {
1007
1014
  this.emit('openai_client_event_queued', ev);
1008
- if (this.oaiRealtimeModel._options.isAzure && this.oaiRealtimeModel._options.apiVersion) {
1015
+ if (this._options.isAzure && this._options.apiVersion) {
1009
1016
  normalizeAzureClientEvent(ev as unknown as Record<string, unknown>);
1010
1017
  }
1011
1018
  wsConn!.send(JSON.stringify(ev));
@@ -1063,7 +1070,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1063
1070
  const retryInterval =
1064
1071
  numRetries === 0
1065
1072
  ? DEFAULT_FIRST_RETRY_INTERVAL_MS
1066
- : this.oaiRealtimeModel._options.connOptions.retryIntervalMs;
1073
+ : this._options.connOptions.retryIntervalMs;
1067
1074
  this.#logger.warn(
1068
1075
  {
1069
1076
  attempt: numRetries,
@@ -1098,7 +1105,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1098
1105
  }
1099
1106
 
1100
1107
  this.emit('openai_client_event_queued', event);
1101
- if (this.oaiRealtimeModel._options.isAzure && this.oaiRealtimeModel._options.apiVersion) {
1108
+ if (this._options.isAzure && this._options.apiVersion) {
1102
1109
  normalizeAzureClientEvent(event as unknown as Record<string, unknown>);
1103
1110
  }
1104
1111
  wsConn.send(JSON.stringify(event));
@@ -1214,7 +1221,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1214
1221
  });
1215
1222
 
1216
1223
  const waitReconnectTask = Task.from(async ({ signal }) => {
1217
- await delay(this.oaiRealtimeModel._options.maxSessionDuration, { signal });
1224
+ await delay(this._options.maxSessionDuration, { signal });
1218
1225
  return new APIConnectionError({
1219
1226
  message: 'OpenAI Realtime API connection timeout',
1220
1227
  });
@@ -1269,7 +1276,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1269
1276
  gen.textChannel.close();
1270
1277
  gen.audioChannel.close();
1271
1278
  if (!gen.modalities.done) {
1272
- gen.modalities.resolve(this.oaiRealtimeModel._options.modalities);
1279
+ gen.modalities.resolve(this._options.modalities);
1273
1280
  }
1274
1281
  }
1275
1282
  this.currentGeneration.messages.clear();
@@ -1295,7 +1302,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1295
1302
  _event: api_proto.InputAudioBufferSpeechStoppedEvent,
1296
1303
  ): void {
1297
1304
  this.emit('input_speech_stopped', {
1298
- userTranscriptionEnabled: this.oaiRealtimeModel._options.inputAudioTranscription !== null,
1305
+ userTranscriptionEnabled: this._options.inputAudioTranscription !== null,
1299
1306
  } as llm.InputSpeechStoppedEvent);
1300
1307
  }
1301
1308
 
@@ -1644,7 +1651,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1644
1651
  itemGeneration.audioChannel.close();
1645
1652
  if (!itemGeneration.modalities.done) {
1646
1653
  // In case message modalities is not set, this shouldn't happen
1647
- itemGeneration.modalities.resolve(this.oaiRealtimeModel._options.modalities);
1654
+ itemGeneration.modalities.resolve(this._options.modalities);
1648
1655
  }
1649
1656
  }
1650
1657
  }
@@ -1670,7 +1677,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1670
1677
  generation.textChannel.close();
1671
1678
  generation.audioChannel.close();
1672
1679
  if (!generation.modalities.done) {
1673
- generation.modalities.resolve(this.oaiRealtimeModel._options.modalities);
1680
+ generation.modalities.resolve(this._options.modalities);
1674
1681
  }
1675
1682
  }
1676
1683
 
@@ -1733,6 +1740,18 @@ export class RealtimeSession extends llm.RealtimeSession {
1733
1740
  return;
1734
1741
  }
1735
1742
  this.#logger.error({ error: event.error }, 'OpenAI Realtime API returned an error');
1743
+
1744
+ const eventId = event.error.event_id;
1745
+ if (eventId) {
1746
+ const handle = this.responseCreatedFutures[eventId];
1747
+ if (handle) {
1748
+ delete this.responseCreatedFutures[eventId];
1749
+ if (!handle.doneFut.done) {
1750
+ handle.doneFut.reject(new Error(event.error.message));
1751
+ }
1752
+ }
1753
+ }
1754
+
1736
1755
  this.emitError({
1737
1756
  error: new APIError(event.error.message, {
1738
1757
  body: event.error,
@@ -1740,8 +1759,6 @@ export class RealtimeSession extends llm.RealtimeSession {
1740
1759
  }),
1741
1760
  recoverable: true,
1742
1761
  });
1743
-
1744
- // TODO(brian): set error for response future if it exists
1745
1762
  }
1746
1763
 
1747
1764
  private emitError({ error, recoverable }: { error: Error; recoverable: boolean }): void {