@livekit/agents-plugin-openai 1.9.1 → 1.9.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.
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/models.cjs +14 -1
- package/dist/models.cjs.map +1 -1
- package/dist/models.d.cts +3 -2
- package/dist/models.d.ts +3 -2
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +14 -1
- package/dist/models.js.map +1 -1
- package/dist/realtime/api_proto.cjs +3 -21
- package/dist/realtime/api_proto.cjs.map +1 -1
- package/dist/realtime/api_proto.d.cts +1 -504
- package/dist/realtime/api_proto.d.ts +1 -504
- package/dist/realtime/api_proto.d.ts.map +1 -1
- package/dist/realtime/api_proto.js +1 -12
- package/dist/realtime/api_proto.js.map +1 -1
- package/dist/realtime/gpt_live_model.cjs +7 -851
- package/dist/realtime/gpt_live_model.cjs.map +1 -1
- package/dist/realtime/gpt_live_model.d.cts +6 -178
- package/dist/realtime/gpt_live_model.d.ts +6 -178
- package/dist/realtime/gpt_live_model.d.ts.map +1 -1
- package/dist/realtime/gpt_live_model.js +7 -850
- package/dist/realtime/gpt_live_model.js.map +1 -1
- package/dist/realtime/gpt_live_model.test.cjs +32 -1
- package/dist/realtime/gpt_live_model.test.cjs.map +1 -1
- package/dist/realtime/gpt_live_model.test.js +32 -1
- package/dist/realtime/gpt_live_model.test.js.map +1 -1
- package/dist/realtime/gpt_live_types.cjs +6 -0
- package/dist/realtime/gpt_live_types.cjs.map +1 -1
- package/dist/realtime/gpt_live_types.d.cts +1 -169
- package/dist/realtime/gpt_live_types.d.ts +1 -169
- package/dist/realtime/gpt_live_types.d.ts.map +1 -1
- package/dist/realtime/gpt_live_types.js +1 -0
- package/dist/realtime/gpt_live_types.js.map +1 -1
- package/dist/realtime/index.cjs +8 -1
- package/dist/realtime/index.cjs.map +1 -1
- package/dist/realtime/index.d.cts +5 -0
- package/dist/realtime/index.d.ts +5 -0
- package/dist/realtime/index.d.ts.map +1 -1
- package/dist/realtime/index.js +6 -1
- package/dist/realtime/index.js.map +1 -1
- package/dist/realtime/realtime_model.cjs +3 -1831
- package/dist/realtime/realtime_model.cjs.map +1 -1
- package/dist/realtime/realtime_model.d.cts +1 -232
- package/dist/realtime/realtime_model.d.ts +1 -232
- package/dist/realtime/realtime_model.d.ts.map +1 -1
- package/dist/realtime/realtime_model.js +1 -1827
- package/dist/realtime/realtime_model.js.map +1 -1
- package/dist/realtime/realtime_model.test.cjs +11 -976
- package/dist/realtime/realtime_model.test.cjs.map +1 -1
- package/dist/realtime/realtime_model.test.js +16 -982
- package/dist/realtime/realtime_model.test.js.map +1 -1
- package/dist/stt.cjs +128 -86
- package/dist/stt.cjs.map +1 -1
- package/dist/stt.d.ts.map +1 -1
- package/dist/stt.js +133 -87
- package/dist/stt.js.map +1 -1
- package/dist/stt_recovery.test.cjs +197 -0
- package/dist/stt_recovery.test.cjs.map +1 -0
- package/dist/stt_recovery.test.d.cts +2 -0
- package/dist/stt_recovery.test.d.ts +2 -0
- package/dist/stt_recovery.test.d.ts.map +1 -0
- package/dist/stt_recovery.test.js +174 -0
- package/dist/stt_recovery.test.js.map +1 -0
- package/dist/ws/llm.cjs +1 -1
- package/dist/ws/llm.cjs.map +1 -1
- package/dist/ws/llm.js +1 -1
- package/dist/ws/llm.js.map +1 -1
- package/package.json +5 -6
- package/src/models.ts +23 -2
- package/src/realtime/api_proto.ts +2 -715
- package/src/realtime/gpt_live_model.test.ts +42 -1
- package/src/realtime/gpt_live_model.ts +17 -1030
- package/src/realtime/gpt_live_types.ts +1 -136
- package/src/realtime/index.ts +7 -0
- package/src/realtime/realtime_model.test.ts +17 -1268
- package/src/realtime/realtime_model.ts +2 -2332
- package/src/stt.ts +147 -104
- package/src/stt_recovery.test.ts +190 -0
- package/src/ws/llm.ts +1 -1
|
@@ -1,1040 +1,27 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 LiveKit, Inc.
|
|
2
2
|
//
|
|
3
3
|
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
shortuuid,
|
|
17
|
-
} from '@livekit/agents';
|
|
18
|
-
import { AudioFrame, AudioResampler } from '@livekit/rtc-node';
|
|
19
|
-
import { ReadableStream, type ReadableStreamDefaultController } from 'node:stream/web';
|
|
20
|
-
import { setTimeout as delay } from 'node:timers/promises';
|
|
21
|
-
import WebSocket from 'ws';
|
|
22
|
-
import { toResponsesTool } from '../tool_utils.js';
|
|
23
|
-
import type {
|
|
24
|
-
ClientEvent,
|
|
25
|
-
Delegation,
|
|
26
|
-
DelegationTarget,
|
|
27
|
-
InputItem,
|
|
28
|
-
InputRole,
|
|
29
|
-
ResponsesConfig,
|
|
30
|
-
ResponsesEvent,
|
|
31
|
-
ServerEvent,
|
|
32
|
-
} from './gpt_live_types.js';
|
|
33
|
-
|
|
34
|
-
const SAMPLE_RATE = 24000;
|
|
35
|
-
const MIN_SILENCE_DURATION = 800;
|
|
36
|
-
const DEFAULT_MODEL = 'gpt-live-1';
|
|
37
|
-
const DEFAULT_BACKEND_MODEL = 'gpt-5.6-luna';
|
|
38
|
-
const SPEAK_NOW = 'Do not wait for the caller to speak first. After that, pause and listen.';
|
|
39
|
-
const ASK_INSTRUCTED = `Immediately follow the instruction below. ${SPEAK_NOW}`;
|
|
40
|
-
const ASK_TYPED = `Reply to the caller now, don't repeat what they said. ${SPEAK_NOW}`;
|
|
41
|
-
const ASK_BARE = `Reply to the caller now. ${SPEAK_NOW}`;
|
|
42
|
-
const SESSION_CLOSE_TIMEOUT = 5000;
|
|
43
|
-
const FATAL_ERROR_CODES = new Set([
|
|
44
|
-
'insufficient_quota',
|
|
45
|
-
'invalid_api_key',
|
|
46
|
-
'account_deactivated',
|
|
47
|
-
'billing_hard_limit_reached',
|
|
48
|
-
]);
|
|
49
|
-
|
|
50
|
-
/** Settings for the backend Responses model. Unset fields use the service defaults.
|
|
51
|
-
* @public
|
|
52
|
-
*/
|
|
53
|
-
export interface ResponsesDelegationOptions {
|
|
54
|
-
/** Defaults to gpt-5.6-luna. */
|
|
55
|
-
model?: string;
|
|
56
|
-
/** Backend instructions, separate from the voice persona. */
|
|
57
|
-
instructions?: string;
|
|
58
|
-
/** Restrict backend tool selection. Null restores automatic selection. */
|
|
59
|
-
toolChoice?: llm.ToolChoice | null;
|
|
60
|
-
/** Allow the backend to request multiple tools in one response. */
|
|
61
|
-
parallelToolCalls?: boolean;
|
|
62
|
-
/** Reasoning effort for the backend model. */
|
|
63
|
-
reasoning?: ResponsesConfig['reasoning'];
|
|
64
|
-
/** Text format and verbosity for backend responses. */
|
|
65
|
-
text?: ResponsesConfig['text'];
|
|
66
|
-
/** Processing tier for backend responses. */
|
|
67
|
-
serviceTier?: ResponsesConfig['service_tier'];
|
|
68
|
-
/** Maximum tokens per backend response; the service requires at least 16. */
|
|
69
|
-
maxOutputTokens?: number;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Work handed to the application under client delegation.
|
|
73
|
-
* @public
|
|
74
|
-
*/
|
|
75
|
-
export interface GPTLiveDelegation {
|
|
76
|
-
/** Answer with GPTLiveSession.appendCommentary. Valid only on the connection that created it. */
|
|
77
|
-
id: string;
|
|
78
|
-
/** The caller's current turn, which may not yet be in the agent's chat context. */
|
|
79
|
-
pendingTranscript: string;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** Suggested GPT-Live voice names. Other supported names also pass through to the API. @public */
|
|
83
|
-
export type GPTLiveVoices = 'aster' | 'beacon' | 'cinder' | 'marin' | 'stone' | 'vesper';
|
|
84
|
-
|
|
85
|
-
/** Options for the OpenAI GPT-Live full-duplex voice model.
|
|
86
|
-
* @public
|
|
87
|
-
*/
|
|
88
|
-
export interface GPTLiveModelOptions {
|
|
89
|
-
/** Voice model identifier. Defaults to gpt-live-1. */
|
|
90
|
-
model?: string;
|
|
91
|
-
/**
|
|
92
|
-
* A named voice (marin by default), or an authorized custom voice object. Fixed at startup.
|
|
93
|
-
* Names pass through unchanged.
|
|
94
|
-
*/
|
|
95
|
-
voice?: GPTLiveVoices | (string & NonNullable<unknown>) | Record<string, unknown>;
|
|
96
|
-
/** Fixed at startup. Client delegation requires an agent with no tools. */
|
|
97
|
-
delegation?: DelegationTarget;
|
|
98
|
-
/** Backend configuration when delegation is responses (the default). */
|
|
99
|
-
responsesOptions?: ResponsesDelegationOptions;
|
|
100
|
-
/** Falls back to OPENAI_API_KEY. */
|
|
101
|
-
apiKey?: string;
|
|
102
|
-
/** Falls back to OPENAI_BASE_URL, then https://api.openai.com/v1. */
|
|
103
|
-
baseURL?: string;
|
|
104
|
-
/** Recycle the connection after this many milliseconds. Null (the default) disables the timer. */
|
|
105
|
-
maxSessionDuration?: number | null;
|
|
106
|
-
/** Connection/startup timeout and retry limits. Defaults to DEFAULT_API_CONNECT_OPTIONS. */
|
|
107
|
-
connOptions?: APIConnectOptions;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
type LiveOptions = Required<GPTLiveModelOptions>;
|
|
4
|
+
import type { llm } from '@livekit/agents';
|
|
5
|
+
import { GPTLiveModel as BaseGPTLiveModel } from '@livekit/agents/llm/openai_realtime/gpt_live_model';
|
|
6
|
+
import type OpenAI from 'openai';
|
|
7
|
+
import { OpenAITool } from '../tools.js';
|
|
8
|
+
|
|
9
|
+
export {
|
|
10
|
+
type GPTLiveDelegation,
|
|
11
|
+
type GPTLiveModelOptions,
|
|
12
|
+
GPTLiveSession,
|
|
13
|
+
type GPTLiveVoices,
|
|
14
|
+
type ResponsesDelegationOptions,
|
|
15
|
+
} from '@livekit/agents/llm/openai_realtime/gpt_live_model';
|
|
111
16
|
|
|
112
17
|
/** OpenAI GPT-Live full-duplex voice model, ready to pass to AgentSession.
|
|
113
18
|
* @public
|
|
114
19
|
*/
|
|
115
|
-
export class GPTLiveModel extends
|
|
20
|
+
export class GPTLiveModel extends BaseGPTLiveModel {
|
|
116
21
|
/** @internal */
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
super({
|
|
122
|
-
userTranscription: true,
|
|
123
|
-
autoToolReplyGeneration: true,
|
|
124
|
-
midSessionChatCtxUpdate: false,
|
|
125
|
-
midSessionInstructionsUpdate: false,
|
|
126
|
-
midSessionToolsUpdate: (options.delegation ?? 'responses') === 'responses',
|
|
127
|
-
});
|
|
128
|
-
const apiKey = options.apiKey ?? process.env.OPENAI_API_KEY;
|
|
129
|
-
if (!apiKey) {
|
|
130
|
-
throw new Error('OpenAI API key is required: pass apiKey or set OPENAI_API_KEY');
|
|
131
|
-
}
|
|
132
|
-
this._opts = {
|
|
133
|
-
model: options.model ?? DEFAULT_MODEL,
|
|
134
|
-
voice: options.voice ?? 'marin',
|
|
135
|
-
delegation: options.delegation ?? 'responses',
|
|
136
|
-
responsesOptions: { ...options.responsesOptions },
|
|
137
|
-
apiKey,
|
|
138
|
-
baseURL: options.baseURL ?? process.env.OPENAI_BASE_URL ?? 'https://api.openai.com/v1',
|
|
139
|
-
maxSessionDuration: options.maxSessionDuration ?? null,
|
|
140
|
-
connOptions: { ...(options.connOptions ?? DEFAULT_API_CONNECT_OPTIONS) },
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/** Voice model identifier used for sessions and metrics. */
|
|
145
|
-
get model(): string {
|
|
146
|
-
return this._opts.model;
|
|
147
|
-
}
|
|
148
|
-
/** Host of the configured API endpoint. */
|
|
149
|
-
get provider(): string {
|
|
150
|
-
return new URL(this._opts.baseURL).host;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/** Keep output active through short pauses in speech. */
|
|
154
|
-
audioGate(): llm.AudioGate {
|
|
155
|
-
return new llm.FixedGate(0.0006, { minSilenceDuration: MIN_SILENCE_DURATION });
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Create a connection that starts after the framework configures the session. */
|
|
159
|
-
session(): GPTLiveSession {
|
|
160
|
-
return new GPTLiveSession(this);
|
|
161
|
-
}
|
|
162
|
-
/** The model owns no shared resources. Close each session to release its connection. */
|
|
163
|
-
async close(): Promise<void> {}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
type Role = 'user' | 'assistant';
|
|
167
|
-
interface Speech {
|
|
168
|
-
messageId: string;
|
|
169
|
-
text: string;
|
|
170
|
-
endMs?: number;
|
|
171
|
-
startedAt: number;
|
|
172
|
-
quietMs: number;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* GPT-Live WebSocket session, accessible through Agent.duplexSession.
|
|
177
|
-
* Also emits openai_server_event_received, openai_client_event_queued and delegation_created.
|
|
178
|
-
* Append methods queue context without waiting for acknowledgment. The appended events arrive
|
|
179
|
-
* at the estimated context-injection end and do not indicate speech completion.
|
|
180
|
-
* @public
|
|
181
|
-
*/
|
|
182
|
-
export class GPTLiveSession extends llm.DuplexSession<{
|
|
183
|
-
openai_server_event_received: (event: ServerEvent) => void;
|
|
184
|
-
openai_client_event_queued: (event: ClientEvent | Record<string, unknown>) => void;
|
|
185
|
-
delegation_created: (event: GPTLiveDelegation) => void;
|
|
186
|
-
}> {
|
|
187
|
-
private readonly opts: LiveOptions;
|
|
188
|
-
private readonly logger = log();
|
|
189
|
-
private readonly debug = Number(process.env.LK_OPENAI_DEBUG ?? 0) !== 0;
|
|
190
|
-
private readonly history = llm.ChatContext.empty();
|
|
191
|
-
private readonly speech = new Map<Role, Speech>();
|
|
192
|
-
// delegation id -> call ids of its response that has not completed yet; on completion the
|
|
193
|
-
// call ids move to the open set, and stay there until each output is sent to the backend.
|
|
194
|
-
// backendResponsePending is set once an output is sent and cleared by the response.create
|
|
195
|
-
private readonly backendRunningResponses = new Map<string | null, Set<string>>();
|
|
196
|
-
private readonly backendOpenCalls = new Set<string>();
|
|
197
|
-
private backendResponsePending = false;
|
|
198
|
-
private readonly delegationIds = new Set<string>();
|
|
199
|
-
private readonly bstream = new AudioByteStream(SAMPLE_RATE, 1, SAMPLE_RATE / 10);
|
|
200
|
-
private inputResampler?: AudioResampler;
|
|
201
|
-
private inputRate?: number;
|
|
202
|
-
private _tools = llm.ToolContext.empty();
|
|
203
|
-
private instructions?: string;
|
|
204
|
-
private askedItemId?: string;
|
|
205
|
-
private _sessionId?: string;
|
|
206
|
-
private usageSeconds = 0;
|
|
207
|
-
private sessionStartSent = false;
|
|
208
|
-
private sessionStarted = false;
|
|
209
|
-
private closing = false;
|
|
210
|
-
private audioClosed = false;
|
|
211
|
-
private queued: {
|
|
212
|
-
event: ClientEvent | Record<string, unknown>;
|
|
213
|
-
replayOnReconnect: boolean;
|
|
214
|
-
context?: string;
|
|
215
|
-
}[] = [];
|
|
216
|
-
private ws?: WebSocket;
|
|
217
|
-
private connectionDone?: Future<Error | undefined>;
|
|
218
|
-
private connectionDraining = false;
|
|
219
|
-
private requestConnectionClose?: () => void;
|
|
220
|
-
private readonly shutdown = new AbortController();
|
|
221
|
-
private readonly mainTask: Promise<void>;
|
|
222
|
-
private audioController!: ReadableStreamDefaultController<llm.DuplexAudioFrame>;
|
|
223
|
-
private readonly output = new ReadableStream<llm.DuplexAudioFrame>({
|
|
224
|
-
start: (controller) => {
|
|
225
|
-
this.audioController = controller;
|
|
226
|
-
},
|
|
227
|
-
cancel: () => {
|
|
228
|
-
this.audioClosed = true;
|
|
229
|
-
},
|
|
230
|
-
});
|
|
231
|
-
|
|
232
|
-
/** Create a session using a copy of the model configuration. */
|
|
233
|
-
constructor(model: GPTLiveModel) {
|
|
234
|
-
super(model);
|
|
235
|
-
this.opts = { ...model._opts, responsesOptions: { ...model._opts.responsesOptions } };
|
|
236
|
-
// Let the adapter attach error/metrics listeners before starting the connection.
|
|
237
|
-
this.mainTask = Promise.resolve()
|
|
238
|
-
.then(() => this.main())
|
|
239
|
-
.catch((error) => {
|
|
240
|
-
this.logger.error({ 'lk.pii.error': error }, 'GPT-Live session failed');
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
/** Provider session identifier. Changes when a replacement connection starts. */
|
|
245
|
-
get sessionId(): string | undefined {
|
|
246
|
-
return this._sessionId;
|
|
247
|
-
}
|
|
248
|
-
/** Mono 24 kHz PCM output, retained across reconnects and closed on shutdown. */
|
|
249
|
-
get audioStream(): ReadableStream<llm.DuplexAudioFrame> {
|
|
250
|
-
return this.output;
|
|
251
|
-
}
|
|
252
|
-
/** Copy of the tools available to the backend Responses model. */
|
|
253
|
-
get tools(): llm.ToolContext {
|
|
254
|
-
return this._tools.copy();
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/** Queue a wire event. Commands wait for session.started before being sent. */
|
|
258
|
-
sendEvent(event: ClientEvent | Record<string, unknown>): void {
|
|
259
|
-
this.queueEvent(event, true);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
private queueEvent(
|
|
263
|
-
event: ClientEvent | Record<string, unknown>,
|
|
264
|
-
replayOnReconnect: boolean,
|
|
265
|
-
context?: string,
|
|
266
|
-
): void {
|
|
267
|
-
if (this.closing) return;
|
|
268
|
-
this.queued.push({ event, replayOnReconnect, context });
|
|
269
|
-
this.flushQueued();
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
private flushQueued(): void {
|
|
273
|
-
if (this.connectionDraining || !this.sessionStarted || this.ws?.readyState !== WebSocket.OPEN)
|
|
274
|
-
return;
|
|
275
|
-
while (this.queued.length) {
|
|
276
|
-
const { event, context } = this.queued.shift()!;
|
|
277
|
-
if (context !== undefined)
|
|
278
|
-
this.history.insert(new llm.ChatMessage({ role: 'developer', content: [context] }));
|
|
279
|
-
this.wsSend(this.ws, event);
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
private wsSend(ws: WebSocket, event: ClientEvent | Record<string, unknown>): void {
|
|
284
|
-
this.emit('openai_client_event_queued', event);
|
|
285
|
-
if (this.debug && event.type !== 'session.input_audio.append')
|
|
286
|
-
this.logger.debug({ 'lk.pii.event': event }, 'GPT-Live client event');
|
|
287
|
-
const done = this.connectionDone;
|
|
288
|
-
try {
|
|
289
|
-
ws.send(JSON.stringify(event), (error) => {
|
|
290
|
-
if (error) done?.resolve(new APIConnectionError({ message: 'GPT-Live send failed' }));
|
|
291
|
-
});
|
|
292
|
-
} catch {
|
|
293
|
-
done?.resolve(new APIConnectionError({ message: 'GPT-Live send failed' }));
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
private buildDelegation(): Delegation {
|
|
298
|
-
if (this.opts.delegation === 'client') return { type: 'client' };
|
|
299
|
-
const opts = this.opts.responsesOptions;
|
|
300
|
-
const tools = this.buildTools();
|
|
301
|
-
return {
|
|
302
|
-
type: 'responses',
|
|
303
|
-
responses: {
|
|
304
|
-
model: opts.model ?? DEFAULT_BACKEND_MODEL,
|
|
305
|
-
instructions: opts.instructions,
|
|
306
|
-
tools: tools.length ? tools : undefined,
|
|
307
|
-
tool_choice: opts.toolChoice !== undefined ? toToolChoice(opts.toolChoice) : undefined,
|
|
308
|
-
parallel_tool_calls: opts.parallelToolCalls,
|
|
309
|
-
reasoning: opts.reasoning,
|
|
310
|
-
text: opts.text,
|
|
311
|
-
service_tier: opts.serviceTier,
|
|
312
|
-
max_output_tokens: opts.maxOutputTokens,
|
|
313
|
-
},
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
private buildTools(): NonNullable<ResponsesConfig['tools']> {
|
|
318
|
-
return this._tools.flatten().flatMap((tool) => {
|
|
319
|
-
const converted = toResponsesTool(tool, false);
|
|
320
|
-
if (converted) return [converted];
|
|
321
|
-
this.logger.debug({ 'lk.pii.tool': tool.id }, 'GPT-Live delegation ignores unsupported tool');
|
|
322
|
-
return [];
|
|
323
|
-
});
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
private sessionStartEvent(): ClientEvent {
|
|
327
|
-
const items = this.history.items.flatMap((item): InputItem[] => {
|
|
328
|
-
const rendered = renderItem(item);
|
|
329
|
-
if (!rendered) return [];
|
|
330
|
-
const [role, text] = rendered;
|
|
331
|
-
return [
|
|
332
|
-
{
|
|
333
|
-
type: 'message',
|
|
334
|
-
role,
|
|
335
|
-
content: [{ type: role === 'assistant' ? 'output_text' : 'input_text', text }],
|
|
336
|
-
},
|
|
337
|
-
];
|
|
338
|
-
});
|
|
339
|
-
if (items.length > 128) {
|
|
340
|
-
this.logger.warn(
|
|
341
|
-
{ dropped: items.length - 128, kept: 128 },
|
|
342
|
-
'GPT-Live startup history exceeds the message limit; dropping the oldest',
|
|
343
|
-
);
|
|
344
|
-
}
|
|
345
|
-
return {
|
|
346
|
-
type: 'session.start',
|
|
347
|
-
event_id: shortuuid('session_start_'),
|
|
348
|
-
session: {
|
|
349
|
-
model: this.opts.model,
|
|
350
|
-
instructions: this.instructions,
|
|
351
|
-
input: items.length ? items.slice(-128) : undefined,
|
|
352
|
-
audio: {
|
|
353
|
-
format: { type: 'audio/pcm', rate: SAMPLE_RATE },
|
|
354
|
-
output: { voice: this.opts.voice },
|
|
355
|
-
},
|
|
356
|
-
delegation: this.buildDelegation(),
|
|
357
|
-
},
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
private sendDelegationUpdate(responses: ResponsesConfig): void {
|
|
362
|
-
if (this.opts.delegation !== 'responses' || !this.sessionStartSent) return;
|
|
363
|
-
this.queueEvent(
|
|
364
|
-
{
|
|
365
|
-
type: 'session.update',
|
|
366
|
-
event_id: shortuuid('delegation_update_'),
|
|
367
|
-
session: { delegation: { type: 'responses', responses } },
|
|
368
|
-
} satisfies ClientEvent,
|
|
369
|
-
false,
|
|
370
|
-
);
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
private async main(): Promise<void> {
|
|
374
|
-
let retries = 0;
|
|
375
|
-
let reconnecting = false;
|
|
376
|
-
try {
|
|
377
|
-
while (!this.closing) {
|
|
378
|
-
try {
|
|
379
|
-
await this.runConnection(
|
|
380
|
-
() => {
|
|
381
|
-
if (reconnecting) {
|
|
382
|
-
// History and delegation settings are rebuilt in session.start.
|
|
383
|
-
this.queued = this.queued.filter((command) => command.replayOnReconnect);
|
|
384
|
-
this.resetInputAudio();
|
|
385
|
-
this.endSpeech('user');
|
|
386
|
-
this.speech.clear();
|
|
387
|
-
this.backendRunningResponses.clear();
|
|
388
|
-
this.backendOpenCalls.clear();
|
|
389
|
-
this.backendResponsePending = false;
|
|
390
|
-
this.delegationIds.clear();
|
|
391
|
-
this.usageSeconds = 0;
|
|
392
|
-
this._sessionId = undefined;
|
|
393
|
-
}
|
|
394
|
-
},
|
|
395
|
-
() => {
|
|
396
|
-
retries = 0;
|
|
397
|
-
if (reconnecting) this.emit('session_reconnected', {});
|
|
398
|
-
},
|
|
399
|
-
);
|
|
400
|
-
} catch (error) {
|
|
401
|
-
if (this.closing) break;
|
|
402
|
-
const err =
|
|
403
|
-
error instanceof APIError
|
|
404
|
-
? error
|
|
405
|
-
: new APIConnectionError({
|
|
406
|
-
message: 'GPT-Live session failed',
|
|
407
|
-
options: { retryable: false },
|
|
408
|
-
});
|
|
409
|
-
const recoverable = err.retryable && retries < this.opts.connOptions.maxRetry;
|
|
410
|
-
this.emitError(err, recoverable);
|
|
411
|
-
if (!recoverable) throw err;
|
|
412
|
-
await delay(intervalForRetry(this.opts.connOptions, retries++), undefined, {
|
|
413
|
-
signal: this.shutdown.signal,
|
|
414
|
-
}).catch((error) => {
|
|
415
|
-
if (!this.closing) throw error;
|
|
416
|
-
});
|
|
417
|
-
} finally {
|
|
418
|
-
this.sessionStartSent = false;
|
|
419
|
-
this.sessionStarted = false;
|
|
420
|
-
}
|
|
421
|
-
reconnecting = true;
|
|
422
|
-
}
|
|
423
|
-
} finally {
|
|
424
|
-
this.endSpeech('user');
|
|
425
|
-
this.delegationIds.clear();
|
|
426
|
-
this.resetInputAudio();
|
|
427
|
-
if (!this.audioClosed) {
|
|
428
|
-
this.audioClosed = true;
|
|
429
|
-
this.audioController.close();
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
private async runConnection(onOpen: () => void, onStarted: () => void): Promise<void> {
|
|
435
|
-
const url = new URL(this.opts.baseURL);
|
|
436
|
-
url.protocol =
|
|
437
|
-
url.protocol === 'https:' ? 'wss:' : url.protocol === 'http:' ? 'ws:' : url.protocol;
|
|
438
|
-
url.pathname = url.pathname.replace(/\/$/, '');
|
|
439
|
-
if (!url.pathname.endsWith('/live/sessions')) url.pathname += '/live/sessions';
|
|
440
|
-
url.search = '';
|
|
441
|
-
url.hash = '';
|
|
442
|
-
const done = new Future<Error | undefined>();
|
|
443
|
-
this.connectionDone = done;
|
|
444
|
-
const startTime = performance.now();
|
|
445
|
-
const ws = new WebSocket(url, {
|
|
446
|
-
headers: {
|
|
447
|
-
'User-Agent': 'LiveKit Agents',
|
|
448
|
-
Authorization: `Bearer ${this.opts.apiKey}`,
|
|
449
|
-
},
|
|
450
|
-
handshakeTimeout: this.opts.connOptions.timeoutMs,
|
|
451
|
-
});
|
|
452
|
-
this.ws = ws;
|
|
453
|
-
let recycleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
454
|
-
let startupTimer: ReturnType<typeof setTimeout> | undefined;
|
|
455
|
-
let closeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
456
|
-
const requestClose = () => {
|
|
457
|
-
if (this.connectionDraining || done.done) return;
|
|
458
|
-
this.connectionDraining = true;
|
|
459
|
-
if (this.sessionStarted && ws.readyState === WebSocket.OPEN) {
|
|
460
|
-
closeTimer = setTimeout(() => done.resolve(undefined), SESSION_CLOSE_TIMEOUT);
|
|
461
|
-
this.wsSend(ws, { type: 'session.close' } satisfies ClientEvent);
|
|
462
|
-
} else {
|
|
463
|
-
done.resolve(undefined);
|
|
464
|
-
}
|
|
465
|
-
};
|
|
466
|
-
this.requestConnectionClose = requestClose;
|
|
467
|
-
const closed = new Future();
|
|
468
|
-
ws.once('close', () => closed.resolve());
|
|
469
|
-
ws.on('open', () => {
|
|
470
|
-
this._reportConnectionAcquired(performance.now() - startTime);
|
|
471
|
-
onOpen();
|
|
472
|
-
void Promise.race([this._configured.wait(), done.await])
|
|
473
|
-
.then(() => {
|
|
474
|
-
if (this.closing || done.done) return;
|
|
475
|
-
this.sessionStartSent = true;
|
|
476
|
-
startupTimer = setTimeout(
|
|
477
|
-
() =>
|
|
478
|
-
done.resolve(new APITimeoutError({ message: 'GPT-Live session start timed out' })),
|
|
479
|
-
this.opts.connOptions.timeoutMs,
|
|
480
|
-
);
|
|
481
|
-
this.wsSend(ws, this.sessionStartEvent());
|
|
482
|
-
})
|
|
483
|
-
.catch((error: Error) => done.resolve(error));
|
|
484
|
-
});
|
|
485
|
-
ws.on('error', () =>
|
|
486
|
-
done.resolve(new APIConnectionError({ message: 'GPT-Live connection failed' })),
|
|
487
|
-
);
|
|
488
|
-
ws.on('close', () =>
|
|
489
|
-
done.resolve(
|
|
490
|
-
this.closing || this.connectionDraining
|
|
491
|
-
? undefined
|
|
492
|
-
: new APIConnectionError({ message: 'OpenAI Live API connection closed unexpectedly' }),
|
|
493
|
-
),
|
|
494
|
-
);
|
|
495
|
-
ws.on('message', (data, isBinary) => {
|
|
496
|
-
if (isBinary || done.done) return;
|
|
497
|
-
try {
|
|
498
|
-
const event = JSON.parse(data.toString()) as ServerEvent;
|
|
499
|
-
if (event.type === 'session.delegation.created' && event.delegation?.id)
|
|
500
|
-
this.delegationIds.add(event.delegation.id);
|
|
501
|
-
this.emit('openai_server_event_received', event);
|
|
502
|
-
if (this.debug && event.type !== 'session.output_audio.delta')
|
|
503
|
-
this.logger.debug({ 'lk.pii.event': event }, 'GPT-Live server event');
|
|
504
|
-
if (
|
|
505
|
-
this.closing &&
|
|
506
|
-
event.type !== 'session.usage.updated' &&
|
|
507
|
-
event.type !== 'session.closed'
|
|
508
|
-
)
|
|
509
|
-
return;
|
|
510
|
-
const started = event.type === 'session.started' && !this.sessionStarted;
|
|
511
|
-
this.handleEvent(event);
|
|
512
|
-
if (started) {
|
|
513
|
-
clearTimeout(startupTimer);
|
|
514
|
-
onStarted();
|
|
515
|
-
if (this.opts.maxSessionDuration !== null) {
|
|
516
|
-
recycleTimer = setTimeout(requestClose, this.opts.maxSessionDuration);
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
} catch (error) {
|
|
520
|
-
if (error instanceof APIError && !error.retryable) done.resolve(error);
|
|
521
|
-
else this.logger.error({ 'lk.pii.error': error }, 'Failed to handle GPT-Live event');
|
|
522
|
-
}
|
|
523
|
-
});
|
|
524
|
-
try {
|
|
525
|
-
const error = await done.await;
|
|
526
|
-
if (error) throw error;
|
|
527
|
-
} finally {
|
|
528
|
-
this.sessionStartSent = false;
|
|
529
|
-
this.sessionStarted = false;
|
|
530
|
-
clearTimeout(recycleTimer);
|
|
531
|
-
clearTimeout(startupTimer);
|
|
532
|
-
clearTimeout(closeTimer);
|
|
533
|
-
this.connectionDraining = false;
|
|
534
|
-
this.requestConnectionClose = undefined;
|
|
535
|
-
this.ws = undefined;
|
|
536
|
-
this.connectionDone = undefined;
|
|
537
|
-
ws.terminate();
|
|
538
|
-
await closed.await;
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
private handleEvent(event: ServerEvent): void {
|
|
543
|
-
switch (event.type) {
|
|
544
|
-
case 'session.started':
|
|
545
|
-
this._sessionId = event.session?.id ?? this._sessionId;
|
|
546
|
-
this.sessionStarted = true;
|
|
547
|
-
this.flushQueued();
|
|
548
|
-
break;
|
|
549
|
-
case 'session.output_audio.delta': {
|
|
550
|
-
const data = Buffer.from(event.delta ?? '', 'base64');
|
|
551
|
-
if (!data.length || this.audioClosed) break;
|
|
552
|
-
const samples = new Int16Array(data.length / 2);
|
|
553
|
-
for (let i = 0; i < samples.length; i++) samples[i] = data.readInt16LE(i * 2);
|
|
554
|
-
this.audioController.enqueue({
|
|
555
|
-
frame: new AudioFrame(samples, SAMPLE_RATE, 1, samples.length),
|
|
556
|
-
});
|
|
557
|
-
break;
|
|
558
|
-
}
|
|
559
|
-
case 'session.input_transcript.delta':
|
|
560
|
-
case 'session.output_transcript.delta':
|
|
561
|
-
this.handleTranscript(
|
|
562
|
-
event.type === 'session.input_transcript.delta' ? 'user' : 'assistant',
|
|
563
|
-
event,
|
|
564
|
-
);
|
|
565
|
-
break;
|
|
566
|
-
case 'session.delegation.created': {
|
|
567
|
-
const delegation = event.delegation;
|
|
568
|
-
if (!delegation?.id)
|
|
569
|
-
this.logger.warn('GPT-Live delegation has no id; nothing can answer it');
|
|
570
|
-
else if (delegation.target === 'client')
|
|
571
|
-
this.emit('delegation_created', {
|
|
572
|
-
id: delegation.id,
|
|
573
|
-
pendingTranscript: this.speech.get('user')?.text ?? '',
|
|
574
|
-
} satisfies GPTLiveDelegation);
|
|
575
|
-
break;
|
|
576
|
-
}
|
|
577
|
-
case 'response.event':
|
|
578
|
-
this.handleResponseEvent(event.delegation_id ?? null, event.event ?? { type: '' });
|
|
579
|
-
break;
|
|
580
|
-
case 'session.usage.updated':
|
|
581
|
-
case 'session.closed':
|
|
582
|
-
if (event.type === 'session.closed')
|
|
583
|
-
this.logger.debug(
|
|
584
|
-
{ reason: event.reason ?? null, sessionId: this._sessionId },
|
|
585
|
-
'GPT-Live session closed',
|
|
586
|
-
);
|
|
587
|
-
if (event.context_window?.usage_ratio != null)
|
|
588
|
-
this.logger.debug(
|
|
589
|
-
{ usageRatio: event.context_window.usage_ratio },
|
|
590
|
-
'GPT-Live context window utilization',
|
|
591
|
-
);
|
|
592
|
-
this.handleUsage(event.usage?.seconds);
|
|
593
|
-
if (event.type === 'session.closed') this.connectionDone?.resolve(undefined);
|
|
594
|
-
break;
|
|
595
|
-
case 'error': {
|
|
596
|
-
const error = event.error ?? {};
|
|
597
|
-
const recoverable = !FATAL_ERROR_CODES.has(error.code || error.type || '');
|
|
598
|
-
this.logger.error({ 'lk.pii.error': error }, 'GPT-Live returned an error');
|
|
599
|
-
const apiError = new APIError('GPT-Live returned an error', {
|
|
600
|
-
retryable: recoverable,
|
|
601
|
-
});
|
|
602
|
-
if (!recoverable) throw apiError;
|
|
603
|
-
this.emitError(apiError, true);
|
|
604
|
-
break;
|
|
605
|
-
}
|
|
606
|
-
default:
|
|
607
|
-
this.logger.debug({ 'lk.pii.type': event.type }, 'GPT-Live acknowledged a command');
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
private handleTranscript(
|
|
612
|
-
role: Role,
|
|
613
|
-
event: { delta?: string; start_ms?: number | null; end_ms?: number | null },
|
|
614
|
-
): void {
|
|
615
|
-
if (!event.delta) return;
|
|
616
|
-
let speech = this.speech.get(role);
|
|
617
|
-
if (
|
|
618
|
-
speech?.endMs !== undefined &&
|
|
619
|
-
event.start_ms != null &&
|
|
620
|
-
event.start_ms - speech.endMs > MIN_SILENCE_DURATION
|
|
621
|
-
) {
|
|
622
|
-
this.endSpeech(role);
|
|
623
|
-
speech = undefined;
|
|
624
|
-
}
|
|
625
|
-
if (!speech) {
|
|
626
|
-
speech = { messageId: shortuuid('speech_'), text: '', startedAt: Date.now(), quietMs: 0 };
|
|
627
|
-
this.speech.set(role, speech);
|
|
628
|
-
this.history.insert(
|
|
629
|
-
new llm.ChatMessage({
|
|
630
|
-
id: speech.messageId,
|
|
631
|
-
role,
|
|
632
|
-
content: [''],
|
|
633
|
-
transcriptConfidence: role === 'user' ? 1 : undefined,
|
|
634
|
-
}),
|
|
635
|
-
);
|
|
636
|
-
if (role === 'user') this.emit('input_speech_started', {});
|
|
637
|
-
}
|
|
638
|
-
speech.text += event.delta;
|
|
639
|
-
speech.quietMs = 0;
|
|
640
|
-
if (event.end_ms != null) speech.endMs = Math.max(speech.endMs ?? 0, event.end_ms);
|
|
641
|
-
const message = this.history.getById(speech.messageId);
|
|
642
|
-
if (message?.type === 'message') message.content[0] = speech.text;
|
|
643
|
-
if (role === 'user') {
|
|
644
|
-
this.emit('input_audio_transcription_completed', {
|
|
645
|
-
itemId: speech.messageId,
|
|
646
|
-
transcript: speech.text,
|
|
647
|
-
isFinal: false,
|
|
648
|
-
turnStartedAt: speech.startedAt,
|
|
649
|
-
} satisfies llm.InputTranscriptionCompleted);
|
|
650
|
-
} else {
|
|
651
|
-
this.emit('transcript_delta', {
|
|
652
|
-
text: event.delta,
|
|
653
|
-
startMs: event.start_ms ?? undefined,
|
|
654
|
-
endMs: event.end_ms ?? undefined,
|
|
655
|
-
} satisfies llm.DuplexOutputTranscriptDelta);
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
private endSpeech(role: Role): void {
|
|
660
|
-
const speech = this.speech.get(role);
|
|
661
|
-
this.speech.delete(role);
|
|
662
|
-
if (!speech || role !== 'user') return;
|
|
663
|
-
this.emit('input_audio_transcription_completed', {
|
|
664
|
-
itemId: speech.messageId,
|
|
665
|
-
transcript: speech.text,
|
|
666
|
-
isFinal: true,
|
|
667
|
-
turnStartedAt: speech.startedAt,
|
|
668
|
-
} satisfies llm.InputTranscriptionCompleted);
|
|
669
|
-
this.emit('input_speech_stopped', {
|
|
670
|
-
userTranscriptionEnabled: false,
|
|
671
|
-
} satisfies llm.InputSpeechStoppedEvent);
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
private handleResponseEvent(delegationId: string | null, event: ResponsesEvent): void {
|
|
675
|
-
switch (event.type) {
|
|
676
|
-
case 'response.created':
|
|
677
|
-
this.backendRunningResponses.set(delegationId, new Set());
|
|
678
|
-
break;
|
|
679
|
-
case 'response.output_item.done': {
|
|
680
|
-
const item = event.item;
|
|
681
|
-
if (!item || item.type !== 'function_call') return;
|
|
682
|
-
if (!item.call_id || !item.name || item.arguments == null) {
|
|
683
|
-
this.logger.warn(
|
|
684
|
-
{ 'lk.pii.call_id': item.call_id, 'lk.pii.name': item.name },
|
|
685
|
-
'GPT-Live dropping function call with missing fields',
|
|
686
|
-
);
|
|
687
|
-
return;
|
|
688
|
-
}
|
|
689
|
-
let calls = this.backendRunningResponses.get(delegationId);
|
|
690
|
-
if (!calls) {
|
|
691
|
-
this.logger.warn(
|
|
692
|
-
{ 'lk.pii.call_id': item.call_id, 'lk.pii.delegation_id': delegationId },
|
|
693
|
-
'GPT-Live function call outside a known response',
|
|
694
|
-
);
|
|
695
|
-
calls = this.backendOpenCalls;
|
|
696
|
-
}
|
|
697
|
-
calls.add(item.call_id);
|
|
698
|
-
const call = new llm.FunctionCall({
|
|
699
|
-
id: item.id ?? shortuuid('fc_'),
|
|
700
|
-
callId: item.call_id,
|
|
701
|
-
name: item.name,
|
|
702
|
-
args: item.arguments,
|
|
703
|
-
});
|
|
704
|
-
this.history.insert(call);
|
|
705
|
-
this.emit('function_call', call);
|
|
706
|
-
break;
|
|
707
|
-
}
|
|
708
|
-
case 'response.completed': {
|
|
709
|
-
this.handleResponseUsage(event.response);
|
|
710
|
-
const calls = this.backendRunningResponses.get(delegationId);
|
|
711
|
-
if (calls) {
|
|
712
|
-
this.backendRunningResponses.delete(delegationId);
|
|
713
|
-
for (const callId of calls) this.backendOpenCalls.add(callId);
|
|
714
|
-
}
|
|
715
|
-
this.maybeContinueResponse();
|
|
716
|
-
break;
|
|
717
|
-
}
|
|
718
|
-
case 'response.failed':
|
|
719
|
-
case 'response.incomplete': {
|
|
720
|
-
this.handleResponseUsage(event.response);
|
|
721
|
-
this.logger.warn(
|
|
722
|
-
{
|
|
723
|
-
type: event.type,
|
|
724
|
-
'lk.pii.delegation_id': delegationId,
|
|
725
|
-
'lk.pii.error': event.response?.error,
|
|
726
|
-
'lk.pii.incomplete_details': event.response?.incomplete_details,
|
|
727
|
-
},
|
|
728
|
-
'GPT-Live backend response did not complete',
|
|
729
|
-
);
|
|
730
|
-
// the service discards a failed response's calls: an output for one is refused, so it
|
|
731
|
-
// goes to the voice model as context instead
|
|
732
|
-
this.backendRunningResponses.delete(delegationId);
|
|
733
|
-
this.maybeContinueResponse();
|
|
734
|
-
break;
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
private handleResponseUsage(response: ResponsesEvent['response']): void {
|
|
740
|
-
const usage = response?.usage;
|
|
741
|
-
if (usage) {
|
|
742
|
-
const metric: metrics.LLMMetrics = {
|
|
743
|
-
type: 'llm_metrics',
|
|
744
|
-
label: this.duplexModel.label(),
|
|
745
|
-
requestId: response?.id ?? '',
|
|
746
|
-
timestamp: Date.now(),
|
|
747
|
-
durationMs: 0,
|
|
748
|
-
ttftMs: -1,
|
|
749
|
-
cancelled: false,
|
|
750
|
-
tokensPerSecond: 0,
|
|
751
|
-
promptTokens: usage.input_tokens ?? 0,
|
|
752
|
-
promptCachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
|
|
753
|
-
cacheCreationTokens: usage.input_tokens_details?.cache_write_tokens ?? 0,
|
|
754
|
-
completionTokens: usage.output_tokens ?? 0,
|
|
755
|
-
reasoningTokens: usage.output_tokens_details?.reasoning_tokens ?? 0,
|
|
756
|
-
totalTokens: usage.total_tokens ?? 0,
|
|
757
|
-
metadata: {
|
|
758
|
-
modelName: response?.model || this.opts.responsesOptions.model || DEFAULT_BACKEND_MODEL,
|
|
759
|
-
modelProvider: this.duplexModel.provider,
|
|
760
|
-
},
|
|
761
|
-
};
|
|
762
|
-
this.emit('metrics_collected', metric);
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
private maybeContinueResponse(): void {
|
|
767
|
-
// one response.create continues the chain, and only once nothing is still asking and every
|
|
768
|
-
// call in the conversation has its answer: the service refuses a partial batch
|
|
769
|
-
if (
|
|
770
|
-
this.backendRunningResponses.size ||
|
|
771
|
-
this.backendOpenCalls.size ||
|
|
772
|
-
!this.backendResponsePending
|
|
773
|
-
)
|
|
774
|
-
return;
|
|
775
|
-
this.backendResponsePending = false;
|
|
776
|
-
this.queueEvent(
|
|
777
|
-
{
|
|
778
|
-
type: 'response.create',
|
|
779
|
-
event_id: shortuuid('response_create_'),
|
|
780
|
-
} satisfies ClientEvent,
|
|
781
|
-
false,
|
|
782
|
-
);
|
|
783
|
-
}
|
|
784
|
-
|
|
785
|
-
private handleUsage(seconds: number | undefined): void {
|
|
786
|
-
if (seconds === undefined || !Number.isFinite(seconds) || seconds < this.usageSeconds) return;
|
|
787
|
-
const previous = this.usageSeconds;
|
|
788
|
-
this.usageSeconds = seconds;
|
|
789
|
-
this.emit('metrics_collected', {
|
|
790
|
-
type: 'realtime_model_metrics',
|
|
791
|
-
label: this.duplexModel.label(),
|
|
792
|
-
requestId: this._sessionId ?? '',
|
|
793
|
-
timestamp: Date.now(),
|
|
794
|
-
durationMs: 0,
|
|
795
|
-
ttftMs: -1,
|
|
796
|
-
cancelled: false,
|
|
797
|
-
sessionDurationMs: Math.max(0, seconds - previous) * 1000,
|
|
798
|
-
inputTokens: 0,
|
|
799
|
-
outputTokens: 0,
|
|
800
|
-
totalTokens: 0,
|
|
801
|
-
tokensPerSecond: 0,
|
|
802
|
-
inputTokenDetails: { audioTokens: 0, textTokens: 0, imageTokens: 0, cachedTokens: 0 },
|
|
803
|
-
outputTokenDetails: { audioTokens: 0, textTokens: 0, imageTokens: 0 },
|
|
804
|
-
metadata: { modelName: this.duplexModel.model, modelProvider: this.duplexModel.provider },
|
|
805
|
-
} satisfies metrics.RealtimeModelMetrics);
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
private emitError(error: Error, recoverable: boolean): void {
|
|
809
|
-
this.emit('error', {
|
|
810
|
-
type: 'realtime_model_error',
|
|
811
|
-
timestamp: Date.now(),
|
|
812
|
-
label: this.duplexModel.label(),
|
|
813
|
-
error,
|
|
814
|
-
recoverable,
|
|
815
|
-
} satisfies llm.RealtimeModelError);
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
/** Buffer microphone audio, mixing to mono and resampling to 24 kHz as needed. */
|
|
819
|
-
pushAudio(frame: AudioFrame): void {
|
|
820
|
-
if (this.closing) return;
|
|
821
|
-
const speech = this.speech.get('user');
|
|
822
|
-
if (speech) {
|
|
823
|
-
speech.quietMs += Math.round((frame.samplesPerChannel / frame.sampleRate) * 1000);
|
|
824
|
-
if (speech.quietMs >= MIN_SILENCE_DURATION) this.endSpeech('user');
|
|
825
|
-
}
|
|
826
|
-
if (frame.channels !== 1) {
|
|
827
|
-
const mono = new Int16Array(frame.samplesPerChannel);
|
|
828
|
-
for (let i = 0; i < mono.length; i++) {
|
|
829
|
-
let sum = 0;
|
|
830
|
-
for (let channel = 0; channel < frame.channels; channel++)
|
|
831
|
-
sum += frame.data[i * frame.channels + channel]!;
|
|
832
|
-
mono[i] = Math.round(sum / frame.channels);
|
|
833
|
-
}
|
|
834
|
-
frame = new AudioFrame(mono, frame.sampleRate, 1, mono.length);
|
|
835
|
-
}
|
|
836
|
-
if (this.inputRate !== frame.sampleRate) {
|
|
837
|
-
this.inputResampler?.close();
|
|
838
|
-
this.inputResampler =
|
|
839
|
-
frame.sampleRate === SAMPLE_RATE
|
|
840
|
-
? undefined
|
|
841
|
-
: new AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);
|
|
842
|
-
this.inputRate = frame.sampleRate;
|
|
843
|
-
}
|
|
844
|
-
for (const resampled of this.inputResampler ? this.inputResampler.push(frame) : [frame]) {
|
|
845
|
-
for (const chunk of this.bstream.write(resampled.data)) {
|
|
846
|
-
this.sendEvent({
|
|
847
|
-
type: 'session.input_audio.append',
|
|
848
|
-
audio: Buffer.from(
|
|
849
|
-
chunk.data.buffer,
|
|
850
|
-
chunk.data.byteOffset,
|
|
851
|
-
chunk.data.byteLength,
|
|
852
|
-
).toString('base64'),
|
|
853
|
-
} satisfies ClientEvent);
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
private resetInputAudio(): void {
|
|
859
|
-
// Discard partial samples from the old session, including the resampler's filter history.
|
|
860
|
-
this.bstream.flush();
|
|
861
|
-
this.inputResampler?.close();
|
|
862
|
-
this.inputResampler = undefined;
|
|
863
|
-
this.inputRate = undefined;
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
/** Add a standing rule retained in reconnect history. The service caps each append at 500 tokens. */
|
|
867
|
-
appendInstructions(text: string, options: { delegationId?: string | null } = {}): void {
|
|
868
|
-
this.append('session.instructions.append', text, options.delegationId ?? null, {
|
|
869
|
-
persist: true,
|
|
870
|
-
});
|
|
871
|
-
}
|
|
872
|
-
/** Add silent context retained in reconnect history. The service caps each append at 500 tokens. */
|
|
873
|
-
appendThinking(text: string, options: { delegationId?: string | null } = {}): void {
|
|
874
|
-
this.append('session.thinking.append', text, options.delegationId ?? null, { persist: true });
|
|
875
|
-
}
|
|
876
|
-
/** Give the model text to paraphrase aloud, or answer a client delegation. Capped at 500 tokens by the service. */
|
|
877
|
-
appendCommentary(text: string, options: { delegationId?: string | null } = {}): void {
|
|
878
|
-
this.append('session.commentary.append', text, options.delegationId ?? null);
|
|
879
|
-
}
|
|
880
|
-
private append(
|
|
881
|
-
type: 'session.instructions.append' | 'session.thinking.append' | 'session.commentary.append',
|
|
882
|
-
content: string,
|
|
883
|
-
delegationId: string | null,
|
|
884
|
-
options: { replayOnReconnect?: boolean; persist?: boolean } = {},
|
|
885
|
-
): void {
|
|
886
|
-
if (delegationId !== null && !this.delegationIds.has(delegationId)) {
|
|
887
|
-
this.logger.debug('GPT-Live ignoring append for an inactive delegation');
|
|
888
|
-
return;
|
|
889
|
-
}
|
|
890
|
-
this.queueEvent(
|
|
891
|
-
{
|
|
892
|
-
type,
|
|
893
|
-
event_id: shortuuid('append_'),
|
|
894
|
-
delegation_id: delegationId,
|
|
895
|
-
content,
|
|
896
|
-
} satisfies ClientEvent,
|
|
897
|
-
delegationId === null && (options.replayOnReconnect ?? true),
|
|
898
|
-
options.persist ? content : undefined,
|
|
899
|
-
);
|
|
900
|
-
}
|
|
901
|
-
/** Replace microphone input with silence while the model continues speaking. */
|
|
902
|
-
muteInput(): void {
|
|
903
|
-
this.sendEvent({
|
|
904
|
-
type: 'session.input_audio.mute',
|
|
905
|
-
event_id: shortuuid('mute_'),
|
|
906
|
-
} satisfies ClientEvent);
|
|
907
|
-
}
|
|
908
|
-
/** Restore microphone input. */
|
|
909
|
-
unmuteInput(): void {
|
|
910
|
-
this.sendEvent({
|
|
911
|
-
type: 'session.input_audio.unmute',
|
|
912
|
-
event_id: shortuuid('unmute_'),
|
|
913
|
-
} satisfies ClientEvent);
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
/** Drain final provider usage, then close the transport and output stream. */
|
|
917
|
-
protected async closeConnection(): Promise<void> {
|
|
918
|
-
if (!this.closing) {
|
|
919
|
-
this.closing = true;
|
|
920
|
-
this.shutdown.abort();
|
|
921
|
-
this.requestConnectionClose?.();
|
|
922
|
-
}
|
|
923
|
-
await this.mainTask;
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
/** Set the initial voice instructions. Changes after session.start are rejected. */
|
|
927
|
-
async _updateInstructions(instructions: string): Promise<void> {
|
|
928
|
-
if (this.sessionStartSent && instructions !== this.instructions) {
|
|
929
|
-
throw new llm.RealtimeError(
|
|
930
|
-
'gpt-live voice instructions are immutable after session start; use appendInstructions for a standing rule',
|
|
931
|
-
);
|
|
932
|
-
}
|
|
933
|
-
this.instructions = instructions;
|
|
934
|
-
}
|
|
935
|
-
/** Update backend tools. Client delegation requires an empty tool context. */
|
|
936
|
-
async _updateTools(tools: llm.ToolContext): Promise<void> {
|
|
937
|
-
if (this.opts.delegation === 'client' && tools.flatten().length) {
|
|
938
|
-
throw new llm.RealtimeError(
|
|
939
|
-
`gpt-live client delegation has no tool channel, so the model can never call ${tools
|
|
940
|
-
.flatten()
|
|
941
|
-
.map((tool) => tool.id)
|
|
942
|
-
.sort()
|
|
943
|
-
.join(
|
|
944
|
-
', ',
|
|
945
|
-
)}. Leave the agent's tools empty and answer delegation_created with appendCommentary, or pass delegation="responses" to run tools on the backend model.`,
|
|
946
|
-
);
|
|
947
|
-
}
|
|
948
|
-
this._tools = tools.copy();
|
|
949
|
-
this.sendDelegationUpdate({ tools: this.buildTools() });
|
|
950
|
-
}
|
|
951
|
-
/** Retain framework chat items for reconnects and send their context or tool results. */
|
|
952
|
-
async _appendItems(items: llm.ChatItem[]): Promise<void> {
|
|
953
|
-
this.history.insert(items);
|
|
954
|
-
if (!this.sessionStartSent) return;
|
|
955
|
-
const outputs: llm.FunctionCallOutput[] = [];
|
|
956
|
-
const lines: string[] = [];
|
|
957
|
-
for (const item of items) {
|
|
958
|
-
if (item.type === 'message' && (item.role === 'system' || item.role === 'developer')) {
|
|
959
|
-
if (item.textContent)
|
|
960
|
-
this.append('session.instructions.append', item.textContent, null, {
|
|
961
|
-
replayOnReconnect: false,
|
|
962
|
-
});
|
|
963
|
-
} else if (
|
|
964
|
-
item.type === 'function_call_output' &&
|
|
965
|
-
(this.backendOpenCalls.has(item.callId) ||
|
|
966
|
-
[...this.backendRunningResponses.values()].some((calls) => calls.has(item.callId)))
|
|
967
|
-
) {
|
|
968
|
-
outputs.push(item);
|
|
969
|
-
} else {
|
|
970
|
-
const rendered = renderItem(item);
|
|
971
|
-
if (rendered) lines.push(`${rendered[0]}: ${rendered[1]}`);
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
if (lines.length)
|
|
975
|
-
this.append('session.thinking.append', lines.join('\n'), null, { replayOnReconnect: false });
|
|
976
|
-
for (const output of outputs) {
|
|
977
|
-
this.queueEvent(
|
|
978
|
-
{
|
|
979
|
-
type: 'response.item.create',
|
|
980
|
-
event_id: shortuuid('tool_output_'),
|
|
981
|
-
item: { type: 'function_call_output', call_id: output.callId, output: output.output },
|
|
982
|
-
} satisfies ClientEvent,
|
|
983
|
-
false,
|
|
984
|
-
);
|
|
985
|
-
this.backendOpenCalls.delete(output.callId);
|
|
986
|
-
for (const calls of this.backendRunningResponses.values()) calls.delete(output.callId);
|
|
987
|
-
}
|
|
988
|
-
if (outputs.length) {
|
|
989
|
-
this.backendResponsePending = true;
|
|
990
|
-
this.maybeContinueResponse();
|
|
991
|
-
}
|
|
992
|
-
}
|
|
993
|
-
/** Prompt an immediate spoken reply to instructions or the newest typed user message. */
|
|
994
|
-
_generateReply(instructions?: string): void {
|
|
995
|
-
if (instructions !== undefined) {
|
|
996
|
-
this.appendCommentary(`${ASK_INSTRUCTED}\n\n${instructions}`);
|
|
997
|
-
return;
|
|
998
|
-
}
|
|
999
|
-
const newest = this.history.items.at(-1);
|
|
1000
|
-
const typed =
|
|
1001
|
-
newest?.type === 'message' &&
|
|
1002
|
-
newest.role === 'user' &&
|
|
1003
|
-
newest.transcriptConfidence === undefined &&
|
|
1004
|
-
newest.id !== this.askedItemId
|
|
1005
|
-
? newest.textContent
|
|
1006
|
-
: undefined;
|
|
1007
|
-
this.askedItemId = newest?.id;
|
|
1008
|
-
this.appendCommentary(typed ? `${ASK_TYPED}\n\n${typed}` : ASK_BARE);
|
|
1009
|
-
}
|
|
1010
|
-
/** Update backend tool selection for this session and future reconnects. */
|
|
1011
|
-
_updateOptions(options: { toolChoice?: llm.ToolChoice | null }): void {
|
|
1012
|
-
if (options.toolChoice !== undefined) {
|
|
1013
|
-
this.opts.responsesOptions.toolChoice = options.toolChoice;
|
|
1014
|
-
this.sendDelegationUpdate({ tool_choice: toToolChoice(options.toolChoice) });
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
function toToolChoice(choice: llm.ToolChoice | null): NonNullable<ResponsesConfig['tool_choice']> {
|
|
1020
|
-
return typeof choice === 'string'
|
|
1021
|
-
? choice
|
|
1022
|
-
: choice?.type === 'function'
|
|
1023
|
-
? { type: 'function', name: choice.function.name }
|
|
1024
|
-
: 'auto';
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
function renderItem(item: llm.ChatItem): [InputRole, string] | undefined {
|
|
1028
|
-
if (item.type === 'message') {
|
|
1029
|
-
if (item.textContent)
|
|
1030
|
-
return [item.role === 'system' ? 'developer' : item.role, item.textContent];
|
|
1031
|
-
} else if (item.type === 'function_call') {
|
|
1032
|
-
return ['developer', `Called tool ${item.name} with ${item.args}`];
|
|
1033
|
-
} else if (item.type === 'function_call_output') {
|
|
1034
|
-
return [
|
|
1035
|
-
'developer',
|
|
1036
|
-
`Tool ${item.name || item.callId} ${item.isError ? 'failed with' : 'returned'} ${item.output}`,
|
|
1037
|
-
];
|
|
22
|
+
override _providerToolConfig(tool: llm.ProviderTool): OpenAI.Responses.Tool | undefined {
|
|
23
|
+
return tool instanceof OpenAITool
|
|
24
|
+
? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)
|
|
25
|
+
: undefined;
|
|
1038
26
|
}
|
|
1039
|
-
return undefined;
|
|
1040
27
|
}
|