@livekit/agents-plugin-openai 1.4.11 → 1.5.1
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 +10 -3
- 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 +10 -3
- 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/realtime_model.cjs +26 -21
- package/dist/realtime/realtime_model.cjs.map +1 -1
- package/dist/realtime/realtime_model.d.cts +2 -2
- package/dist/realtime/realtime_model.d.ts +2 -2
- package/dist/realtime/realtime_model.d.ts.map +1 -1
- package/dist/realtime/realtime_model.js +26 -21
- 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 +16 -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 +16 -18
- package/dist/responses/llm.js.map +1 -1
- package/dist/stt.cjs +23 -9
- package/dist/stt.cjs.map +1 -1
- package/dist/stt.d.ts.map +1 -1
- package/dist/stt.js +23 -9
- package/dist/stt.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/tts.cjs +1 -0
- package/dist/tts.cjs.map +1 -1
- package/dist/tts.d.ts.map +1 -1
- package/dist/tts.js +1 -0
- package/dist/tts.js.map +1 -1
- 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 +18 -4
- package/src/models.ts +18 -3
- package/src/realtime/realtime_model.test.ts +38 -0
- package/src/realtime/realtime_model.ts +31 -21
- package/src/responses/llm.ts +28 -23
- package/src/stt.ts +26 -12
- package/src/tool_utils.test.ts +84 -0
- package/src/tool_utils.ts +46 -0
- package/src/tools.ts +166 -0
- package/src/tts.ts +1 -0
- package/src/ws/llm.ts +25 -24
package/src/models.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
export type ChatModels =
|
|
6
6
|
| 'gpt-5.4'
|
|
7
|
+
| 'gpt-5.4-mini'
|
|
7
8
|
| 'gpt-5.3-chat-latest'
|
|
8
9
|
| 'gpt-5.2'
|
|
9
10
|
| 'gpt-5.2-chat-latest'
|
|
@@ -205,16 +206,30 @@ export type MetaChatModels =
|
|
|
205
206
|
| 'Llama-3.3-70B-Instruct'
|
|
206
207
|
| 'Llama-3.3-8B-Instruct';
|
|
207
208
|
|
|
209
|
+
export type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high';
|
|
210
|
+
|
|
211
|
+
export type Reasoning = { effort?: ReasoningEffort | null; [key: string]: unknown };
|
|
212
|
+
|
|
208
213
|
export function supportsReasoningEffort(model: ChatModels | string): boolean {
|
|
209
214
|
return [
|
|
210
215
|
'gpt-5.4',
|
|
211
|
-
'gpt-5.
|
|
216
|
+
'gpt-5.4-mini',
|
|
212
217
|
'gpt-5.2',
|
|
213
|
-
'gpt-5.2-chat-latest',
|
|
214
218
|
'gpt-5.1',
|
|
215
|
-
'gpt-5.1-chat-latest',
|
|
216
219
|
'gpt-5',
|
|
217
220
|
'gpt-5-mini',
|
|
218
221
|
'gpt-5-nano',
|
|
219
222
|
].includes(model);
|
|
220
223
|
}
|
|
224
|
+
|
|
225
|
+
export function defaultReasoningEffort(model: ChatModels | string): ReasoningEffort | undefined {
|
|
226
|
+
if (!supportsReasoningEffort(model)) {
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (['gpt-5.1', 'gpt-5.2', 'gpt-5.4', 'gpt-5.4-mini'].includes(model)) {
|
|
231
|
+
return 'none';
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return 'minimal';
|
|
235
|
+
}
|
|
@@ -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();
|
|
@@ -248,7 +248,7 @@ export class RealtimeModel extends llm.RealtimeModel {
|
|
|
248
248
|
* @param apiKey - Azure OpenAI API key. If undefined, will attempt to read from the environment variable AZURE_OPENAI_API_KEY.
|
|
249
249
|
* @param entraToken - Azure Entra authentication token. Required if not using API key authentication.
|
|
250
250
|
* @param baseURL - Base URL for the API endpoint. If undefined, constructed from the azure_endpoint.
|
|
251
|
-
* @param voice - Voice setting for audio outputs. Defaults to "
|
|
251
|
+
* @param voice - Voice setting for audio outputs. Defaults to "marin".
|
|
252
252
|
* @param inputAudioTranscription - Options for transcribing input audio. Defaults to @see DEFAULT_INPUT_AUDIO_TRANSCRIPTION.
|
|
253
253
|
* @param inputAudioNoiseReduction - Options for noise reduction. Defaults to undefined.
|
|
254
254
|
* @param turnDetection - Options for server-based voice activity detection (VAD). Defaults to @see DEFAULT_SERVER_VAD_OPTIONS.
|
|
@@ -266,7 +266,7 @@ export class RealtimeModel extends llm.RealtimeModel {
|
|
|
266
266
|
apiKey,
|
|
267
267
|
entraToken,
|
|
268
268
|
baseURL,
|
|
269
|
-
voice = '
|
|
269
|
+
voice = 'marin',
|
|
270
270
|
temperature, // eslint-disable-line @typescript-eslint/no-unused-vars
|
|
271
271
|
inputAudioTranscription = AZURE_DEFAULT_INPUT_AUDIO_TRANSCRIPTION,
|
|
272
272
|
inputAudioNoiseReduction,
|
|
@@ -429,7 +429,7 @@ export function processBaseURL({
|
|
|
429
429
|
* - openai_client_event_queued: expose the raw client events sent to the OpenAI Realtime API
|
|
430
430
|
*/
|
|
431
431
|
export class RealtimeSession extends llm.RealtimeSession {
|
|
432
|
-
private _tools: llm.ToolContext =
|
|
432
|
+
private _tools: llm.ToolContext = llm.ToolContext.empty();
|
|
433
433
|
private remoteChatCtx: llm.RemoteChatContext = new llm.RemoteChatContext();
|
|
434
434
|
private messageChannel = new Queue<api_proto.ClientEvent>();
|
|
435
435
|
private inputResampler?: AudioResampler;
|
|
@@ -557,7 +557,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
557
557
|
}
|
|
558
558
|
|
|
559
559
|
get tools() {
|
|
560
|
-
return
|
|
560
|
+
return this._tools.copy();
|
|
561
561
|
}
|
|
562
562
|
|
|
563
563
|
async updateChatCtx(_chatCtx: llm.ChatContext): Promise<void> {
|
|
@@ -724,13 +724,12 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
724
724
|
|
|
725
725
|
// TODO(brian): these logics below are noops I think; remove them later.
|
|
726
726
|
const retainedToolNames = new Set(ev.session.tools.map((tool) => tool.name));
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
),
|
|
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),
|
|
731
730
|
);
|
|
732
731
|
|
|
733
|
-
this._tools =
|
|
732
|
+
this._tools = new llm.ToolContext(retainedEntries);
|
|
734
733
|
|
|
735
734
|
unlock();
|
|
736
735
|
}
|
|
@@ -738,26 +737,26 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
738
737
|
private createToolsUpdateEvent(_tools: llm.ToolContext): api_proto.SessionUpdateEvent {
|
|
739
738
|
const oaiTools: api_proto.Tool[] = [];
|
|
740
739
|
|
|
741
|
-
for (const
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
continue;
|
|
745
|
-
}
|
|
740
|
+
for (const t of _tools.flatten()) {
|
|
741
|
+
// TODO: support provider tools in the Realtime session-update schema.
|
|
742
|
+
if (!llm.isFunctionTool(t)) continue;
|
|
746
743
|
|
|
747
|
-
const { parameters: toolParameters, description } = tool;
|
|
748
744
|
try {
|
|
749
745
|
const parameters = llm.toJsonSchema(
|
|
750
|
-
|
|
746
|
+
t.parameters,
|
|
751
747
|
) as unknown as api_proto.Tool['parameters'];
|
|
752
748
|
|
|
753
749
|
oaiTools.push({
|
|
754
|
-
name,
|
|
755
|
-
description,
|
|
750
|
+
name: t.name,
|
|
751
|
+
description: t.description,
|
|
756
752
|
parameters: parameters,
|
|
757
753
|
type: 'function',
|
|
758
754
|
});
|
|
759
755
|
} catch (e) {
|
|
760
|
-
this.#logger.error(
|
|
756
|
+
this.#logger.error(
|
|
757
|
+
{ name: t.name, tool: t },
|
|
758
|
+
"OpenAI Realtime API doesn't support this tool type",
|
|
759
|
+
);
|
|
761
760
|
continue;
|
|
762
761
|
}
|
|
763
762
|
}
|
|
@@ -847,7 +846,18 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
847
846
|
instructions?: string,
|
|
848
847
|
options: { signal?: AbortSignal } = {},
|
|
849
848
|
): Promise<llm.GenerationCreatedEvent> {
|
|
850
|
-
|
|
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
|
+
});
|
|
851
861
|
this.textModeRecoveryRetries = 0;
|
|
852
862
|
|
|
853
863
|
const onAbort = () => {
|
|
@@ -1065,7 +1075,7 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
1065
1075
|
events.push(this.createSessionUpdateEvent());
|
|
1066
1076
|
|
|
1067
1077
|
// tools
|
|
1068
|
-
if (Object.keys(this._tools).length > 0) {
|
|
1078
|
+
if (Object.keys(this._tools.functionTools).length > 0) {
|
|
1069
1079
|
events.push(this.createToolsUpdateEvent(this._tools));
|
|
1070
1080
|
}
|
|
1071
1081
|
|
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
|
}
|
|
@@ -63,6 +74,7 @@ class ResponsesHttpLLM extends llm.LLM {
|
|
|
63
74
|
this.#opts.client ||
|
|
64
75
|
new OpenAI({
|
|
65
76
|
baseURL: this.#opts.baseURL,
|
|
77
|
+
maxRetries: 0,
|
|
66
78
|
apiKey: this.#opts.apiKey,
|
|
67
79
|
});
|
|
68
80
|
}
|
|
@@ -77,25 +89,30 @@ class ResponsesHttpLLM extends llm.LLM {
|
|
|
77
89
|
|
|
78
90
|
override chat({
|
|
79
91
|
chatCtx,
|
|
80
|
-
toolCtx,
|
|
92
|
+
toolCtx: toolCtxInput,
|
|
81
93
|
connOptions = DEFAULT_API_CONNECT_OPTIONS,
|
|
82
94
|
parallelToolCalls,
|
|
83
95
|
toolChoice,
|
|
84
96
|
extraKwargs,
|
|
85
97
|
}: {
|
|
86
98
|
chatCtx: llm.ChatContext;
|
|
87
|
-
toolCtx?: llm.
|
|
99
|
+
toolCtx?: llm.ToolContextLike;
|
|
88
100
|
connOptions?: APIConnectOptions;
|
|
89
101
|
parallelToolCalls?: boolean;
|
|
90
102
|
toolChoice?: llm.ToolChoice;
|
|
91
103
|
extraKwargs?: Record<string, unknown>;
|
|
92
104
|
}): ResponsesHttpLLMStream {
|
|
105
|
+
const toolCtx = llm.toToolContext(toolCtxInput);
|
|
93
106
|
const modelOptions: Record<string, unknown> = { ...(extraKwargs || {}) };
|
|
94
107
|
|
|
95
108
|
parallelToolCalls =
|
|
96
109
|
parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;
|
|
97
110
|
|
|
98
|
-
if (
|
|
111
|
+
if (
|
|
112
|
+
toolCtx &&
|
|
113
|
+
Object.keys(toolCtx.functionTools).length > 0 &&
|
|
114
|
+
parallelToolCalls !== undefined
|
|
115
|
+
) {
|
|
99
116
|
modelOptions.parallel_tool_calls = parallelToolCalls;
|
|
100
117
|
}
|
|
101
118
|
|
|
@@ -126,6 +143,10 @@ class ResponsesHttpLLM extends llm.LLM {
|
|
|
126
143
|
modelOptions.max_output_tokens = this.#opts.maxOutputTokens;
|
|
127
144
|
}
|
|
128
145
|
|
|
146
|
+
if (this.#opts.reasoning !== undefined) {
|
|
147
|
+
modelOptions.reasoning = this.#opts.reasoning;
|
|
148
|
+
}
|
|
149
|
+
|
|
129
150
|
return new ResponsesHttpLLMStream(this, {
|
|
130
151
|
model: this.#opts.model,
|
|
131
152
|
client: this.#client,
|
|
@@ -181,25 +202,9 @@ class ResponsesHttpLLMStream extends llm.LLMStream {
|
|
|
181
202
|
'openai.responses',
|
|
182
203
|
)) as OpenAI.Responses.ResponseInputItem[];
|
|
183
204
|
|
|
205
|
+
// TODO: support provider tools in the Responses schema.
|
|
184
206
|
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
|
-
})
|
|
207
|
+
? toResponsesTools(this.toolCtx, this.strictToolSchema)
|
|
203
208
|
: undefined;
|
|
204
209
|
|
|
205
210
|
const requestOptions: Record<string, unknown> = { ...this.modelOptions };
|
|
@@ -430,7 +435,7 @@ export class LLM extends llm.LLM {
|
|
|
430
435
|
extraKwargs,
|
|
431
436
|
}: {
|
|
432
437
|
chatCtx: llm.ChatContext;
|
|
433
|
-
toolCtx?: llm.
|
|
438
|
+
toolCtx?: llm.ToolContextLike;
|
|
434
439
|
connOptions?: APIConnectOptions;
|
|
435
440
|
parallelToolCalls?: boolean;
|
|
436
441
|
toolChoice?: llm.ToolChoice;
|
package/src/stt.ts
CHANGED
|
@@ -298,6 +298,7 @@ export class STT extends stt.STT {
|
|
|
298
298
|
this.#opts.client ||
|
|
299
299
|
new OpenAI({
|
|
300
300
|
baseURL: this.#opts.baseURL,
|
|
301
|
+
maxRetries: 0,
|
|
301
302
|
apiKey: this.#opts.apiKey,
|
|
302
303
|
});
|
|
303
304
|
}
|
|
@@ -520,6 +521,9 @@ export class SpeechStream extends stt.SpeechStream {
|
|
|
520
521
|
}
|
|
521
522
|
|
|
522
523
|
protected async run(): Promise<void> {
|
|
524
|
+
// Avoid fusing an open segment into the next connection attempt after a retry.
|
|
525
|
+
this.#emitEndOfSpeech();
|
|
526
|
+
|
|
523
527
|
_validateRealtimeVad(this.#options.model, this.#options.turnDetection, this.#options.vad);
|
|
524
528
|
const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection)
|
|
525
529
|
? await _loadRealtimeVad(this.#options.vad)
|
|
@@ -540,7 +544,10 @@ export class SpeechStream extends stt.SpeechStream {
|
|
|
540
544
|
|
|
541
545
|
try {
|
|
542
546
|
ws.send(JSON.stringify(this.#sessionUpdateEvent()));
|
|
543
|
-
const tasks = [
|
|
547
|
+
const tasks = [
|
|
548
|
+
this.#forwardInput(ws, vadStream),
|
|
549
|
+
this.#forwardEvents(ws, Boolean(vadStream)),
|
|
550
|
+
];
|
|
544
551
|
if (vadStream) {
|
|
545
552
|
tasks.push(this.#forwardVadEvents(ws, vadStream));
|
|
546
553
|
}
|
|
@@ -634,16 +641,16 @@ export class SpeechStream extends stt.SpeechStream {
|
|
|
634
641
|
for await (const event of vadStream) {
|
|
635
642
|
if (event.type === VADEventType.START_OF_SPEECH) {
|
|
636
643
|
this.#emitStartOfSpeech();
|
|
637
|
-
} else if (
|
|
638
|
-
|
|
639
|
-
this.#options.turnDetection === null
|
|
640
|
-
|
|
641
|
-
|
|
644
|
+
} else if (event.type === VADEventType.END_OF_SPEECH) {
|
|
645
|
+
this.#emitEndOfSpeech();
|
|
646
|
+
if (this.#options.turnDetection === null) {
|
|
647
|
+
ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
|
|
648
|
+
}
|
|
642
649
|
}
|
|
643
650
|
}
|
|
644
651
|
}
|
|
645
652
|
|
|
646
|
-
async #forwardEvents(ws: WebSocket): Promise<void> {
|
|
653
|
+
async #forwardEvents(ws: WebSocket, hasClientVad: boolean): Promise<void> {
|
|
647
654
|
for await (const data of this.#messages(ws)) {
|
|
648
655
|
const event = parseRealtimeTranscriptionServerEvent(data);
|
|
649
656
|
switch (event.type) {
|
|
@@ -653,7 +660,9 @@ export class SpeechStream extends stt.SpeechStream {
|
|
|
653
660
|
this.#itemAudioTiming.set(itemId, {
|
|
654
661
|
startMs: event.audio_start_ms,
|
|
655
662
|
});
|
|
656
|
-
|
|
663
|
+
if (!hasClientVad) {
|
|
664
|
+
this.#emitStartOfSpeech();
|
|
665
|
+
}
|
|
657
666
|
break;
|
|
658
667
|
}
|
|
659
668
|
case 'input_audio_buffer.speech_stopped': {
|
|
@@ -661,13 +670,15 @@ export class SpeechStream extends stt.SpeechStream {
|
|
|
661
670
|
const timing = this.#itemAudioTiming.get(itemId) ?? {};
|
|
662
671
|
timing.endMs = event.audio_end_ms;
|
|
663
672
|
this.#itemAudioTiming.set(itemId, timing);
|
|
673
|
+
if (!hasClientVad) {
|
|
674
|
+
this.#emitEndOfSpeech();
|
|
675
|
+
}
|
|
664
676
|
break;
|
|
665
677
|
}
|
|
666
678
|
case 'conversation.item.input_audio_transcription.delta':
|
|
667
679
|
this.#currentItemId = event.item_id ?? this.#currentItemId;
|
|
668
680
|
if (event.delta) {
|
|
669
681
|
this.#targetTranscript += event.delta;
|
|
670
|
-
this.#emitStartOfSpeech();
|
|
671
682
|
this.queue.put(this.#speechEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT));
|
|
672
683
|
}
|
|
673
684
|
break;
|
|
@@ -676,14 +687,11 @@ export class SpeechStream extends stt.SpeechStream {
|
|
|
676
687
|
const transcript = event.transcript ?? '';
|
|
677
688
|
if (transcript) {
|
|
678
689
|
this.#targetTranscript = transcript;
|
|
679
|
-
this.#emitStartOfSpeech();
|
|
680
690
|
this.queue.put(this.#speechEvent(stt.SpeechEventType.FINAL_TRANSCRIPT, itemId));
|
|
681
691
|
}
|
|
682
692
|
this.#emitRecognitionUsage(event, itemId);
|
|
683
|
-
this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });
|
|
684
693
|
this.#targetTranscript = '';
|
|
685
694
|
this.#currentItemId = '';
|
|
686
|
-
this.#speaking = false;
|
|
687
695
|
break;
|
|
688
696
|
}
|
|
689
697
|
case 'error': {
|
|
@@ -754,6 +762,12 @@ export class SpeechStream extends stt.SpeechStream {
|
|
|
754
762
|
this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });
|
|
755
763
|
}
|
|
756
764
|
|
|
765
|
+
#emitEndOfSpeech(): void {
|
|
766
|
+
if (!this.#speaking) return;
|
|
767
|
+
this.#speaking = false;
|
|
768
|
+
this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });
|
|
769
|
+
}
|
|
770
|
+
|
|
757
771
|
#speechEvent(type: stt.SpeechEventType, requestId = this.#currentItemId): stt.SpeechEvent {
|
|
758
772
|
return {
|
|
759
773
|
type,
|
|
@@ -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
|
+
}
|