@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.
- package/dist/index.cjs +4 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/llm.cjs +8 -2
- package/dist/llm.cjs.map +1 -1
- package/dist/llm.d.cts +4 -3
- package/dist/llm.d.ts +4 -3
- package/dist/llm.d.ts.map +1 -1
- package/dist/llm.js +8 -2
- package/dist/llm.js.map +1 -1
- package/dist/models.cjs +12 -3
- package/dist/models.cjs.map +1 -1
- package/dist/models.d.cts +7 -1
- package/dist/models.d.ts +7 -1
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +11 -3
- package/dist/models.js.map +1 -1
- package/dist/realtime/api_proto.cjs.map +1 -1
- package/dist/realtime/api_proto.d.cts +1 -0
- package/dist/realtime/api_proto.d.ts +1 -0
- package/dist/realtime/api_proto.d.ts.map +1 -1
- package/dist/realtime/api_proto.js.map +1 -1
- package/dist/realtime/realtime_model.cjs +85 -27
- package/dist/realtime/realtime_model.cjs.map +1 -1
- package/dist/realtime/realtime_model.d.cts +2 -1
- package/dist/realtime/realtime_model.d.ts +2 -1
- package/dist/realtime/realtime_model.d.ts.map +1 -1
- package/dist/realtime/realtime_model.js +85 -27
- package/dist/realtime/realtime_model.js.map +1 -1
- package/dist/realtime/realtime_model.test.cjs +28 -0
- package/dist/realtime/realtime_model.test.cjs.map +1 -1
- package/dist/realtime/realtime_model.test.js +28 -0
- package/dist/realtime/realtime_model.test.js.map +1 -1
- package/dist/responses/llm.cjs +15 -18
- package/dist/responses/llm.cjs.map +1 -1
- package/dist/responses/llm.d.cts +4 -2
- package/dist/responses/llm.d.ts +4 -2
- package/dist/responses/llm.d.ts.map +1 -1
- package/dist/responses/llm.js +15 -18
- package/dist/responses/llm.js.map +1 -1
- package/dist/tool_utils.cjs +53 -0
- package/dist/tool_utils.cjs.map +1 -0
- package/dist/tool_utils.d.cts +4 -0
- package/dist/tool_utils.d.ts +4 -0
- package/dist/tool_utils.d.ts.map +1 -0
- package/dist/tool_utils.js +29 -0
- package/dist/tool_utils.js.map +1 -0
- package/dist/tool_utils.test.cjs +77 -0
- package/dist/tool_utils.test.cjs.map +1 -0
- package/dist/tool_utils.test.d.cts +2 -0
- package/dist/tool_utils.test.d.ts +2 -0
- package/dist/tool_utils.test.d.ts.map +1 -0
- package/dist/tool_utils.test.js +76 -0
- package/dist/tool_utils.test.js.map +1 -0
- package/dist/tools.cjs +117 -0
- package/dist/tools.cjs.map +1 -0
- package/dist/tools.d.cts +88 -0
- package/dist/tools.d.ts +88 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +90 -0
- package/dist/tools.js.map +1 -0
- package/dist/ws/llm.cjs +15 -18
- package/dist/ws/llm.cjs.map +1 -1
- package/dist/ws/llm.d.cts +5 -3
- package/dist/ws/llm.d.ts +5 -3
- package/dist/ws/llm.d.ts.map +1 -1
- package/dist/ws/llm.js +15 -18
- package/dist/ws/llm.js.map +1 -1
- package/package.json +7 -7
- package/src/index.ts +1 -0
- package/src/llm.ts +16 -3
- package/src/models.ts +18 -3
- package/src/realtime/api_proto.ts +1 -0
- package/src/realtime/realtime_model.test.ts +38 -0
- package/src/realtime/realtime_model.ts +104 -28
- package/src/responses/llm.ts +27 -23
- package/src/tool_utils.test.ts +84 -0
- package/src/tool_utils.ts +46 -0
- package/src/tools.ts +166 -0
- package/src/ws/llm.ts +25 -24
|
@@ -13,9 +13,15 @@ import {
|
|
|
13
13
|
|
|
14
14
|
type RealtimeSessionInternals = {
|
|
15
15
|
generateReply: RealtimeSession['generateReply'];
|
|
16
|
+
updateInstructions: RealtimeSession['updateInstructions'];
|
|
16
17
|
responseCreatedFutures: Record<string, unknown>;
|
|
17
18
|
sendEvent: ReturnType<typeof vi.fn>;
|
|
18
19
|
textModeRecoveryRetries: number;
|
|
20
|
+
instructions?: string;
|
|
21
|
+
_options: {
|
|
22
|
+
isAzure?: boolean;
|
|
23
|
+
apiVersion?: string;
|
|
24
|
+
};
|
|
19
25
|
};
|
|
20
26
|
|
|
21
27
|
type ResponseDoneSessionInternals = {
|
|
@@ -36,6 +42,7 @@ function createSessionForTest(): RealtimeSessionInternals {
|
|
|
36
42
|
session.responseCreatedFutures = {};
|
|
37
43
|
session.sendEvent = vi.fn();
|
|
38
44
|
session.textModeRecoveryRetries = 0;
|
|
45
|
+
session._options = {};
|
|
39
46
|
return session;
|
|
40
47
|
}
|
|
41
48
|
|
|
@@ -49,6 +56,37 @@ function stubTaskRuntime(): void {
|
|
|
49
56
|
}
|
|
50
57
|
|
|
51
58
|
describe('RealtimeSession.generateReply', () => {
|
|
59
|
+
it('preserves session instructions when generating with per-response instructions', async () => {
|
|
60
|
+
const session = createSessionForTest();
|
|
61
|
+
await session.updateInstructions('Your name is Kelly. Always respond in English.');
|
|
62
|
+
|
|
63
|
+
const abortController = new AbortController();
|
|
64
|
+
const promise = session.generateReply('Tell the user what your name is.', {
|
|
65
|
+
signal: abortController.signal,
|
|
66
|
+
});
|
|
67
|
+
abortController.abort();
|
|
68
|
+
|
|
69
|
+
await expect(promise).rejects.toThrow('generateReply aborted');
|
|
70
|
+
expect(session.instructions).toBe('Your name is Kelly. Always respond in English.');
|
|
71
|
+
expect(session.sendEvent).toHaveBeenCalledWith(
|
|
72
|
+
expect.objectContaining({
|
|
73
|
+
type: 'session.update',
|
|
74
|
+
session: expect.objectContaining({
|
|
75
|
+
instructions: 'Your name is Kelly. Always respond in English.',
|
|
76
|
+
}),
|
|
77
|
+
}),
|
|
78
|
+
);
|
|
79
|
+
expect(session.sendEvent).toHaveBeenCalledWith(
|
|
80
|
+
expect.objectContaining({
|
|
81
|
+
type: 'response.create',
|
|
82
|
+
response: expect.objectContaining({
|
|
83
|
+
instructions:
|
|
84
|
+
'Your name is Kelly. Always respond in English.\nTell the user what your name is.',
|
|
85
|
+
}),
|
|
86
|
+
}),
|
|
87
|
+
);
|
|
88
|
+
});
|
|
89
|
+
|
|
52
90
|
it('cancels an in-flight response when aborted before response.created', async () => {
|
|
53
91
|
const session = createSessionForTest();
|
|
54
92
|
const abortController = new AbortController();
|
|
@@ -82,10 +82,14 @@ interface ResponseGeneration {
|
|
|
82
82
|
_firstTokenTimestamp?: number;
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
class DiscardedGeneration {
|
|
86
|
+
readonly discarded = true;
|
|
87
|
+
}
|
|
88
|
+
|
|
85
89
|
class CreateResponseHandle {
|
|
86
90
|
instructions?: string;
|
|
87
91
|
doneFut: Future<llm.GenerationCreatedEvent>;
|
|
88
|
-
|
|
92
|
+
timeout?: ReturnType<typeof setTimeout>;
|
|
89
93
|
constructor({ instructions }: { instructions?: string }) {
|
|
90
94
|
this.instructions = instructions;
|
|
91
95
|
this.doneFut = new Future();
|
|
@@ -425,7 +429,7 @@ export function processBaseURL({
|
|
|
425
429
|
* - openai_client_event_queued: expose the raw client events sent to the OpenAI Realtime API
|
|
426
430
|
*/
|
|
427
431
|
export class RealtimeSession extends llm.RealtimeSession {
|
|
428
|
-
private _tools: llm.ToolContext =
|
|
432
|
+
private _tools: llm.ToolContext = llm.ToolContext.empty();
|
|
429
433
|
private remoteChatCtx: llm.RemoteChatContext = new llm.RemoteChatContext();
|
|
430
434
|
private messageChannel = new Queue<api_proto.ClientEvent>();
|
|
431
435
|
private inputResampler?: AudioResampler;
|
|
@@ -435,8 +439,9 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
435
439
|
// per-session copy of options so updateOptions can diff against the session's
|
|
436
440
|
// own state instead of the shared model-level state.
|
|
437
441
|
private _options: RealtimeOptions;
|
|
438
|
-
private currentGeneration?: ResponseGeneration;
|
|
442
|
+
private currentGeneration?: ResponseGeneration | DiscardedGeneration;
|
|
439
443
|
private responseCreatedFutures: { [id: string]: CreateResponseHandle } = {};
|
|
444
|
+
private discardedEventIds = new Set<string>();
|
|
440
445
|
|
|
441
446
|
private textModeRecoveryRetries: number = 0;
|
|
442
447
|
|
|
@@ -552,7 +557,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
552
557
|
}
|
|
553
558
|
|
|
554
559
|
get tools() {
|
|
555
|
-
return
|
|
560
|
+
return this._tools.copy();
|
|
556
561
|
}
|
|
557
562
|
|
|
558
563
|
async updateChatCtx(_chatCtx: llm.ChatContext): Promise<void> {
|
|
@@ -719,13 +724,12 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
719
724
|
|
|
720
725
|
// TODO(brian): these logics below are noops I think; remove them later.
|
|
721
726
|
const retainedToolNames = new Set(ev.session.tools.map((tool) => tool.name));
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
),
|
|
727
|
+
// Keep provider tools and Toolsets as-is; only drop function tools the server didn't accept.
|
|
728
|
+
const retainedEntries = _tools.tools.filter(
|
|
729
|
+
(entry) => !llm.isFunctionTool(entry) || retainedToolNames.has(entry.name),
|
|
726
730
|
);
|
|
727
731
|
|
|
728
|
-
this._tools =
|
|
732
|
+
this._tools = new llm.ToolContext(retainedEntries);
|
|
729
733
|
|
|
730
734
|
unlock();
|
|
731
735
|
}
|
|
@@ -733,26 +737,26 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
733
737
|
private createToolsUpdateEvent(_tools: llm.ToolContext): api_proto.SessionUpdateEvent {
|
|
734
738
|
const oaiTools: api_proto.Tool[] = [];
|
|
735
739
|
|
|
736
|
-
for (const
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
continue;
|
|
740
|
-
}
|
|
740
|
+
for (const t of _tools.flatten()) {
|
|
741
|
+
// TODO: support provider tools in the Realtime session-update schema.
|
|
742
|
+
if (!llm.isFunctionTool(t)) continue;
|
|
741
743
|
|
|
742
|
-
const { parameters: toolParameters, description } = tool;
|
|
743
744
|
try {
|
|
744
745
|
const parameters = llm.toJsonSchema(
|
|
745
|
-
|
|
746
|
+
t.parameters,
|
|
746
747
|
) as unknown as api_proto.Tool['parameters'];
|
|
747
748
|
|
|
748
749
|
oaiTools.push({
|
|
749
|
-
name,
|
|
750
|
-
description,
|
|
750
|
+
name: t.name,
|
|
751
|
+
description: t.description,
|
|
751
752
|
parameters: parameters,
|
|
752
753
|
type: 'function',
|
|
753
754
|
});
|
|
754
755
|
} catch (e) {
|
|
755
|
-
this.#logger.error(
|
|
756
|
+
this.#logger.error(
|
|
757
|
+
{ name: t.name, tool: t },
|
|
758
|
+
"OpenAI Realtime API doesn't support this tool type",
|
|
759
|
+
);
|
|
756
760
|
continue;
|
|
757
761
|
}
|
|
758
762
|
}
|
|
@@ -842,7 +846,18 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
842
846
|
instructions?: string,
|
|
843
847
|
options: { signal?: AbortSignal } = {},
|
|
844
848
|
): Promise<llm.GenerationCreatedEvent> {
|
|
845
|
-
|
|
849
|
+
// In OpenAI realtime, the session-level instructions are completely replaced by the
|
|
850
|
+
// per-response instructions for this response. Prepend the session instructions so they
|
|
851
|
+
// are preserved (parity with the Python implementation).
|
|
852
|
+
let responseInstructions = instructions;
|
|
853
|
+
if (instructions && this.instructions) {
|
|
854
|
+
responseInstructions = `${this.instructions}\n${instructions}`;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
const handle = this.createResponse({
|
|
858
|
+
instructions: responseInstructions,
|
|
859
|
+
userInitiated: true,
|
|
860
|
+
});
|
|
846
861
|
this.textModeRecoveryRetries = 0;
|
|
847
862
|
|
|
848
863
|
const onAbort = () => {
|
|
@@ -851,7 +866,9 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
851
866
|
)?.[0];
|
|
852
867
|
if (eventId) {
|
|
853
868
|
delete this.responseCreatedFutures[eventId];
|
|
869
|
+
this.discardedEventIds.add(eventId);
|
|
854
870
|
}
|
|
871
|
+
if (handle.timeout) clearTimeout(handle.timeout);
|
|
855
872
|
if (!handle.doneFut.done) {
|
|
856
873
|
handle.doneFut.reject(new Error('generateReply aborted'));
|
|
857
874
|
this.sendEvent({
|
|
@@ -1043,8 +1060,10 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1043
1060
|
if (!handle.doneFut.done) {
|
|
1044
1061
|
handle.doneFut.reject(new Error('Session reconnected'));
|
|
1045
1062
|
}
|
|
1063
|
+
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1046
1064
|
}
|
|
1047
1065
|
this.responseCreatedFutures = {};
|
|
1066
|
+
this.discardedEventIds.clear();
|
|
1048
1067
|
|
|
1049
1068
|
// Clear audio-capable item tracking - restored items are text-only on the server
|
|
1050
1069
|
this.audioCapableItemIds.clear();
|
|
@@ -1056,7 +1075,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1056
1075
|
events.push(this.createSessionUpdateEvent());
|
|
1057
1076
|
|
|
1058
1077
|
// tools
|
|
1059
|
-
if (Object.keys(this._tools).length > 0) {
|
|
1078
|
+
if (Object.keys(this._tools.functionTools).length > 0) {
|
|
1060
1079
|
events.push(this.createToolsUpdateEvent(this._tools));
|
|
1061
1080
|
}
|
|
1062
1081
|
|
|
@@ -1295,8 +1314,13 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1295
1314
|
try {
|
|
1296
1315
|
const result = await Promise.race([wsTask.result, sendTask.result, waitReconnectTask.result]);
|
|
1297
1316
|
|
|
1298
|
-
|
|
1299
|
-
|
|
1317
|
+
const currentGeneration = this.currentGeneration;
|
|
1318
|
+
if (waitReconnectTask.done && currentGeneration) {
|
|
1319
|
+
if (currentGeneration instanceof DiscardedGeneration) {
|
|
1320
|
+
this.currentGeneration = undefined;
|
|
1321
|
+
} else {
|
|
1322
|
+
await currentGeneration._doneFut.await;
|
|
1323
|
+
}
|
|
1300
1324
|
}
|
|
1301
1325
|
|
|
1302
1326
|
if (result instanceof Error) {
|
|
@@ -1318,6 +1342,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1318
1342
|
if (!handle.doneFut.done) {
|
|
1319
1343
|
handle.doneFut.reject(new Error('Session closed'));
|
|
1320
1344
|
}
|
|
1345
|
+
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1321
1346
|
}
|
|
1322
1347
|
this.responseCreatedFutures = {};
|
|
1323
1348
|
|
|
@@ -1338,7 +1363,9 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1338
1363
|
this.inputTranscriptAccumulators.clear();
|
|
1339
1364
|
|
|
1340
1365
|
// Clean up current generation if exists
|
|
1341
|
-
if (this.currentGeneration) {
|
|
1366
|
+
if (this.currentGeneration instanceof DiscardedGeneration) {
|
|
1367
|
+
this.currentGeneration = undefined;
|
|
1368
|
+
} else if (this.currentGeneration) {
|
|
1342
1369
|
for (const gen of this.currentGeneration.messages.values()) {
|
|
1343
1370
|
gen.textChannel.close();
|
|
1344
1371
|
gen.audioChannel.close();
|
|
@@ -1378,28 +1405,41 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1378
1405
|
throw new Error('response.id is missing');
|
|
1379
1406
|
}
|
|
1380
1407
|
|
|
1381
|
-
|
|
1408
|
+
const clientEventId = event.response.metadata?.client_event_id;
|
|
1409
|
+
if (clientEventId && this.discardedEventIds.has(clientEventId)) {
|
|
1410
|
+
this.discardedEventIds.delete(clientEventId);
|
|
1411
|
+
this.sendEvent({
|
|
1412
|
+
type: 'response.cancel',
|
|
1413
|
+
response_id: event.response.id,
|
|
1414
|
+
} as api_proto.ResponseCancelEvent);
|
|
1415
|
+
this.currentGeneration = new DiscardedGeneration();
|
|
1416
|
+
this.#logger.warn('discarding response that arrived after it was timed out or interrupted');
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
const currentGeneration: ResponseGeneration = {
|
|
1382
1421
|
messageChannel: stream.createStreamChannel<llm.MessageGeneration>(),
|
|
1383
1422
|
functionChannel: stream.createStreamChannel<llm.FunctionCall>(),
|
|
1384
1423
|
messages: new Map(),
|
|
1385
1424
|
_doneFut: new Future(),
|
|
1386
1425
|
_createdTimestamp: Date.now(),
|
|
1387
1426
|
};
|
|
1427
|
+
this.currentGeneration = currentGeneration;
|
|
1388
1428
|
|
|
1389
1429
|
// Build generation event and resolve client future (if any) before emitting,
|
|
1390
1430
|
// matching Python behavior.
|
|
1391
1431
|
const generationEv = {
|
|
1392
|
-
messageStream:
|
|
1393
|
-
functionStream:
|
|
1432
|
+
messageStream: currentGeneration.messageChannel.stream(),
|
|
1433
|
+
functionStream: currentGeneration.functionChannel.stream(),
|
|
1394
1434
|
userInitiated: false,
|
|
1395
1435
|
responseId: event.response.id,
|
|
1396
1436
|
} as llm.GenerationCreatedEvent;
|
|
1397
1437
|
|
|
1398
|
-
const clientEventId = event.response.metadata?.client_event_id;
|
|
1399
1438
|
if (clientEventId) {
|
|
1400
1439
|
const handle = this.responseCreatedFutures[clientEventId];
|
|
1401
1440
|
if (handle) {
|
|
1402
1441
|
delete this.responseCreatedFutures[clientEventId];
|
|
1442
|
+
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1403
1443
|
generationEv.userInitiated = true;
|
|
1404
1444
|
if (!handle.doneFut.done) {
|
|
1405
1445
|
handle.doneFut.resolve(generationEv);
|
|
@@ -1411,6 +1451,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1411
1451
|
}
|
|
1412
1452
|
|
|
1413
1453
|
private handleResponseOutputItemAdded(event: api_proto.ResponseOutputItemAddedEvent): void {
|
|
1454
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1455
|
+
|
|
1414
1456
|
if (!this.currentGeneration) {
|
|
1415
1457
|
throw new Error('currentGeneration is not set');
|
|
1416
1458
|
}
|
|
@@ -1583,6 +1625,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1583
1625
|
}
|
|
1584
1626
|
|
|
1585
1627
|
private handleResponseContentPartAdded(event: api_proto.ResponseContentPartAddedEvent): void {
|
|
1628
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1629
|
+
|
|
1586
1630
|
if (!this.currentGeneration) {
|
|
1587
1631
|
throw new Error('currentGeneration is not set');
|
|
1588
1632
|
}
|
|
@@ -1617,6 +1661,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1617
1661
|
}
|
|
1618
1662
|
|
|
1619
1663
|
private handleResponseContentPartDone(event: api_proto.ResponseContentPartDoneEvent): void {
|
|
1664
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1665
|
+
|
|
1620
1666
|
if (!event.part) {
|
|
1621
1667
|
return;
|
|
1622
1668
|
}
|
|
@@ -1632,6 +1678,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1632
1678
|
}
|
|
1633
1679
|
|
|
1634
1680
|
private handleResponseTextDelta(event: api_proto.ResponseTextDeltaEvent): void {
|
|
1681
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1682
|
+
|
|
1635
1683
|
if (!this.currentGeneration) {
|
|
1636
1684
|
throw new Error('currentGeneration is not set');
|
|
1637
1685
|
}
|
|
@@ -1653,6 +1701,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1653
1701
|
}
|
|
1654
1702
|
|
|
1655
1703
|
private handleResponseTextDone(_event: api_proto.ResponseTextDoneEvent): void {
|
|
1704
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1705
|
+
|
|
1656
1706
|
if (!this.currentGeneration) {
|
|
1657
1707
|
throw new Error('currentGeneration is not set');
|
|
1658
1708
|
}
|
|
@@ -1661,6 +1711,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1661
1711
|
private handleResponseAudioTranscriptDelta(
|
|
1662
1712
|
event: api_proto.ResponseAudioTranscriptDeltaEvent,
|
|
1663
1713
|
): void {
|
|
1714
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1715
|
+
|
|
1664
1716
|
if (!this.currentGeneration) {
|
|
1665
1717
|
throw new Error('currentGeneration is not set');
|
|
1666
1718
|
}
|
|
@@ -1683,6 +1735,8 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1683
1735
|
}
|
|
1684
1736
|
|
|
1685
1737
|
private handleResponseAudioDelta(event: api_proto.ResponseAudioDeltaEvent): void {
|
|
1738
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1739
|
+
|
|
1686
1740
|
if (!this.currentGeneration) {
|
|
1687
1741
|
throw new Error('currentGeneration is not set');
|
|
1688
1742
|
}
|
|
@@ -1720,18 +1774,24 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1720
1774
|
private handleResponseAudioTranscriptDone(
|
|
1721
1775
|
_event: api_proto.ResponseAudioTranscriptDoneEvent,
|
|
1722
1776
|
): void {
|
|
1777
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1778
|
+
|
|
1723
1779
|
if (!this.currentGeneration) {
|
|
1724
1780
|
throw new Error('currentGeneration is not set');
|
|
1725
1781
|
}
|
|
1726
1782
|
}
|
|
1727
1783
|
|
|
1728
1784
|
private handleResponseAudioDone(_event: api_proto.ResponseAudioDoneEvent): void {
|
|
1785
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1786
|
+
|
|
1729
1787
|
if (!this.currentGeneration) {
|
|
1730
1788
|
throw new Error('currentGeneration is not set');
|
|
1731
1789
|
}
|
|
1732
1790
|
}
|
|
1733
1791
|
|
|
1734
1792
|
private handleResponseOutputItemDone(event: api_proto.ResponseOutputItemDoneEvent): void {
|
|
1793
|
+
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1794
|
+
|
|
1735
1795
|
if (!this.currentGeneration) {
|
|
1736
1796
|
throw new Error('currentGeneration is not set');
|
|
1737
1797
|
}
|
|
@@ -1767,6 +1827,11 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1767
1827
|
}
|
|
1768
1828
|
|
|
1769
1829
|
private handleResponseDone(_event: api_proto.ResponseDoneEvent): void {
|
|
1830
|
+
if (this.currentGeneration instanceof DiscardedGeneration) {
|
|
1831
|
+
this.currentGeneration = undefined;
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1770
1835
|
if (!this.currentGeneration) {
|
|
1771
1836
|
// OpenAI has a race condition where we could receive response.done without any
|
|
1772
1837
|
// previous response.created (This happens generally during interruption)
|
|
@@ -1902,6 +1967,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1902
1967
|
const handle = this.responseCreatedFutures[eventId];
|
|
1903
1968
|
if (handle) {
|
|
1904
1969
|
delete this.responseCreatedFutures[eventId];
|
|
1970
|
+
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1905
1971
|
if (!handle.doneFut.done) {
|
|
1906
1972
|
handle.doneFut.reject(new Error(event.error.message));
|
|
1907
1973
|
}
|
|
@@ -1948,8 +2014,18 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1948
2014
|
}
|
|
1949
2015
|
|
|
1950
2016
|
const eventId = shortuuid('response_create_');
|
|
2017
|
+
this.discardedEventIds ??= new Set<string>();
|
|
1951
2018
|
if (userInitiated) {
|
|
1952
2019
|
this.responseCreatedFutures[eventId] = handle;
|
|
2020
|
+
handle.timeout = setTimeout(() => {
|
|
2021
|
+
if (this.responseCreatedFutures[eventId] === handle) {
|
|
2022
|
+
delete this.responseCreatedFutures[eventId];
|
|
2023
|
+
}
|
|
2024
|
+
if (!handle.doneFut.done) {
|
|
2025
|
+
this.discardedEventIds.add(eventId);
|
|
2026
|
+
handle.doneFut.reject(new Error('generateReply timed out.'));
|
|
2027
|
+
}
|
|
2028
|
+
}, 10000);
|
|
1953
2029
|
}
|
|
1954
2030
|
|
|
1955
2031
|
const response: api_proto.ResponseCreateEvent['response'] = {};
|
package/src/responses/llm.ts
CHANGED
|
@@ -12,7 +12,9 @@ import {
|
|
|
12
12
|
toError,
|
|
13
13
|
} from '@livekit/agents';
|
|
14
14
|
import OpenAI from 'openai';
|
|
15
|
-
import type { ChatModels } from '../models.js';
|
|
15
|
+
import type { ChatModels, Reasoning } from '../models.js';
|
|
16
|
+
import { defaultReasoningEffort } from '../models.js';
|
|
17
|
+
import { toResponsesTools } from '../tool_utils.js';
|
|
16
18
|
import { WSLLM } from '../ws/llm.js';
|
|
17
19
|
|
|
18
20
|
export interface LLMOptions {
|
|
@@ -30,6 +32,8 @@ export interface LLMOptions {
|
|
|
30
32
|
serviceTier?: string;
|
|
31
33
|
/** Upper bound for the number of tokens that can be generated for a response. */
|
|
32
34
|
maxOutputTokens?: number;
|
|
35
|
+
/** Configuration options for reasoning models. */
|
|
36
|
+
reasoning?: Reasoning | null;
|
|
33
37
|
|
|
34
38
|
/**
|
|
35
39
|
* Whether to use the WebSocket API.
|
|
@@ -55,6 +59,13 @@ class ResponsesHttpLLM extends llm.LLM {
|
|
|
55
59
|
super();
|
|
56
60
|
|
|
57
61
|
this.#opts = { ...defaultLLMOptions, ...opts };
|
|
62
|
+
if (this.#opts.reasoning === undefined) {
|
|
63
|
+
const effort = defaultReasoningEffort(this.#opts.model);
|
|
64
|
+
if (effort !== undefined) {
|
|
65
|
+
this.#opts.reasoning = { effort };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
58
69
|
if (this.#opts.apiKey === undefined && this.#opts.client === undefined) {
|
|
59
70
|
throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');
|
|
60
71
|
}
|
|
@@ -77,25 +88,30 @@ class ResponsesHttpLLM extends llm.LLM {
|
|
|
77
88
|
|
|
78
89
|
override chat({
|
|
79
90
|
chatCtx,
|
|
80
|
-
toolCtx,
|
|
91
|
+
toolCtx: toolCtxInput,
|
|
81
92
|
connOptions = DEFAULT_API_CONNECT_OPTIONS,
|
|
82
93
|
parallelToolCalls,
|
|
83
94
|
toolChoice,
|
|
84
95
|
extraKwargs,
|
|
85
96
|
}: {
|
|
86
97
|
chatCtx: llm.ChatContext;
|
|
87
|
-
toolCtx?: llm.
|
|
98
|
+
toolCtx?: llm.ToolContextLike;
|
|
88
99
|
connOptions?: APIConnectOptions;
|
|
89
100
|
parallelToolCalls?: boolean;
|
|
90
101
|
toolChoice?: llm.ToolChoice;
|
|
91
102
|
extraKwargs?: Record<string, unknown>;
|
|
92
103
|
}): ResponsesHttpLLMStream {
|
|
104
|
+
const toolCtx = llm.toToolContext(toolCtxInput);
|
|
93
105
|
const modelOptions: Record<string, unknown> = { ...(extraKwargs || {}) };
|
|
94
106
|
|
|
95
107
|
parallelToolCalls =
|
|
96
108
|
parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;
|
|
97
109
|
|
|
98
|
-
if (
|
|
110
|
+
if (
|
|
111
|
+
toolCtx &&
|
|
112
|
+
Object.keys(toolCtx.functionTools).length > 0 &&
|
|
113
|
+
parallelToolCalls !== undefined
|
|
114
|
+
) {
|
|
99
115
|
modelOptions.parallel_tool_calls = parallelToolCalls;
|
|
100
116
|
}
|
|
101
117
|
|
|
@@ -126,6 +142,10 @@ class ResponsesHttpLLM extends llm.LLM {
|
|
|
126
142
|
modelOptions.max_output_tokens = this.#opts.maxOutputTokens;
|
|
127
143
|
}
|
|
128
144
|
|
|
145
|
+
if (this.#opts.reasoning !== undefined) {
|
|
146
|
+
modelOptions.reasoning = this.#opts.reasoning;
|
|
147
|
+
}
|
|
148
|
+
|
|
129
149
|
return new ResponsesHttpLLMStream(this, {
|
|
130
150
|
model: this.#opts.model,
|
|
131
151
|
client: this.#client,
|
|
@@ -181,25 +201,9 @@ class ResponsesHttpLLMStream extends llm.LLMStream {
|
|
|
181
201
|
'openai.responses',
|
|
182
202
|
)) as OpenAI.Responses.ResponseInputItem[];
|
|
183
203
|
|
|
204
|
+
// TODO: support provider tools in the Responses schema.
|
|
184
205
|
const tools = this.toolCtx
|
|
185
|
-
?
|
|
186
|
-
const oaiParams = {
|
|
187
|
-
type: 'function' as const,
|
|
188
|
-
name: name,
|
|
189
|
-
description: func.description,
|
|
190
|
-
parameters: llm.toJsonSchema(
|
|
191
|
-
func.parameters,
|
|
192
|
-
true,
|
|
193
|
-
this.strictToolSchema,
|
|
194
|
-
) as unknown as OpenAI.Responses.FunctionTool['parameters'],
|
|
195
|
-
} as OpenAI.Responses.FunctionTool;
|
|
196
|
-
|
|
197
|
-
if (this.strictToolSchema) {
|
|
198
|
-
oaiParams.strict = true;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
return oaiParams;
|
|
202
|
-
})
|
|
206
|
+
? toResponsesTools(this.toolCtx, this.strictToolSchema)
|
|
203
207
|
: undefined;
|
|
204
208
|
|
|
205
209
|
const requestOptions: Record<string, unknown> = { ...this.modelOptions };
|
|
@@ -430,7 +434,7 @@ export class LLM extends llm.LLM {
|
|
|
430
434
|
extraKwargs,
|
|
431
435
|
}: {
|
|
432
436
|
chatCtx: llm.ChatContext;
|
|
433
|
-
toolCtx?: llm.
|
|
437
|
+
toolCtx?: llm.ToolContextLike;
|
|
434
438
|
connOptions?: APIConnectOptions;
|
|
435
439
|
parallelToolCalls?: boolean;
|
|
436
440
|
toolChoice?: llm.ToolChoice;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import { llm } from '@livekit/agents';
|
|
5
|
+
import { describe, expect, it } from 'vitest';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { toResponsesTools } from './tool_utils.js';
|
|
8
|
+
import { CodeInterpreter, FileSearch, WebSearch } from './tools.js';
|
|
9
|
+
|
|
10
|
+
describe('toResponsesTools', () => {
|
|
11
|
+
it('serializes function tools', () => {
|
|
12
|
+
const fn = llm.tool({
|
|
13
|
+
name: 'lookup_weather',
|
|
14
|
+
description: 'Look up weather',
|
|
15
|
+
parameters: z.object({ city: z.string() }),
|
|
16
|
+
execute: async () => 'sunny',
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
expect(toResponsesTools(new llm.ToolContext([fn]), true)).toEqual([
|
|
20
|
+
{
|
|
21
|
+
type: 'function',
|
|
22
|
+
name: 'lookup_weather',
|
|
23
|
+
description: 'Look up weather',
|
|
24
|
+
parameters: {
|
|
25
|
+
$schema: 'http://json-schema.org/draft-07/schema#',
|
|
26
|
+
type: 'object',
|
|
27
|
+
properties: { city: { type: 'string' } },
|
|
28
|
+
required: ['city'],
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
},
|
|
31
|
+
strict: true,
|
|
32
|
+
},
|
|
33
|
+
]);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('serializes OpenAI provider tools', () => {
|
|
37
|
+
const tools = toResponsesTools(
|
|
38
|
+
new llm.ToolContext([
|
|
39
|
+
new WebSearch({
|
|
40
|
+
filters: { allowed_domains: ['docs.livekit.io'] },
|
|
41
|
+
searchContextSize: 'low',
|
|
42
|
+
userLocation: { type: 'approximate', country: 'US' },
|
|
43
|
+
}),
|
|
44
|
+
new FileSearch({
|
|
45
|
+
vectorStoreIds: ['vs_123'],
|
|
46
|
+
maxNumResults: 3,
|
|
47
|
+
rankingOptions: { ranker: 'auto' },
|
|
48
|
+
}),
|
|
49
|
+
new CodeInterpreter({ container: { type: 'auto', file_ids: ['file_123'] } }),
|
|
50
|
+
]),
|
|
51
|
+
false,
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
expect(tools).toEqual([
|
|
55
|
+
{
|
|
56
|
+
type: 'web_search',
|
|
57
|
+
search_context_size: 'low',
|
|
58
|
+
filters: { allowed_domains: ['docs.livekit.io'] },
|
|
59
|
+
user_location: { type: 'approximate', country: 'US' },
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
type: 'file_search',
|
|
63
|
+
vector_store_ids: ['vs_123'],
|
|
64
|
+
max_num_results: 3,
|
|
65
|
+
ranking_options: { ranker: 'auto' },
|
|
66
|
+
},
|
|
67
|
+
{ type: 'code_interpreter', container: { type: 'auto', file_ids: ['file_123'] } },
|
|
68
|
+
]);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('omits the code interpreter container when unset', () => {
|
|
72
|
+
expect(toResponsesTools(new llm.ToolContext([new CodeInterpreter()]), false)).toEqual([
|
|
73
|
+
{ type: 'code_interpreter' },
|
|
74
|
+
]);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('ignores non-OpenAI provider tools', () => {
|
|
78
|
+
class OtherProviderTool extends llm.ProviderTool {}
|
|
79
|
+
|
|
80
|
+
expect(
|
|
81
|
+
toResponsesTools(new llm.ToolContext([new OtherProviderTool({ id: 'other' })]), false),
|
|
82
|
+
).toBeUndefined();
|
|
83
|
+
});
|
|
84
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import { llm } from '@livekit/agents';
|
|
5
|
+
import type OpenAI from 'openai';
|
|
6
|
+
import { OpenAITool } from './tools.js';
|
|
7
|
+
|
|
8
|
+
export function toResponsesTools(
|
|
9
|
+
toolCtx: llm.ToolContext,
|
|
10
|
+
strictToolSchema: boolean,
|
|
11
|
+
): OpenAI.Responses.Tool[] | undefined {
|
|
12
|
+
// Function tools are emitted first, sorted by name for deterministic payloads; provider
|
|
13
|
+
// tools follow in registration order.
|
|
14
|
+
const functionTools = llm.sortedToolEntries(toolCtx).map(([name, tool]) => {
|
|
15
|
+
const oaiParams = {
|
|
16
|
+
type: 'function' as const,
|
|
17
|
+
name,
|
|
18
|
+
description: tool.description,
|
|
19
|
+
parameters: llm.toJsonSchema(
|
|
20
|
+
tool.parameters,
|
|
21
|
+
true,
|
|
22
|
+
strictToolSchema,
|
|
23
|
+
) as unknown as OpenAI.Responses.FunctionTool['parameters'],
|
|
24
|
+
} as OpenAI.Responses.FunctionTool;
|
|
25
|
+
|
|
26
|
+
if (strictToolSchema) {
|
|
27
|
+
oaiParams.strict = true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return oaiParams;
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const providerTools = toolCtx
|
|
34
|
+
.flatten()
|
|
35
|
+
.filter((tool) => !llm.isFunctionTool(tool))
|
|
36
|
+
.map((tool) =>
|
|
37
|
+
tool instanceof OpenAITool
|
|
38
|
+
? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)
|
|
39
|
+
: undefined,
|
|
40
|
+
)
|
|
41
|
+
.filter((tool): tool is OpenAI.Responses.Tool => tool !== undefined);
|
|
42
|
+
|
|
43
|
+
const tools = [...functionTools, ...providerTools];
|
|
44
|
+
|
|
45
|
+
return tools.length > 0 ? tools : undefined;
|
|
46
|
+
}
|