@livekit/agents-plugin-openai 1.5.2 → 1.5.5
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.
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/realtime/realtime_model.cjs +216 -160
- package/dist/realtime/realtime_model.cjs.map +1 -1
- package/dist/realtime/realtime_model.d.cts +4 -0
- package/dist/realtime/realtime_model.d.ts +4 -0
- package/dist/realtime/realtime_model.d.ts.map +1 -1
- package/dist/realtime/realtime_model.js +215 -160
- package/dist/realtime/realtime_model.js.map +1 -1
- package/dist/realtime/realtime_model.test.cjs +216 -0
- package/dist/realtime/realtime_model.test.cjs.map +1 -1
- package/dist/realtime/realtime_model.test.js +217 -0
- package/dist/realtime/realtime_model.test.js.map +1 -1
- package/dist/ws/llm.cjs +6 -3
- package/dist/ws/llm.cjs.map +1 -1
- package/dist/ws/llm.d.cts +4 -5
- package/dist/ws/llm.d.ts +4 -5
- package/dist/ws/llm.d.ts.map +1 -1
- package/dist/ws/llm.js +6 -3
- package/dist/ws/llm.js.map +1 -1
- package/dist/ws/llm.test.cjs +22 -2
- package/dist/ws/llm.test.cjs.map +1 -1
- package/dist/ws/llm.test.js +22 -2
- package/dist/ws/llm.test.js.map +1 -1
- package/package.json +5 -5
- package/src/realtime/realtime_model.test.ts +265 -0
- package/src/realtime/realtime_model.ts +229 -164
- package/src/ws/llm.test.ts +28 -2
- package/src/ws/llm.ts +13 -8
|
@@ -86,6 +86,22 @@ class DiscardedGeneration {
|
|
|
86
86
|
readonly discarded = true;
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
// These server-side errors cannot be fixed by reconnecting; retrying only loops forever.
|
|
90
|
+
const FATAL_ERROR_CODES = new Set([
|
|
91
|
+
'insufficient_quota',
|
|
92
|
+
'invalid_api_key',
|
|
93
|
+
'account_deactivated',
|
|
94
|
+
'billing_hard_limit_reached',
|
|
95
|
+
]);
|
|
96
|
+
|
|
97
|
+
/** @internal Exported for testing purposes */
|
|
98
|
+
export function isFatalError(error: unknown): boolean {
|
|
99
|
+
if (error === null || typeof error !== 'object') return false;
|
|
100
|
+
const { code, type } = error as { code?: unknown; type?: unknown };
|
|
101
|
+
const errorCode = typeof code === 'string' && code.length > 0 ? code : type;
|
|
102
|
+
return typeof errorCode === 'string' && FATAL_ERROR_CODES.has(errorCode);
|
|
103
|
+
}
|
|
104
|
+
|
|
89
105
|
class CreateResponseHandle {
|
|
90
106
|
instructions?: string;
|
|
91
107
|
doneFut: Future<llm.GenerationCreatedEvent>;
|
|
@@ -698,7 +714,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
698
714
|
} as api_proto.ConversationItemDeleteEvent);
|
|
699
715
|
}
|
|
700
716
|
|
|
701
|
-
|
|
717
|
+
const createItem = async (previousId: string | null, id: string) => {
|
|
702
718
|
const chatItem = newChatCtx.getById(id);
|
|
703
719
|
if (!chatItem) {
|
|
704
720
|
throw new Error(`Chat item ${id} not found`);
|
|
@@ -709,6 +725,27 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
709
725
|
previous_item_id: previousId ?? undefined,
|
|
710
726
|
event_id: shortuuid('chat_ctx_create_'),
|
|
711
727
|
} as api_proto.ConversationItemCreateEvent);
|
|
728
|
+
};
|
|
729
|
+
|
|
730
|
+
const isContentEmpty = (id: string) => {
|
|
731
|
+
const remoteItem = remoteCtx.getById(id);
|
|
732
|
+
return remoteItem?.type === 'message' && remoteItem.content.length === 0;
|
|
733
|
+
};
|
|
734
|
+
|
|
735
|
+
for (const [previousId, id] of diffOps.toCreate) {
|
|
736
|
+
await createItem(previousId, id);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
for (const [previousId, id] of diffOps.toUpdate) {
|
|
740
|
+
if (isContentEmpty(id)) {
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
events.push({
|
|
744
|
+
type: 'conversation.item.delete',
|
|
745
|
+
item_id: id,
|
|
746
|
+
event_id: shortuuid('chat_ctx_delete_'),
|
|
747
|
+
} as api_proto.ConversationItemDeleteEvent);
|
|
748
|
+
await createItem(previousId, id);
|
|
712
749
|
}
|
|
713
750
|
return events;
|
|
714
751
|
}
|
|
@@ -969,6 +1006,41 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
969
1006
|
return untypedEvent;
|
|
970
1007
|
}
|
|
971
1008
|
|
|
1009
|
+
private closeCurrentGeneration(reason: string): void {
|
|
1010
|
+
if (this.currentGeneration instanceof DiscardedGeneration) {
|
|
1011
|
+
this.currentGeneration = undefined;
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
if (!this.currentGeneration) return;
|
|
1016
|
+
|
|
1017
|
+
for (const gen of this.currentGeneration.messages.values()) {
|
|
1018
|
+
gen.textChannel.close();
|
|
1019
|
+
gen.audioChannel.close();
|
|
1020
|
+
if (!gen.modalities.done) {
|
|
1021
|
+
gen.modalities.resolve(this._options.modalities);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
this.currentGeneration.messages.clear();
|
|
1025
|
+
this.currentGeneration.messageChannel.close();
|
|
1026
|
+
this.currentGeneration.functionChannel.close();
|
|
1027
|
+
if (!this.currentGeneration._doneFut.done) {
|
|
1028
|
+
this.currentGeneration._doneFut.resolve();
|
|
1029
|
+
}
|
|
1030
|
+
this.#logger.warn(`In-progress generation discarded due to ${reason}`);
|
|
1031
|
+
this.currentGeneration = undefined;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
private rejectResponseCreatedFutures(reason: string): void {
|
|
1035
|
+
for (const handle of Object.values(this.responseCreatedFutures)) {
|
|
1036
|
+
if (!handle.doneFut.done) {
|
|
1037
|
+
handle.doneFut.reject(new Error(reason));
|
|
1038
|
+
}
|
|
1039
|
+
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1040
|
+
}
|
|
1041
|
+
this.responseCreatedFutures = {};
|
|
1042
|
+
}
|
|
1043
|
+
|
|
972
1044
|
private async createWsConn(): Promise<WebSocket> {
|
|
973
1045
|
const headers: Record<string, string> = {
|
|
974
1046
|
'User-Agent': 'LiveKit-Agents-JS',
|
|
@@ -1056,14 +1128,9 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1056
1128
|
}
|
|
1057
1129
|
this.itemDeleteFutures = {};
|
|
1058
1130
|
|
|
1059
|
-
|
|
1060
|
-
if (!handle.doneFut.done) {
|
|
1061
|
-
handle.doneFut.reject(new Error('Session reconnected'));
|
|
1062
|
-
}
|
|
1063
|
-
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1064
|
-
}
|
|
1065
|
-
this.responseCreatedFutures = {};
|
|
1131
|
+
this.rejectResponseCreatedFutures('Session reconnected');
|
|
1066
1132
|
this.discardedEventIds.clear();
|
|
1133
|
+
this.closeCurrentGeneration('session reconnection');
|
|
1067
1134
|
|
|
1068
1135
|
// Clear audio-capable item tracking - restored items are text-only on the server
|
|
1069
1136
|
this.audioCapableItemIds.clear();
|
|
@@ -1111,61 +1178,66 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1111
1178
|
};
|
|
1112
1179
|
|
|
1113
1180
|
reconnecting = false;
|
|
1114
|
-
|
|
1115
|
-
this.#
|
|
1116
|
-
|
|
1117
|
-
|
|
1181
|
+
try {
|
|
1182
|
+
while (!this.#closed && !signal.aborted) {
|
|
1183
|
+
this.#logger.debug('Creating WebSocket connection to OpenAI Realtime API');
|
|
1184
|
+
wsConn = await this.createWsConn();
|
|
1185
|
+
if (signal.aborted) break;
|
|
1118
1186
|
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1187
|
+
try {
|
|
1188
|
+
if (reconnecting) {
|
|
1189
|
+
await reconnect();
|
|
1190
|
+
if (signal.aborted) break;
|
|
1191
|
+
numRetries = 0;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
await this.runWs(wsConn);
|
|
1122
1195
|
if (signal.aborted) break;
|
|
1123
|
-
|
|
1124
|
-
|
|
1196
|
+
} catch (error) {
|
|
1197
|
+
if (!isAPIError(error)) {
|
|
1198
|
+
this.emitError({ error: error as Error, recoverable: false });
|
|
1199
|
+
throw error;
|
|
1200
|
+
}
|
|
1125
1201
|
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
this.emitError({ error: error as Error, recoverable: false });
|
|
1131
|
-
throw error;
|
|
1132
|
-
}
|
|
1202
|
+
if (maxRetries === 0 || !error.retryable) {
|
|
1203
|
+
this.emitError({ error: error as Error, recoverable: false });
|
|
1204
|
+
throw error;
|
|
1205
|
+
}
|
|
1133
1206
|
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1207
|
+
if (numRetries === maxRetries) {
|
|
1208
|
+
this.emitError({ error: error as Error, recoverable: false });
|
|
1209
|
+
throw new APIConnectionError({
|
|
1210
|
+
message: `OpenAI Realtime API connection failed after ${numRetries} attempts`,
|
|
1211
|
+
options: {
|
|
1212
|
+
body: error,
|
|
1213
|
+
retryable: false,
|
|
1214
|
+
},
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1138
1217
|
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1218
|
+
this.emitError({ error: error as Error, recoverable: true });
|
|
1219
|
+
const retryInterval =
|
|
1220
|
+
numRetries === 0
|
|
1221
|
+
? DEFAULT_FIRST_RETRY_INTERVAL_MS
|
|
1222
|
+
: this._options.connOptions.retryIntervalMs;
|
|
1223
|
+
this.#logger.warn(
|
|
1224
|
+
{
|
|
1225
|
+
attempt: numRetries,
|
|
1226
|
+
maxRetries,
|
|
1227
|
+
error,
|
|
1146
1228
|
},
|
|
1147
|
-
|
|
1148
|
-
|
|
1229
|
+
`OpenAI Realtime API connection failed, retrying in ${retryInterval / 1000}s`,
|
|
1230
|
+
);
|
|
1149
1231
|
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
? DEFAULT_FIRST_RETRY_INTERVAL_MS
|
|
1154
|
-
: this._options.connOptions.retryIntervalMs;
|
|
1155
|
-
this.#logger.warn(
|
|
1156
|
-
{
|
|
1157
|
-
attempt: numRetries,
|
|
1158
|
-
maxRetries,
|
|
1159
|
-
error,
|
|
1160
|
-
},
|
|
1161
|
-
`OpenAI Realtime API connection failed, retrying in ${retryInterval / 1000}s`,
|
|
1162
|
-
);
|
|
1232
|
+
await delay(retryInterval);
|
|
1233
|
+
numRetries++;
|
|
1234
|
+
}
|
|
1163
1235
|
|
|
1164
|
-
|
|
1165
|
-
numRetries++;
|
|
1236
|
+
reconnecting = true;
|
|
1166
1237
|
}
|
|
1167
|
-
|
|
1168
|
-
|
|
1238
|
+
} finally {
|
|
1239
|
+
this.closeCurrentGeneration('session close');
|
|
1240
|
+
this.rejectResponseCreatedFutures('Realtime session closed');
|
|
1169
1241
|
}
|
|
1170
1242
|
}
|
|
1171
1243
|
|
|
@@ -1216,79 +1288,88 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1216
1288
|
this.#logger.debug(this.loggableEvent(event), `(server) <- ${event.type}`);
|
|
1217
1289
|
}
|
|
1218
1290
|
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1291
|
+
try {
|
|
1292
|
+
switch (event.type) {
|
|
1293
|
+
case 'input_audio_buffer.speech_started':
|
|
1294
|
+
this.handleInputAudioBufferSpeechStarted(event);
|
|
1295
|
+
break;
|
|
1296
|
+
case 'input_audio_buffer.speech_stopped':
|
|
1297
|
+
this.handleInputAudioBufferSpeechStopped(event);
|
|
1298
|
+
break;
|
|
1299
|
+
case 'response.created':
|
|
1300
|
+
this.handleResponseCreated(event);
|
|
1301
|
+
break;
|
|
1302
|
+
case 'response.output_item.added':
|
|
1303
|
+
this.handleResponseOutputItemAdded(event);
|
|
1304
|
+
break;
|
|
1305
|
+
case 'conversation.item.added':
|
|
1306
|
+
case 'conversation.item.created': // Beta: kept for backward compatibility
|
|
1307
|
+
this.handleConversationItemCreated(event);
|
|
1308
|
+
break;
|
|
1309
|
+
case 'conversation.item.deleted':
|
|
1310
|
+
this.handleConversationItemDeleted(event);
|
|
1311
|
+
break;
|
|
1312
|
+
case 'conversation.item.input_audio_transcription.delta':
|
|
1313
|
+
this.handleConversationItemInputAudioTranscriptionDelta(event);
|
|
1314
|
+
break;
|
|
1315
|
+
case 'conversation.item.input_audio_transcription.completed':
|
|
1316
|
+
this.handleConversationItemInputAudioTranscriptionCompleted(event);
|
|
1317
|
+
break;
|
|
1318
|
+
case 'conversation.item.input_audio_transcription.failed':
|
|
1319
|
+
this.handleConversationItemInputAudioTranscriptionFailed(event);
|
|
1320
|
+
break;
|
|
1321
|
+
case 'response.content_part.added':
|
|
1322
|
+
this.handleResponseContentPartAdded(event);
|
|
1323
|
+
break;
|
|
1324
|
+
case 'response.content_part.done':
|
|
1325
|
+
this.handleResponseContentPartDone(event);
|
|
1326
|
+
break;
|
|
1327
|
+
case 'response.output_text.delta':
|
|
1328
|
+
case 'response.text.delta': // Beta: kept for backward compatibility
|
|
1329
|
+
this.handleResponseTextDelta(event);
|
|
1330
|
+
break;
|
|
1331
|
+
case 'response.output_text.done':
|
|
1332
|
+
case 'response.text.done': // Beta: kept for backward compatibility
|
|
1333
|
+
this.handleResponseTextDone(event);
|
|
1334
|
+
break;
|
|
1335
|
+
case 'response.output_audio_transcript.delta':
|
|
1336
|
+
case 'response.audio_transcript.delta': // Beta: kept for backward compatibility
|
|
1337
|
+
this.handleResponseAudioTranscriptDelta(event);
|
|
1338
|
+
break;
|
|
1339
|
+
case 'response.output_audio.delta':
|
|
1340
|
+
case 'response.audio.delta': // Beta: kept for backward compatibility
|
|
1341
|
+
this.handleResponseAudioDelta(event);
|
|
1342
|
+
break;
|
|
1343
|
+
case 'response.output_audio_transcript.done':
|
|
1344
|
+
case 'response.audio_transcript.done': // Beta: kept for backward compatibility
|
|
1345
|
+
this.handleResponseAudioTranscriptDone(event);
|
|
1346
|
+
break;
|
|
1347
|
+
case 'response.output_audio.done':
|
|
1348
|
+
case 'response.audio.done': // Beta: kept for backward compatibility
|
|
1349
|
+
this.handleResponseAudioDone(event);
|
|
1350
|
+
break;
|
|
1351
|
+
case 'response.output_item.done':
|
|
1352
|
+
this.handleResponseOutputItemDone(event);
|
|
1353
|
+
break;
|
|
1354
|
+
case 'response.done':
|
|
1355
|
+
this.handleResponseDone(event);
|
|
1356
|
+
break;
|
|
1357
|
+
case 'error':
|
|
1358
|
+
this.handleError(event);
|
|
1359
|
+
break;
|
|
1360
|
+
default:
|
|
1361
|
+
if (lkOaiDebug) {
|
|
1362
|
+
this.#logger.debug(`unhandled event: ${event.type}`);
|
|
1363
|
+
}
|
|
1364
|
+
break;
|
|
1365
|
+
}
|
|
1366
|
+
} catch (error) {
|
|
1367
|
+
if (isAPIError(error) && !error.retryable) {
|
|
1368
|
+
wsCloseFuture.resolve(error);
|
|
1369
|
+
wsConn.close();
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
this.#logger.error({ error, event }, 'Failed to handle OpenAI Realtime API event');
|
|
1292
1373
|
}
|
|
1293
1374
|
};
|
|
1294
1375
|
|
|
@@ -1338,13 +1419,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1338
1419
|
await this.#task;
|
|
1339
1420
|
|
|
1340
1421
|
// Clean up pending futures to prevent memory leaks
|
|
1341
|
-
|
|
1342
|
-
if (!handle.doneFut.done) {
|
|
1343
|
-
handle.doneFut.reject(new Error('Session closed'));
|
|
1344
|
-
}
|
|
1345
|
-
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1346
|
-
}
|
|
1347
|
-
this.responseCreatedFutures = {};
|
|
1422
|
+
this.rejectResponseCreatedFutures('Session closed');
|
|
1348
1423
|
|
|
1349
1424
|
for (const fut of Object.values(this.itemCreateFutures)) {
|
|
1350
1425
|
if (!fut.done) {
|
|
@@ -1363,24 +1438,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1363
1438
|
this.inputTranscriptAccumulators.clear();
|
|
1364
1439
|
|
|
1365
1440
|
// Clean up current generation if exists
|
|
1366
|
-
|
|
1367
|
-
this.currentGeneration = undefined;
|
|
1368
|
-
} else if (this.currentGeneration) {
|
|
1369
|
-
for (const gen of this.currentGeneration.messages.values()) {
|
|
1370
|
-
gen.textChannel.close();
|
|
1371
|
-
gen.audioChannel.close();
|
|
1372
|
-
if (!gen.modalities.done) {
|
|
1373
|
-
gen.modalities.resolve(this._options.modalities);
|
|
1374
|
-
}
|
|
1375
|
-
}
|
|
1376
|
-
this.currentGeneration.messages.clear();
|
|
1377
|
-
this.currentGeneration.messageChannel.close();
|
|
1378
|
-
this.currentGeneration.functionChannel.close();
|
|
1379
|
-
if (!this.currentGeneration._doneFut.done) {
|
|
1380
|
-
this.currentGeneration._doneFut.resolve();
|
|
1381
|
-
}
|
|
1382
|
-
this.currentGeneration = undefined;
|
|
1383
|
-
}
|
|
1441
|
+
this.closeCurrentGeneration('Session closed');
|
|
1384
1442
|
|
|
1385
1443
|
// Clear the message queue
|
|
1386
1444
|
this.messageChannel.items.length = 0;
|
|
@@ -1924,13 +1982,18 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1924
1982
|
const errorTypeValue = errorBody && 'type' in errorBody ? errorBody.type : undefined;
|
|
1925
1983
|
const errorType = typeof errorTypeValue === 'string' ? errorTypeValue : 'unknown';
|
|
1926
1984
|
|
|
1927
|
-
|
|
1928
|
-
|
|
1985
|
+
const recoverable = !isFatalError(errorBody);
|
|
1986
|
+
const error = new APIError(
|
|
1987
|
+
`OpenAI Realtime API response failed with error type: ${errorType}`,
|
|
1988
|
+
{
|
|
1929
1989
|
body: errorBody ?? null,
|
|
1930
|
-
retryable:
|
|
1931
|
-
}
|
|
1932
|
-
|
|
1933
|
-
|
|
1990
|
+
retryable: recoverable,
|
|
1991
|
+
},
|
|
1992
|
+
);
|
|
1993
|
+
if (!recoverable) {
|
|
1994
|
+
throw error;
|
|
1995
|
+
}
|
|
1996
|
+
this.emitError({ error, recoverable: true });
|
|
1934
1997
|
} else if (event.response.status === 'cancelled' || event.response.status === 'incomplete') {
|
|
1935
1998
|
let statusType: string | undefined;
|
|
1936
1999
|
let statusReason: string | undefined;
|
|
@@ -1974,13 +2037,15 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1974
2037
|
}
|
|
1975
2038
|
}
|
|
1976
2039
|
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
}),
|
|
1982
|
-
recoverable: true,
|
|
2040
|
+
const recoverable = !isFatalError(event.error);
|
|
2041
|
+
const error = new APIError(event.error.message, {
|
|
2042
|
+
body: event.error,
|
|
2043
|
+
retryable: recoverable,
|
|
1983
2044
|
});
|
|
2045
|
+
if (!recoverable) {
|
|
2046
|
+
throw error;
|
|
2047
|
+
}
|
|
2048
|
+
this.emitError({ error, recoverable: true });
|
|
1984
2049
|
}
|
|
1985
2050
|
|
|
1986
2051
|
private emitError({ error, recoverable }: { error: Error; recoverable: boolean }): void {
|
package/src/ws/llm.test.ts
CHANGED
|
@@ -12,13 +12,13 @@ initializeLogger({ level: 'silent', pretty: false });
|
|
|
12
12
|
const hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);
|
|
13
13
|
|
|
14
14
|
describe('buildResponsesWsUrl', () => {
|
|
15
|
-
it('points at the OpenAI Responses WS endpoint
|
|
15
|
+
it('points at the OpenAI Responses WS endpoint without model when no baseURL is set', () => {
|
|
16
16
|
const url = new URL(buildResponsesWsUrl(undefined, 'gpt-4.1'));
|
|
17
17
|
|
|
18
18
|
expect(url.protocol).toBe('wss:');
|
|
19
19
|
expect(url.host).toBe('api.openai.com');
|
|
20
20
|
expect(url.pathname).toBe('/v1/responses');
|
|
21
|
-
expect(url.searchParams.get('model')).toBe(
|
|
21
|
+
expect(url.searchParams.get('model')).toBe(null);
|
|
22
22
|
});
|
|
23
23
|
|
|
24
24
|
it('rewrites https baseURL to wss and appends /responses with the model', () => {
|
|
@@ -30,6 +30,32 @@ describe('buildResponsesWsUrl', () => {
|
|
|
30
30
|
expect(url.searchParams.get('model')).toBe('gpt-4o');
|
|
31
31
|
});
|
|
32
32
|
|
|
33
|
+
it('rewrites full https Responses endpoint to wss without duplicating /responses', () => {
|
|
34
|
+
const url = new URL(buildResponsesWsUrl('https://gateway.example.com/v1/responses', 'gpt-4o'));
|
|
35
|
+
|
|
36
|
+
expect(url.protocol).toBe('wss:');
|
|
37
|
+
expect(url.host).toBe('gateway.example.com');
|
|
38
|
+
expect(url.pathname).toBe('/v1/responses');
|
|
39
|
+
expect(url.searchParams.get('model')).toBe('gpt-4o');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('uses full wss Responses endpoint with the model', () => {
|
|
43
|
+
const url = new URL(buildResponsesWsUrl('wss://gateway.example.com/v1/responses', 'gpt-4o'));
|
|
44
|
+
|
|
45
|
+
expect(url.protocol).toBe('wss:');
|
|
46
|
+
expect(url.host).toBe('gateway.example.com');
|
|
47
|
+
expect(url.pathname).toBe('/v1/responses');
|
|
48
|
+
expect(url.searchParams.get('model')).toBe('gpt-4o');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('omits the model when an explicit baseURL still points at api.openai.com', () => {
|
|
52
|
+
const url = new URL(buildResponsesWsUrl('https://api.openai.com/v1', 'gpt-4.1'));
|
|
53
|
+
|
|
54
|
+
expect(url.host).toBe('api.openai.com');
|
|
55
|
+
expect(url.pathname).toBe('/v1/responses');
|
|
56
|
+
expect(url.searchParams.get('model')).toBe(null);
|
|
57
|
+
});
|
|
58
|
+
|
|
33
59
|
it('strips a trailing slash on baseURL before appending /responses', () => {
|
|
34
60
|
const url = new URL(buildResponsesWsUrl('https://gateway.example.com/v1/', 'gpt-4o-mini'));
|
|
35
61
|
|
package/src/ws/llm.ts
CHANGED
|
@@ -36,12 +36,11 @@ const WS_MAX_SESSION_DURATION = 3_600_000;
|
|
|
36
36
|
/**
|
|
37
37
|
* Build the Responses-API WebSocket URL.
|
|
38
38
|
*
|
|
39
|
-
* Includes the model on the upgrade URL
|
|
39
|
+
* Includes the model on the upgrade URL for OpenAI-compatible gateways
|
|
40
40
|
* (which can only see the URL at the WebSocket upgrade, not the subsequent
|
|
41
|
-
* `response.create` frame) can route by model.
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* parameter, so this is a no-op for direct connections.
|
|
41
|
+
* `response.create` frame) so they can route by model. OpenAI's native
|
|
42
|
+
* endpoint gets the model in the `response.create` frame, so the query
|
|
43
|
+
* parameter is intentionally omitted for direct connections.
|
|
45
44
|
*
|
|
46
45
|
* The scheme of `baseURL` is respected: `http://` maps to `ws://`
|
|
47
46
|
* and `https://` maps to `wss://`.
|
|
@@ -49,11 +48,16 @@ const WS_MAX_SESSION_DURATION = 3_600_000;
|
|
|
49
48
|
* @internal
|
|
50
49
|
*/
|
|
51
50
|
export function buildResponsesWsUrl(baseURL: string | undefined, model: string): string {
|
|
52
|
-
const
|
|
53
|
-
|
|
51
|
+
const normalizedBaseURL = baseURL?.replace(/^http(s?):/, 'ws$1:').replace(/\/+$/, '');
|
|
52
|
+
const base = normalizedBaseURL
|
|
53
|
+
? normalizedBaseURL.endsWith('/responses')
|
|
54
|
+
? normalizedBaseURL
|
|
55
|
+
: `${normalizedBaseURL}/responses`
|
|
54
56
|
: OPENAI_RESPONSES_WS_URL;
|
|
55
57
|
const url = new URL(base);
|
|
56
|
-
url.
|
|
58
|
+
if (url.hostname !== 'api.openai.com') {
|
|
59
|
+
url.searchParams.set('model', model);
|
|
60
|
+
}
|
|
57
61
|
return url.toString();
|
|
58
62
|
}
|
|
59
63
|
|
|
@@ -330,6 +334,7 @@ export class WSLLM extends llm.LLM {
|
|
|
330
334
|
|
|
331
335
|
if (
|
|
332
336
|
diff.toRemove.length === 0 &&
|
|
337
|
+
diff.toUpdate.length === 0 &&
|
|
333
338
|
diff.toCreate.length > 0 &&
|
|
334
339
|
diff.toCreate[0]![0] === lastPrevItemId
|
|
335
340
|
) {
|