@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,14 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
2
|
var __defProp = Object.defineProperty;
|
|
4
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
6
|
var __copyProps = (to, from, except, desc) => {
|
|
13
7
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
8
|
for (let key of __getOwnPropNames(from))
|
|
@@ -17,1835 +11,13 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
11
|
}
|
|
18
12
|
return to;
|
|
19
13
|
};
|
|
20
|
-
var
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
14
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
28
15
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
16
|
var realtime_model_exports = {};
|
|
30
|
-
__export(realtime_model_exports, {
|
|
31
|
-
DiscardedGeneration: () => DiscardedGeneration,
|
|
32
|
-
RealtimeModel: () => RealtimeModel,
|
|
33
|
-
RealtimeSession: () => RealtimeSession,
|
|
34
|
-
isFatalError: () => isFatalError,
|
|
35
|
-
livekitItemToOpenAIItem: () => livekitItemToOpenAIItem,
|
|
36
|
-
processBaseURL: () => processBaseURL
|
|
37
|
-
});
|
|
38
17
|
module.exports = __toCommonJS(realtime_model_exports);
|
|
39
|
-
|
|
40
|
-
var import_mutex = require("@livekit/mutex");
|
|
41
|
-
var import_rtc_node = require("@livekit/rtc-node");
|
|
42
|
-
var import_ws = require("ws");
|
|
43
|
-
var api_proto = __toESM(require("./api_proto.cjs"), 1);
|
|
44
|
-
const lkOaiDebug = process.env.LK_OPENAI_DEBUG ? Number(process.env.LK_OPENAI_DEBUG) : 0;
|
|
45
|
-
const SAMPLE_RATE = 24e3;
|
|
46
|
-
const NUM_CHANNELS = 1;
|
|
47
|
-
const BASE_URL = "https://api.openai.com/v1";
|
|
48
|
-
const MOCK_AUDIO_ID_PREFIX = "lk_mock_audio_item_";
|
|
49
|
-
class DiscardedGeneration {
|
|
50
|
-
discarded = true;
|
|
51
|
-
}
|
|
52
|
-
const FATAL_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
53
|
-
"insufficient_quota",
|
|
54
|
-
"invalid_api_key",
|
|
55
|
-
"account_deactivated",
|
|
56
|
-
"billing_hard_limit_reached"
|
|
57
|
-
]);
|
|
58
|
-
function isFatalError(error) {
|
|
59
|
-
if (error === null || typeof error !== "object") return false;
|
|
60
|
-
const { code, type } = error;
|
|
61
|
-
const errorCode = typeof code === "string" && code.length > 0 ? code : type;
|
|
62
|
-
return typeof errorCode === "string" && FATAL_ERROR_CODES.has(errorCode);
|
|
63
|
-
}
|
|
64
|
-
class CreateResponseHandle {
|
|
65
|
-
instructions;
|
|
66
|
-
doneFut;
|
|
67
|
-
timeout;
|
|
68
|
-
constructor({ instructions }) {
|
|
69
|
-
this.instructions = instructions;
|
|
70
|
-
this.doneFut = new import_agents.Future();
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
const DEFAULT_FIRST_RETRY_INTERVAL_MS = 100;
|
|
74
|
-
const DEFAULT_TURN_DETECTION = {
|
|
75
|
-
type: "semantic_vad",
|
|
76
|
-
eagerness: "medium",
|
|
77
|
-
create_response: true,
|
|
78
|
-
interrupt_response: true
|
|
79
|
-
};
|
|
80
|
-
const DEFAULT_INPUT_AUDIO_TRANSCRIPTION = {
|
|
81
|
-
model: "gpt-4o-mini-transcribe"
|
|
82
|
-
};
|
|
83
|
-
const DEFAULT_TOOL_CHOICE = "auto";
|
|
84
|
-
const DEFAULT_MAX_RESPONSE_OUTPUT_TOKENS = "inf";
|
|
85
|
-
const AZURE_DEFAULT_INPUT_AUDIO_TRANSCRIPTION = {
|
|
86
|
-
model: "whisper-1"
|
|
87
|
-
};
|
|
88
|
-
const AZURE_DEFAULT_TURN_DETECTION = {
|
|
89
|
-
type: "server_vad",
|
|
90
|
-
threshold: 0.5,
|
|
91
|
-
prefix_padding_ms: 300,
|
|
92
|
-
silence_duration_ms: 200,
|
|
93
|
-
create_response: true
|
|
94
|
-
};
|
|
95
|
-
const DEFAULT_MAX_SESSION_DURATION = 20 * 60 * 1e3;
|
|
96
|
-
const DEFAULT_REALTIME_MODEL_OPTIONS = {
|
|
97
|
-
model: "gpt-realtime",
|
|
98
|
-
voice: "marin",
|
|
99
|
-
inputAudioTranscription: DEFAULT_INPUT_AUDIO_TRANSCRIPTION,
|
|
100
|
-
inputAudioNoiseReduction: void 0,
|
|
101
|
-
turnDetection: DEFAULT_TURN_DETECTION,
|
|
102
|
-
toolChoice: DEFAULT_TOOL_CHOICE,
|
|
103
|
-
maxResponseOutputTokens: DEFAULT_MAX_RESPONSE_OUTPUT_TOKENS,
|
|
104
|
-
maxSessionDuration: DEFAULT_MAX_SESSION_DURATION,
|
|
105
|
-
connOptions: import_agents.DEFAULT_API_CONNECT_OPTIONS,
|
|
106
|
-
modalities: ["text", "audio"],
|
|
107
|
-
tracing: void 0
|
|
108
|
-
};
|
|
109
|
-
class RealtimeModel extends import_agents.llm.RealtimeModel {
|
|
110
|
-
sampleRate = api_proto.SAMPLE_RATE;
|
|
111
|
-
numChannels = api_proto.NUM_CHANNELS;
|
|
112
|
-
inFrameSize = api_proto.IN_FRAME_SIZE;
|
|
113
|
-
outFrameSize = api_proto.OUT_FRAME_SIZE;
|
|
114
|
-
/* @internal */
|
|
115
|
-
_options;
|
|
116
|
-
get model() {
|
|
117
|
-
return this._options.model;
|
|
118
|
-
}
|
|
119
|
-
get provider() {
|
|
120
|
-
try {
|
|
121
|
-
const url = new URL(this._options.baseURL);
|
|
122
|
-
return url.host;
|
|
123
|
-
} catch {
|
|
124
|
-
return "api.openai.com";
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
label() {
|
|
128
|
-
return "openai.RealtimeModel";
|
|
129
|
-
}
|
|
130
|
-
constructor(options = {}) {
|
|
131
|
-
const modalities = options.modalities || DEFAULT_REALTIME_MODEL_OPTIONS.modalities;
|
|
132
|
-
super({
|
|
133
|
-
messageTruncation: true,
|
|
134
|
-
turnDetection: options.turnDetection !== null,
|
|
135
|
-
userTranscription: options.inputAudioTranscription !== null,
|
|
136
|
-
autoToolReplyGeneration: false,
|
|
137
|
-
audioOutput: modalities.includes("audio"),
|
|
138
|
-
manualFunctionCalls: true,
|
|
139
|
-
midSessionChatCtxUpdate: true,
|
|
140
|
-
midSessionInstructionsUpdate: true,
|
|
141
|
-
midSessionToolsUpdate: true,
|
|
142
|
-
perResponseToolChoice: true
|
|
143
|
-
});
|
|
144
|
-
const isAzure = !!(options.apiVersion || options.entraToken || options.azureDeployment);
|
|
145
|
-
if (options.apiKey === "" && !isAzure) {
|
|
146
|
-
throw new Error(
|
|
147
|
-
"OpenAI API key is required, either using the argument or by setting the OPENAI_API_KEY environment variable"
|
|
148
|
-
);
|
|
149
|
-
}
|
|
150
|
-
const apiKey = options.apiKey || process.env.OPENAI_API_KEY;
|
|
151
|
-
if (!apiKey && !isAzure) {
|
|
152
|
-
throw new Error(
|
|
153
|
-
"OpenAI API key is required, either using the argument or by setting the OPENAI_API_KEY environment variable"
|
|
154
|
-
);
|
|
155
|
-
}
|
|
156
|
-
if (!options.baseURL && isAzure) {
|
|
157
|
-
const azureEndpoint = process.env.AZURE_OPENAI_ENDPOINT;
|
|
158
|
-
if (!azureEndpoint) {
|
|
159
|
-
throw new Error(
|
|
160
|
-
"Missing Azure endpoint. Please pass base_url or set AZURE_OPENAI_ENDPOINT environment variable."
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
options.baseURL = `${azureEndpoint.replace(/\/$/, "")}/openai`;
|
|
164
|
-
}
|
|
165
|
-
const { modalities: _, ...optionsWithoutModalities } = options;
|
|
166
|
-
this._options = {
|
|
167
|
-
...DEFAULT_REALTIME_MODEL_OPTIONS,
|
|
168
|
-
...optionsWithoutModalities,
|
|
169
|
-
baseURL: options.baseURL || process.env.OPENAI_BASE_URL || BASE_URL,
|
|
170
|
-
apiKey,
|
|
171
|
-
isAzure,
|
|
172
|
-
model: options.model || DEFAULT_REALTIME_MODEL_OPTIONS.model,
|
|
173
|
-
modalities
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Create a RealtimeModel instance configured for Azure OpenAI Service.
|
|
178
|
-
*
|
|
179
|
-
* @param azureDeployment - The name of your Azure OpenAI deployment.
|
|
180
|
-
* @param azureEndpoint - The endpoint URL for your Azure OpenAI resource. If undefined, will attempt to read from the environment variable AZURE_OPENAI_ENDPOINT.
|
|
181
|
-
* @param apiVersion - **Deprecated.** API version for legacy Azure OpenAI preview models. Will be removed on April 30, 2026. Omit for GA models.
|
|
182
|
-
* @param apiKey - Azure OpenAI API key. If undefined, will attempt to read from the environment variable AZURE_OPENAI_API_KEY.
|
|
183
|
-
* @param entraToken - Azure Entra authentication token. Required if not using API key authentication.
|
|
184
|
-
* @param baseURL - Base URL for the API endpoint. If undefined, constructed from the azure_endpoint.
|
|
185
|
-
* @param voice - Voice setting for audio outputs. Defaults to "marin".
|
|
186
|
-
* @param inputAudioTranscription - Options for transcribing input audio. Defaults to @see DEFAULT_INPUT_AUDIO_TRANSCRIPTION.
|
|
187
|
-
* @param inputAudioNoiseReduction - Options for noise reduction. Defaults to undefined.
|
|
188
|
-
* @param turnDetection - Options for server-based voice activity detection (VAD). Defaults to @see DEFAULT_SERVER_VAD_OPTIONS.
|
|
189
|
-
* @param speed - Speed of the audio output. Defaults to 1.0.
|
|
190
|
-
* @param tracing - Tracing configuration. Defaults to undefined.
|
|
191
|
-
*
|
|
192
|
-
* @returns A RealtimeModel instance configured for Azure OpenAI Service.
|
|
193
|
-
*
|
|
194
|
-
* @throws Error if required Azure parameters are missing or invalid.
|
|
195
|
-
*/
|
|
196
|
-
static withAzure({
|
|
197
|
-
azureDeployment,
|
|
198
|
-
azureEndpoint,
|
|
199
|
-
apiVersion,
|
|
200
|
-
apiKey,
|
|
201
|
-
entraToken,
|
|
202
|
-
baseURL,
|
|
203
|
-
voice = "marin",
|
|
204
|
-
temperature,
|
|
205
|
-
// eslint-disable-line @typescript-eslint/no-unused-vars
|
|
206
|
-
inputAudioTranscription = AZURE_DEFAULT_INPUT_AUDIO_TRANSCRIPTION,
|
|
207
|
-
inputAudioNoiseReduction,
|
|
208
|
-
turnDetection = AZURE_DEFAULT_TURN_DETECTION,
|
|
209
|
-
speed,
|
|
210
|
-
tracing
|
|
211
|
-
}) {
|
|
212
|
-
apiKey = apiKey || process.env.AZURE_OPENAI_API_KEY;
|
|
213
|
-
if (!apiKey && !entraToken) {
|
|
214
|
-
throw new Error(
|
|
215
|
-
"Missing credentials. Please pass one of `apiKey`, `entraToken`, or the `AZURE_OPENAI_API_KEY` environment variable."
|
|
216
|
-
);
|
|
217
|
-
}
|
|
218
|
-
apiVersion = apiVersion || process.env.OPENAI_API_VERSION;
|
|
219
|
-
if (apiVersion) {
|
|
220
|
-
(0, import_agents.log)().warn(
|
|
221
|
-
"The `apiVersion` parameter for Azure OpenAI Realtime is deprecated and will be removed on April 30, 2026. Please use the newer Azure OpenAI Realtime API without specifying an API version."
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
|
-
if (!baseURL) {
|
|
225
|
-
azureEndpoint = azureEndpoint || process.env.AZURE_OPENAI_ENDPOINT;
|
|
226
|
-
if (!azureEndpoint) {
|
|
227
|
-
throw new Error(
|
|
228
|
-
"Missing Azure endpoint. Please pass the `azure_endpoint` parameter or set the `AZURE_OPENAI_ENDPOINT` environment variable."
|
|
229
|
-
);
|
|
230
|
-
}
|
|
231
|
-
baseURL = `${azureEndpoint.replace(/\/$/, "")}/openai`;
|
|
232
|
-
}
|
|
233
|
-
return new RealtimeModel({
|
|
234
|
-
voice,
|
|
235
|
-
inputAudioTranscription,
|
|
236
|
-
inputAudioNoiseReduction,
|
|
237
|
-
turnDetection,
|
|
238
|
-
speed,
|
|
239
|
-
tracing,
|
|
240
|
-
apiKey,
|
|
241
|
-
azureDeployment,
|
|
242
|
-
apiVersion,
|
|
243
|
-
entraToken,
|
|
244
|
-
baseURL
|
|
245
|
-
});
|
|
246
|
-
}
|
|
247
|
-
session() {
|
|
248
|
-
return new RealtimeSession(this);
|
|
249
|
-
}
|
|
250
|
-
async close() {
|
|
251
|
-
return;
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
function normalizeAzureClientEvent(event) {
|
|
255
|
-
const item = event["item"];
|
|
256
|
-
if (!item) return;
|
|
257
|
-
const content = item["content"];
|
|
258
|
-
if (!content) return;
|
|
259
|
-
for (const contentPart of content) {
|
|
260
|
-
if (contentPart["type"] === "output_text") {
|
|
261
|
-
contentPart["type"] = "text";
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
function processBaseURL({
|
|
266
|
-
baseURL,
|
|
267
|
-
model,
|
|
268
|
-
isAzure = false,
|
|
269
|
-
azureDeployment,
|
|
270
|
-
apiVersion
|
|
271
|
-
}) {
|
|
272
|
-
const url = new URL(baseURL);
|
|
273
|
-
if (url.protocol === "https:") {
|
|
274
|
-
url.protocol = "wss:";
|
|
275
|
-
} else if (url.protocol === "http:") {
|
|
276
|
-
url.protocol = "ws:";
|
|
277
|
-
}
|
|
278
|
-
const pathStripped = url.pathname.replace(/\/$/, "");
|
|
279
|
-
if (isAzure) {
|
|
280
|
-
if (["", "/openai"].includes(pathStripped)) {
|
|
281
|
-
url.pathname = pathStripped + (apiVersion ? "/realtime" : "/v1/realtime");
|
|
282
|
-
} else if (pathStripped === "/openai/v1") {
|
|
283
|
-
url.pathname = "/openai/v1/realtime";
|
|
284
|
-
}
|
|
285
|
-
} else if (!url.pathname || ["", "/v1", "/openai", "/openai/v1"].includes(pathStripped)) {
|
|
286
|
-
url.pathname = pathStripped + "/realtime";
|
|
287
|
-
}
|
|
288
|
-
if (isAzure) {
|
|
289
|
-
url.searchParams.delete("api-version");
|
|
290
|
-
}
|
|
291
|
-
const queryParams = {};
|
|
292
|
-
if (isAzure && apiVersion) {
|
|
293
|
-
queryParams["api-version"] = apiVersion;
|
|
294
|
-
if (azureDeployment) {
|
|
295
|
-
queryParams["deployment"] = azureDeployment;
|
|
296
|
-
}
|
|
297
|
-
} else if (isAzure) {
|
|
298
|
-
if (!url.searchParams.has("model") && azureDeployment) {
|
|
299
|
-
queryParams["model"] = azureDeployment;
|
|
300
|
-
}
|
|
301
|
-
} else {
|
|
302
|
-
if (!url.searchParams.has("model")) {
|
|
303
|
-
queryParams["model"] = model;
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
for (const [key, value] of Object.entries(queryParams)) {
|
|
307
|
-
url.searchParams.set(key, value);
|
|
308
|
-
}
|
|
309
|
-
return url.toString();
|
|
310
|
-
}
|
|
311
|
-
class RealtimeSession extends import_agents.llm.RealtimeSession {
|
|
312
|
-
_tools = import_agents.llm.ToolContext.empty();
|
|
313
|
-
remoteChatCtx = new import_agents.llm.RemoteChatContext();
|
|
314
|
-
messageChannel = new import_agents.Queue();
|
|
315
|
-
inputResampler;
|
|
316
|
-
instructions;
|
|
317
|
-
oaiRealtimeModel;
|
|
318
|
-
// Ref: python livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/realtime_model.py - 795-797 lines
|
|
319
|
-
// per-session copy of options so updateOptions can diff against the session's
|
|
320
|
-
// own state instead of the shared model-level state.
|
|
321
|
-
_options;
|
|
322
|
-
currentGeneration;
|
|
323
|
-
responseCreatedFutures = {};
|
|
324
|
-
discardedEventIds = /* @__PURE__ */ new Set();
|
|
325
|
-
textModeRecoveryRetries = 0;
|
|
326
|
-
itemCreateFutures = {};
|
|
327
|
-
itemDeleteFutures = {};
|
|
328
|
-
chatCtxEventFutures = {};
|
|
329
|
-
inputTranscriptAccumulators = /* @__PURE__ */ new Map();
|
|
330
|
-
// Track items that have real server-side audio (created in current session, not restored)
|
|
331
|
-
// Items restored after reconnection are text-only and cannot be truncated
|
|
332
|
-
audioCapableItemIds = /* @__PURE__ */ new Set();
|
|
333
|
-
updateChatCtxLock = new import_mutex.Mutex();
|
|
334
|
-
updateFuncCtxLock = new import_mutex.Mutex();
|
|
335
|
-
// 100ms chunks
|
|
336
|
-
bstream = new import_agents.AudioByteStream(SAMPLE_RATE, NUM_CHANNELS, SAMPLE_RATE / 10);
|
|
337
|
-
pushedDurationMs = 0;
|
|
338
|
-
#logger = (0, import_agents.log)();
|
|
339
|
-
#task;
|
|
340
|
-
#closed = false;
|
|
341
|
-
constructor(realtimeModel) {
|
|
342
|
-
super(realtimeModel);
|
|
343
|
-
this.oaiRealtimeModel = realtimeModel;
|
|
344
|
-
this._options = { ...realtimeModel._options };
|
|
345
|
-
this.#task = import_agents.Task.from(({ signal }) => this.#mainTask(signal));
|
|
346
|
-
this.sendEvent(this.createSessionUpdateEvent());
|
|
347
|
-
}
|
|
348
|
-
hasInflightResponse() {
|
|
349
|
-
return this.currentGeneration !== void 0 || Object.keys(this.responseCreatedFutures).length > 0;
|
|
350
|
-
}
|
|
351
|
-
sendEvent(command) {
|
|
352
|
-
this.messageChannel.put(command);
|
|
353
|
-
}
|
|
354
|
-
createSessionUpdateEvent() {
|
|
355
|
-
const opts = this._options;
|
|
356
|
-
const maxOutputTokens = opts.maxResponseOutputTokens === Infinity ? "inf" : opts.maxResponseOutputTokens;
|
|
357
|
-
if (opts.isAzure && opts.apiVersion) {
|
|
358
|
-
const modalities = opts.modalities.includes("audio") ? ["text", "audio"] : ["text"];
|
|
359
|
-
return {
|
|
360
|
-
type: "session.update",
|
|
361
|
-
session: {
|
|
362
|
-
model: opts.model,
|
|
363
|
-
voice: opts.voice,
|
|
364
|
-
input_audio_format: "pcm16",
|
|
365
|
-
output_audio_format: "pcm16",
|
|
366
|
-
modalities,
|
|
367
|
-
turn_detection: opts.turnDetection,
|
|
368
|
-
input_audio_transcription: opts.inputAudioTranscription,
|
|
369
|
-
tool_choice: toOaiToolChoice(opts.toolChoice),
|
|
370
|
-
max_response_output_tokens: maxOutputTokens,
|
|
371
|
-
speed: opts.speed,
|
|
372
|
-
instructions: this.instructions
|
|
373
|
-
}
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
const audioFormat = { type: "audio/pcm", rate: SAMPLE_RATE };
|
|
377
|
-
const modality = opts.modalities.includes("audio") ? "audio" : "text";
|
|
378
|
-
const includeReasoning = opts.reasoning && opts.model.startsWith("gpt-realtime-2");
|
|
379
|
-
return {
|
|
380
|
-
type: "session.update",
|
|
381
|
-
session: {
|
|
382
|
-
type: "realtime",
|
|
383
|
-
model: opts.model,
|
|
384
|
-
output_modalities: [modality],
|
|
385
|
-
audio: {
|
|
386
|
-
input: {
|
|
387
|
-
format: audioFormat,
|
|
388
|
-
noise_reduction: opts.inputAudioNoiseReduction,
|
|
389
|
-
transcription: opts.inputAudioTranscription,
|
|
390
|
-
turn_detection: opts.turnDetection
|
|
391
|
-
},
|
|
392
|
-
output: {
|
|
393
|
-
format: audioFormat,
|
|
394
|
-
speed: opts.speed,
|
|
395
|
-
voice: opts.voice
|
|
396
|
-
}
|
|
397
|
-
},
|
|
398
|
-
max_output_tokens: maxOutputTokens,
|
|
399
|
-
tool_choice: toOaiToolChoice(opts.toolChoice),
|
|
400
|
-
tracing: opts.tracing,
|
|
401
|
-
instructions: this.instructions,
|
|
402
|
-
...includeReasoning ? { reasoning: opts.reasoning } : {}
|
|
403
|
-
}
|
|
404
|
-
};
|
|
405
|
-
}
|
|
406
|
-
get chatCtx() {
|
|
407
|
-
return this.remoteChatCtx.toChatCtx();
|
|
408
|
-
}
|
|
409
|
-
get tools() {
|
|
410
|
-
return this._tools.copy();
|
|
411
|
-
}
|
|
412
|
-
async updateChatCtx(_chatCtx) {
|
|
413
|
-
const unlock = await this.updateChatCtxLock.lock();
|
|
414
|
-
try {
|
|
415
|
-
const validation = import_agents.llm.validateChatContextStructure(_chatCtx);
|
|
416
|
-
const blockingErrors = validation.issues.filter(
|
|
417
|
-
(issue) => issue.severity === "error" && issue.code !== "timestamp_order"
|
|
418
|
-
);
|
|
419
|
-
const timestampOrderIssue = validation.issues.find(
|
|
420
|
-
(issue) => issue.code === "timestamp_order"
|
|
421
|
-
);
|
|
422
|
-
if (blockingErrors.length > 0) {
|
|
423
|
-
this.#logger.error(
|
|
424
|
-
{ issues: validation.issues, blockingErrors },
|
|
425
|
-
"Invalid chat context supplied to updateChatCtx"
|
|
426
|
-
);
|
|
427
|
-
throw new Error(
|
|
428
|
-
`Invalid chat context: ${validation.errors} errors, ${validation.warnings} warnings`
|
|
429
|
-
);
|
|
430
|
-
}
|
|
431
|
-
if (timestampOrderIssue) {
|
|
432
|
-
this.#logger.warn(
|
|
433
|
-
{ timestampOrderIssue },
|
|
434
|
-
"Proceeding with non-monotonic createdAt ordering in realtime chat context"
|
|
435
|
-
);
|
|
436
|
-
}
|
|
437
|
-
if (lkOaiDebug > 0 && validation.warnings > 0) {
|
|
438
|
-
this.#logger.debug(
|
|
439
|
-
{
|
|
440
|
-
warnings: validation.warnings,
|
|
441
|
-
issues: validation.issues
|
|
442
|
-
},
|
|
443
|
-
"Chat context warnings detected before realtime update"
|
|
444
|
-
);
|
|
445
|
-
}
|
|
446
|
-
const events = await this.createChatCtxUpdateEvents(_chatCtx);
|
|
447
|
-
const futures = [];
|
|
448
|
-
const ownedCreateFutures = {};
|
|
449
|
-
const ownedDeleteFutures = {};
|
|
450
|
-
const ownedEventFutures = {};
|
|
451
|
-
const cleanupFutures = () => {
|
|
452
|
-
for (const [itemId, future] of Object.entries(ownedDeleteFutures)) {
|
|
453
|
-
if (this.itemDeleteFutures[itemId] === future) {
|
|
454
|
-
delete this.itemDeleteFutures[itemId];
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
for (const [itemId, future] of Object.entries(ownedCreateFutures)) {
|
|
458
|
-
if (this.itemCreateFutures[itemId] === future) {
|
|
459
|
-
delete this.itemCreateFutures[itemId];
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
for (const [eventId, future] of Object.entries(ownedEventFutures)) {
|
|
463
|
-
if (this.chatCtxEventFutures[eventId] === future) {
|
|
464
|
-
delete this.chatCtxEventFutures[eventId];
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
};
|
|
468
|
-
for (const event of events) {
|
|
469
|
-
let future;
|
|
470
|
-
if (event.type === "conversation.item.create") {
|
|
471
|
-
future = new import_agents.Future();
|
|
472
|
-
futures.push(future);
|
|
473
|
-
this.itemCreateFutures[event.item.id] = future;
|
|
474
|
-
ownedCreateFutures[event.item.id] = future;
|
|
475
|
-
} else if (event.type == "conversation.item.delete") {
|
|
476
|
-
const existingDeleteFuture = this.itemDeleteFutures[event.item_id];
|
|
477
|
-
if (existingDeleteFuture) {
|
|
478
|
-
futures.push(existingDeleteFuture);
|
|
479
|
-
continue;
|
|
480
|
-
}
|
|
481
|
-
future = new import_agents.Future();
|
|
482
|
-
futures.push(future);
|
|
483
|
-
this.itemDeleteFutures[event.item_id] = future;
|
|
484
|
-
ownedDeleteFutures[event.item_id] = future;
|
|
485
|
-
} else {
|
|
486
|
-
continue;
|
|
487
|
-
}
|
|
488
|
-
if (event.event_id) {
|
|
489
|
-
this.chatCtxEventFutures[event.event_id] = future;
|
|
490
|
-
ownedEventFutures[event.event_id] = future;
|
|
491
|
-
}
|
|
492
|
-
this.sendEvent(event);
|
|
493
|
-
}
|
|
494
|
-
if (futures.length === 0) {
|
|
495
|
-
return;
|
|
496
|
-
}
|
|
497
|
-
const timeoutController = new AbortController();
|
|
498
|
-
const timeoutPromise = (0, import_agents.delay)(5e3, { signal: timeoutController.signal }).then(() => {
|
|
499
|
-
throw new import_agents.llm.RealtimeError("update_chat_ctx timed out.");
|
|
500
|
-
});
|
|
501
|
-
try {
|
|
502
|
-
const results = await Promise.race([
|
|
503
|
-
Promise.allSettled(futures.map((fut) => fut.await)),
|
|
504
|
-
timeoutPromise
|
|
505
|
-
]);
|
|
506
|
-
const rejected = results.filter((result) => result.status === "rejected");
|
|
507
|
-
if (rejected.length > 0) {
|
|
508
|
-
this.#logger.warn(
|
|
509
|
-
{ errors: rejected.map((result) => String(result.reason)) },
|
|
510
|
-
`${this.oaiRealtimeModel.label()} rejected part of a chat context update`
|
|
511
|
-
);
|
|
512
|
-
}
|
|
513
|
-
} finally {
|
|
514
|
-
cleanupFutures();
|
|
515
|
-
if (!timeoutController.signal.aborted) {
|
|
516
|
-
timeoutController.abort();
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
} catch (e) {
|
|
520
|
-
this.#logger.error(e.message);
|
|
521
|
-
throw e;
|
|
522
|
-
} finally {
|
|
523
|
-
unlock();
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
async createChatCtxUpdateEvents(chatCtx, addMockAudio = false) {
|
|
527
|
-
const newChatCtx = chatCtx.copy({
|
|
528
|
-
excludeHandoff: true,
|
|
529
|
-
excludeConfigUpdate: true
|
|
530
|
-
});
|
|
531
|
-
if (addMockAudio) {
|
|
532
|
-
newChatCtx.items.push(createMockAudioItem());
|
|
533
|
-
} else {
|
|
534
|
-
newChatCtx.items = newChatCtx.items.filter(
|
|
535
|
-
(item) => !item.id.startsWith(MOCK_AUDIO_ID_PREFIX)
|
|
536
|
-
);
|
|
537
|
-
}
|
|
538
|
-
const events = [];
|
|
539
|
-
const remoteCtx = this.chatCtx;
|
|
540
|
-
const remoteIds = new Set(remoteCtx.items.map((item) => item.id));
|
|
541
|
-
newChatCtx.items = newChatCtx.items.filter(
|
|
542
|
-
(item) => item.type !== "message" || item.content.length > 0 || remoteIds.has(item.id)
|
|
543
|
-
);
|
|
544
|
-
const diffOps = import_agents.llm.computeChatCtxDiff(remoteCtx, newChatCtx);
|
|
545
|
-
for (const op of diffOps.toRemove) {
|
|
546
|
-
events.push({
|
|
547
|
-
type: "conversation.item.delete",
|
|
548
|
-
item_id: op,
|
|
549
|
-
event_id: (0, import_agents.shortuuid)("chat_ctx_delete_")
|
|
550
|
-
});
|
|
551
|
-
}
|
|
552
|
-
const createItem = async (previousId, id) => {
|
|
553
|
-
const chatItem = newChatCtx.getById(id);
|
|
554
|
-
if (!chatItem) {
|
|
555
|
-
throw new Error(`Chat item ${id} not found`);
|
|
556
|
-
}
|
|
557
|
-
events.push({
|
|
558
|
-
type: "conversation.item.create",
|
|
559
|
-
item: await livekitItemToOpenAIItem(chatItem),
|
|
560
|
-
previous_item_id: previousId ?? void 0,
|
|
561
|
-
event_id: (0, import_agents.shortuuid)("chat_ctx_create_")
|
|
562
|
-
});
|
|
563
|
-
};
|
|
564
|
-
const isContentEmpty = (id) => {
|
|
565
|
-
const remoteItem = remoteCtx.getById(id);
|
|
566
|
-
return (remoteItem == null ? void 0 : remoteItem.type) === "message" && remoteItem.content.length === 0;
|
|
567
|
-
};
|
|
568
|
-
for (const [previousId, id] of diffOps.toCreate) {
|
|
569
|
-
await createItem(previousId, id);
|
|
570
|
-
}
|
|
571
|
-
for (const [previousId, id] of diffOps.toUpdate) {
|
|
572
|
-
if (isContentEmpty(id)) {
|
|
573
|
-
continue;
|
|
574
|
-
}
|
|
575
|
-
events.push({
|
|
576
|
-
type: "conversation.item.delete",
|
|
577
|
-
item_id: id,
|
|
578
|
-
event_id: (0, import_agents.shortuuid)("chat_ctx_delete_")
|
|
579
|
-
});
|
|
580
|
-
await createItem(previousId, id);
|
|
581
|
-
}
|
|
582
|
-
return events;
|
|
583
|
-
}
|
|
584
|
-
async updateTools(_tools) {
|
|
585
|
-
const unlock = await this.updateFuncCtxLock.lock();
|
|
586
|
-
const ev = this.createToolsUpdateEvent(_tools);
|
|
587
|
-
this.sendEvent(ev);
|
|
588
|
-
if (!ev.session.tools) {
|
|
589
|
-
throw new Error("Tools are missing in the session update event");
|
|
590
|
-
}
|
|
591
|
-
const retainedToolNames = new Set(ev.session.tools.map((tool) => tool.name));
|
|
592
|
-
const retainedEntries = _tools.tools.filter(
|
|
593
|
-
(entry) => !import_agents.llm.isFunctionTool(entry) || retainedToolNames.has(entry.name)
|
|
594
|
-
);
|
|
595
|
-
this._tools = new import_agents.llm.ToolContext(retainedEntries);
|
|
596
|
-
unlock();
|
|
597
|
-
}
|
|
598
|
-
createToolsUpdateEvent(_tools) {
|
|
599
|
-
const oaiTools = [];
|
|
600
|
-
for (const t of _tools.flatten()) {
|
|
601
|
-
if (!import_agents.llm.isFunctionTool(t)) continue;
|
|
602
|
-
try {
|
|
603
|
-
const parameters = import_agents.llm.toJsonSchema(
|
|
604
|
-
t.parameters
|
|
605
|
-
);
|
|
606
|
-
oaiTools.push({
|
|
607
|
-
name: t.name,
|
|
608
|
-
description: t.description,
|
|
609
|
-
parameters,
|
|
610
|
-
type: "function"
|
|
611
|
-
});
|
|
612
|
-
} catch (e) {
|
|
613
|
-
this.#logger.error(
|
|
614
|
-
{ name: t.name, tool: t },
|
|
615
|
-
"OpenAI Realtime API doesn't support this tool type"
|
|
616
|
-
);
|
|
617
|
-
continue;
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
|
|
621
|
-
return {
|
|
622
|
-
type: "session.update",
|
|
623
|
-
session: {
|
|
624
|
-
...!isLegacyAzure && { type: "realtime" },
|
|
625
|
-
model: this._options.model,
|
|
626
|
-
tools: oaiTools
|
|
627
|
-
},
|
|
628
|
-
event_id: (0, import_agents.shortuuid)("tools_update_")
|
|
629
|
-
};
|
|
630
|
-
}
|
|
631
|
-
async updateInstructions(_instructions) {
|
|
632
|
-
const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
|
|
633
|
-
const eventId = (0, import_agents.shortuuid)("instructions_update_");
|
|
634
|
-
this.sendEvent({
|
|
635
|
-
type: "session.update",
|
|
636
|
-
session: {
|
|
637
|
-
...!isLegacyAzure && { type: "realtime" },
|
|
638
|
-
instructions: _instructions
|
|
639
|
-
},
|
|
640
|
-
event_id: eventId
|
|
641
|
-
});
|
|
642
|
-
this.instructions = _instructions;
|
|
643
|
-
}
|
|
644
|
-
updateOptions({ toolChoice }) {
|
|
645
|
-
const currentToolChoice = toOaiToolChoice(this._options.toolChoice);
|
|
646
|
-
const nextToolChoice = toOaiToolChoice(toolChoice);
|
|
647
|
-
if (currentToolChoice === nextToolChoice) {
|
|
648
|
-
this._options.toolChoice = toolChoice;
|
|
649
|
-
return;
|
|
650
|
-
}
|
|
651
|
-
const isLegacyAzure = this._options.isAzure && !!this._options.apiVersion;
|
|
652
|
-
const options = {
|
|
653
|
-
...!isLegacyAzure && { type: "realtime" }
|
|
654
|
-
};
|
|
655
|
-
this._options.toolChoice = toolChoice;
|
|
656
|
-
options.tool_choice = toOaiToolChoice(toolChoice);
|
|
657
|
-
this.sendEvent({
|
|
658
|
-
type: "session.update",
|
|
659
|
-
session: options,
|
|
660
|
-
event_id: (0, import_agents.shortuuid)("options_update_")
|
|
661
|
-
});
|
|
662
|
-
}
|
|
663
|
-
pushAudio(frame) {
|
|
664
|
-
for (const f of this.resampleAudio(frame)) {
|
|
665
|
-
for (const nf of this.bstream.write(f.data.buffer)) {
|
|
666
|
-
this.sendEvent({
|
|
667
|
-
type: "input_audio_buffer.append",
|
|
668
|
-
audio: Buffer.from(nf.data.buffer).toString("base64")
|
|
669
|
-
});
|
|
670
|
-
this.pushedDurationMs += nf.samplesPerChannel / nf.sampleRate * 1e3;
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
async commitAudio() {
|
|
675
|
-
if (this.pushedDurationMs > 100) {
|
|
676
|
-
this.sendEvent({
|
|
677
|
-
type: "input_audio_buffer.commit"
|
|
678
|
-
});
|
|
679
|
-
this.pushedDurationMs = 0;
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
async clearAudio() {
|
|
683
|
-
this.sendEvent({
|
|
684
|
-
type: "input_audio_buffer.clear"
|
|
685
|
-
});
|
|
686
|
-
this.pushedDurationMs = 0;
|
|
687
|
-
}
|
|
688
|
-
async generateReply(instructions, options = {}) {
|
|
689
|
-
var _a, _b, _c;
|
|
690
|
-
let responseInstructions = instructions;
|
|
691
|
-
if (instructions && this.instructions) {
|
|
692
|
-
responseInstructions = `${this.instructions}
|
|
693
|
-
${instructions}`;
|
|
694
|
-
}
|
|
695
|
-
const handle = this.createResponse({
|
|
696
|
-
instructions: responseInstructions,
|
|
697
|
-
userInitiated: true
|
|
698
|
-
});
|
|
699
|
-
this.textModeRecoveryRetries = 0;
|
|
700
|
-
const onAbort = () => {
|
|
701
|
-
var _a2;
|
|
702
|
-
const eventId = (_a2 = Object.entries(this.responseCreatedFutures).find(
|
|
703
|
-
([, pendingHandle]) => pendingHandle === handle
|
|
704
|
-
)) == null ? void 0 : _a2[0];
|
|
705
|
-
if (eventId) {
|
|
706
|
-
delete this.responseCreatedFutures[eventId];
|
|
707
|
-
this.discardedEventIds.add(eventId);
|
|
708
|
-
}
|
|
709
|
-
if (handle.timeout) clearTimeout(handle.timeout);
|
|
710
|
-
if (!handle.doneFut.done) {
|
|
711
|
-
handle.doneFut.reject(new Error("generateReply aborted"));
|
|
712
|
-
this.sendEvent({
|
|
713
|
-
type: "response.cancel"
|
|
714
|
-
});
|
|
715
|
-
}
|
|
716
|
-
};
|
|
717
|
-
if ((_a = options.signal) == null ? void 0 : _a.aborted) {
|
|
718
|
-
onAbort();
|
|
719
|
-
} else {
|
|
720
|
-
(_b = options.signal) == null ? void 0 : _b.addEventListener("abort", onAbort, { once: true });
|
|
721
|
-
}
|
|
722
|
-
try {
|
|
723
|
-
return await handle.doneFut.await;
|
|
724
|
-
} finally {
|
|
725
|
-
(_c = options.signal) == null ? void 0 : _c.removeEventListener("abort", onAbort);
|
|
726
|
-
}
|
|
727
|
-
}
|
|
728
|
-
async interrupt() {
|
|
729
|
-
if (!this.hasInflightResponse()) {
|
|
730
|
-
return;
|
|
731
|
-
}
|
|
732
|
-
this.sendEvent({
|
|
733
|
-
type: "response.cancel"
|
|
734
|
-
});
|
|
735
|
-
}
|
|
736
|
-
async truncate(_options) {
|
|
737
|
-
const hasAudioModality = !_options.modalities || _options.modalities.includes("audio");
|
|
738
|
-
const hasServerSideAudio = this.audioCapableItemIds.has(_options.messageId);
|
|
739
|
-
if (hasAudioModality && hasServerSideAudio) {
|
|
740
|
-
const audioEndMs = Number.isFinite(_options.audioEndMs) ? Math.max(0, Math.floor(_options.audioEndMs)) : 0;
|
|
741
|
-
if (audioEndMs > 0) {
|
|
742
|
-
this.sendEvent({
|
|
743
|
-
type: "conversation.item.truncate",
|
|
744
|
-
content_index: 0,
|
|
745
|
-
item_id: _options.messageId,
|
|
746
|
-
audio_end_ms: audioEndMs
|
|
747
|
-
});
|
|
748
|
-
} else {
|
|
749
|
-
this.sendEvent({
|
|
750
|
-
type: "conversation.item.delete",
|
|
751
|
-
item_id: _options.messageId,
|
|
752
|
-
event_id: (0, import_agents.shortuuid)("chat_ctx_delete_")
|
|
753
|
-
});
|
|
754
|
-
}
|
|
755
|
-
} else if (_options.audioTranscript !== void 0) {
|
|
756
|
-
const chatCtx = this.chatCtx.copy();
|
|
757
|
-
const idx = chatCtx.indexById(_options.messageId);
|
|
758
|
-
if (idx !== void 0) {
|
|
759
|
-
const item = chatCtx.items[idx];
|
|
760
|
-
if (item && item.type === "message") {
|
|
761
|
-
const newItem = import_agents.llm.ChatMessage.create({
|
|
762
|
-
...item,
|
|
763
|
-
content: [_options.audioTranscript]
|
|
764
|
-
});
|
|
765
|
-
chatCtx.items[idx] = newItem;
|
|
766
|
-
const events = await this.createChatCtxUpdateEvents(chatCtx);
|
|
767
|
-
for (const ev of events) {
|
|
768
|
-
this.sendEvent(ev);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
loggableEvent(event) {
|
|
775
|
-
const untypedEvent = {};
|
|
776
|
-
for (const [key, value] of Object.entries(event)) {
|
|
777
|
-
if (value !== void 0) {
|
|
778
|
-
untypedEvent[key] = value;
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
if (untypedEvent.audio && typeof untypedEvent.audio === "string") {
|
|
782
|
-
return { ...untypedEvent, audio: "..." };
|
|
783
|
-
}
|
|
784
|
-
if (untypedEvent.delta && typeof untypedEvent.delta === "string" && event.type === "response.audio.delta") {
|
|
785
|
-
return { ...untypedEvent, delta: "..." };
|
|
786
|
-
}
|
|
787
|
-
return untypedEvent;
|
|
788
|
-
}
|
|
789
|
-
closeCurrentGeneration(reason = "provider abandonment") {
|
|
790
|
-
if (this.currentGeneration instanceof DiscardedGeneration) {
|
|
791
|
-
this.currentGeneration = void 0;
|
|
792
|
-
return;
|
|
793
|
-
}
|
|
794
|
-
if (!this.currentGeneration) return;
|
|
795
|
-
for (const gen of this.currentGeneration.messages.values()) {
|
|
796
|
-
gen.textChannel.close();
|
|
797
|
-
gen.audioChannel.close();
|
|
798
|
-
if (!gen.modalities.done) {
|
|
799
|
-
gen.modalities.resolve(this._options.modalities);
|
|
800
|
-
}
|
|
801
|
-
}
|
|
802
|
-
this.currentGeneration.messages.clear();
|
|
803
|
-
this.currentGeneration.messageChannel.close();
|
|
804
|
-
this.currentGeneration.functionChannel.close();
|
|
805
|
-
if (!this.currentGeneration._doneFut.done) {
|
|
806
|
-
this.currentGeneration._doneFut.resolve();
|
|
807
|
-
}
|
|
808
|
-
this.#logger.warn(`In-progress generation discarded due to ${reason}`);
|
|
809
|
-
this.currentGeneration = void 0;
|
|
810
|
-
}
|
|
811
|
-
rejectResponseCreatedFutures(reason) {
|
|
812
|
-
for (const handle of Object.values(this.responseCreatedFutures)) {
|
|
813
|
-
if (!handle.doneFut.done) {
|
|
814
|
-
handle.doneFut.reject(new Error(reason));
|
|
815
|
-
}
|
|
816
|
-
if (handle.timeout) clearTimeout(handle.timeout);
|
|
817
|
-
}
|
|
818
|
-
this.responseCreatedFutures = {};
|
|
819
|
-
}
|
|
820
|
-
async createWsConn() {
|
|
821
|
-
const headers = {
|
|
822
|
-
"User-Agent": "LiveKit-Agents-JS"
|
|
823
|
-
};
|
|
824
|
-
if (this._options.isAzure) {
|
|
825
|
-
if (this._options.entraToken) {
|
|
826
|
-
headers.Authorization = `Bearer ${this._options.entraToken}`;
|
|
827
|
-
} else if (this._options.apiKey) {
|
|
828
|
-
headers["api-key"] = this._options.apiKey;
|
|
829
|
-
} else {
|
|
830
|
-
throw new Error("Microsoft API key or entraToken is required");
|
|
831
|
-
}
|
|
832
|
-
} else {
|
|
833
|
-
if (!this._options.apiKey) {
|
|
834
|
-
throw new Error(
|
|
835
|
-
"OpenAI API key is required but not set. Check OPENAI_API_KEY environment variable."
|
|
836
|
-
);
|
|
837
|
-
}
|
|
838
|
-
headers.Authorization = `Bearer ${this._options.apiKey}`;
|
|
839
|
-
}
|
|
840
|
-
const url = processBaseURL({
|
|
841
|
-
baseURL: this._options.baseURL,
|
|
842
|
-
model: this._options.model,
|
|
843
|
-
isAzure: this._options.isAzure,
|
|
844
|
-
apiVersion: this._options.apiVersion,
|
|
845
|
-
azureDeployment: this._options.azureDeployment
|
|
846
|
-
});
|
|
847
|
-
if (lkOaiDebug) {
|
|
848
|
-
this.#logger.debug(`Connecting to OpenAI Realtime API at ${url}`);
|
|
849
|
-
}
|
|
850
|
-
return new Promise((resolve, reject) => {
|
|
851
|
-
const ws = new import_ws.WebSocket(url, { headers });
|
|
852
|
-
let waiting = true;
|
|
853
|
-
const timeout = setTimeout(() => {
|
|
854
|
-
ws.close();
|
|
855
|
-
reject(new Error("WebSocket connection timeout"));
|
|
856
|
-
}, this._options.connOptions.timeoutMs);
|
|
857
|
-
ws.once("open", () => {
|
|
858
|
-
if (!waiting) return;
|
|
859
|
-
waiting = false;
|
|
860
|
-
clearTimeout(timeout);
|
|
861
|
-
resolve(ws);
|
|
862
|
-
});
|
|
863
|
-
ws.once("close", () => {
|
|
864
|
-
if (!waiting) return;
|
|
865
|
-
waiting = false;
|
|
866
|
-
clearTimeout(timeout);
|
|
867
|
-
reject(new Error("OpenAI Realtime API connection closed"));
|
|
868
|
-
});
|
|
869
|
-
});
|
|
870
|
-
}
|
|
871
|
-
async #mainTask(signal) {
|
|
872
|
-
let reconnecting = false;
|
|
873
|
-
let numRetries = 0;
|
|
874
|
-
let wsConn = null;
|
|
875
|
-
const maxRetries = this._options.connOptions.maxRetry;
|
|
876
|
-
const reconnect = async () => {
|
|
877
|
-
this.#logger.debug(
|
|
878
|
-
{
|
|
879
|
-
maxSessionDuration: this._options.maxSessionDuration
|
|
880
|
-
},
|
|
881
|
-
"Reconnecting to OpenAI Realtime API"
|
|
882
|
-
);
|
|
883
|
-
for (const fut of Object.values(this.itemCreateFutures)) {
|
|
884
|
-
if (!fut.done) fut.reject(new Error("Session reconnected"));
|
|
885
|
-
}
|
|
886
|
-
this.itemCreateFutures = {};
|
|
887
|
-
for (const fut of Object.values(this.itemDeleteFutures)) {
|
|
888
|
-
if (!fut.done) fut.reject(new Error("Session reconnected"));
|
|
889
|
-
}
|
|
890
|
-
this.itemDeleteFutures = {};
|
|
891
|
-
this.rejectResponseCreatedFutures("Session reconnected");
|
|
892
|
-
this.discardedEventIds.clear();
|
|
893
|
-
this.closeCurrentGeneration("session reconnection");
|
|
894
|
-
this.audioCapableItemIds.clear();
|
|
895
|
-
this.resetInputTurnState();
|
|
896
|
-
const events = [];
|
|
897
|
-
events.push(this.createSessionUpdateEvent());
|
|
898
|
-
if (Object.keys(this._tools.functionTools).length > 0) {
|
|
899
|
-
events.push(this.createToolsUpdateEvent(this._tools));
|
|
900
|
-
}
|
|
901
|
-
const chatCtx = this.chatCtx.copy({
|
|
902
|
-
excludeFunctionCall: true,
|
|
903
|
-
excludeInstructions: true,
|
|
904
|
-
excludeEmptyMessage: true
|
|
905
|
-
});
|
|
906
|
-
const oldChatCtx = this.remoteChatCtx;
|
|
907
|
-
this.remoteChatCtx = new import_agents.llm.RemoteChatContext();
|
|
908
|
-
events.push(...await this.createChatCtxUpdateEvents(chatCtx));
|
|
909
|
-
try {
|
|
910
|
-
for (const ev of events) {
|
|
911
|
-
this.emit("openai_client_event_queued", ev);
|
|
912
|
-
if (this._options.isAzure && this._options.apiVersion) {
|
|
913
|
-
normalizeAzureClientEvent(ev);
|
|
914
|
-
}
|
|
915
|
-
wsConn.send(JSON.stringify(ev));
|
|
916
|
-
}
|
|
917
|
-
} catch (error) {
|
|
918
|
-
this.remoteChatCtx = oldChatCtx;
|
|
919
|
-
throw new import_agents.APIConnectionError({
|
|
920
|
-
message: "Failed to send message to OpenAI Realtime API during session re-connection"
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
this.#logger.debug("Reconnected to OpenAI Realtime API");
|
|
924
|
-
this.emit("session_reconnected", {});
|
|
925
|
-
};
|
|
926
|
-
reconnecting = false;
|
|
927
|
-
try {
|
|
928
|
-
while (!this.#closed && !signal.aborted) {
|
|
929
|
-
this.#logger.debug("Creating WebSocket connection to OpenAI Realtime API");
|
|
930
|
-
wsConn = await this.createWsConn();
|
|
931
|
-
if (signal.aborted) break;
|
|
932
|
-
try {
|
|
933
|
-
if (reconnecting) {
|
|
934
|
-
await reconnect();
|
|
935
|
-
if (signal.aborted) break;
|
|
936
|
-
numRetries = 0;
|
|
937
|
-
}
|
|
938
|
-
await this.runWs(wsConn);
|
|
939
|
-
if (signal.aborted) break;
|
|
940
|
-
} catch (error) {
|
|
941
|
-
if (!(0, import_agents.isAPIError)(error)) {
|
|
942
|
-
this.emitError({ error, recoverable: false });
|
|
943
|
-
throw error;
|
|
944
|
-
}
|
|
945
|
-
if (maxRetries === 0 || !error.retryable) {
|
|
946
|
-
this.emitError({ error, recoverable: false });
|
|
947
|
-
throw error;
|
|
948
|
-
}
|
|
949
|
-
if (numRetries === maxRetries) {
|
|
950
|
-
this.emitError({ error, recoverable: false });
|
|
951
|
-
throw new import_agents.APIConnectionError({
|
|
952
|
-
message: `OpenAI Realtime API connection failed after ${numRetries} attempts`,
|
|
953
|
-
options: {
|
|
954
|
-
body: error,
|
|
955
|
-
retryable: false
|
|
956
|
-
}
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
|
-
this.emitError({ error, recoverable: true });
|
|
960
|
-
const retryInterval = numRetries === 0 ? DEFAULT_FIRST_RETRY_INTERVAL_MS : this._options.connOptions.retryIntervalMs;
|
|
961
|
-
this.#logger.warn(
|
|
962
|
-
{
|
|
963
|
-
attempt: numRetries,
|
|
964
|
-
maxRetries,
|
|
965
|
-
error
|
|
966
|
-
},
|
|
967
|
-
`OpenAI Realtime API connection failed, retrying in ${retryInterval / 1e3}s`
|
|
968
|
-
);
|
|
969
|
-
await (0, import_agents.delay)(retryInterval);
|
|
970
|
-
numRetries++;
|
|
971
|
-
}
|
|
972
|
-
reconnecting = true;
|
|
973
|
-
}
|
|
974
|
-
} finally {
|
|
975
|
-
this.closeCurrentGeneration("session close");
|
|
976
|
-
this.rejectResponseCreatedFutures("Realtime session closed");
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
async runWs(wsConn) {
|
|
980
|
-
const forwardEvents = async (signal) => {
|
|
981
|
-
const abortFuture = new import_agents.Future();
|
|
982
|
-
signal.addEventListener("abort", () => abortFuture.resolve());
|
|
983
|
-
while (!this.#closed && wsConn.readyState === import_ws.WebSocket.OPEN && !signal.aborted) {
|
|
984
|
-
try {
|
|
985
|
-
const event = await Promise.race([this.messageChannel.get(), abortFuture.await]);
|
|
986
|
-
if (signal.aborted || abortFuture.done || event === void 0) {
|
|
987
|
-
break;
|
|
988
|
-
}
|
|
989
|
-
if (lkOaiDebug && event.type !== "input_audio_buffer.append") {
|
|
990
|
-
this.#logger.debug(
|
|
991
|
-
{
|
|
992
|
-
eventType: event.type,
|
|
993
|
-
"lk.pii.event": this.loggableEvent(event)
|
|
994
|
-
},
|
|
995
|
-
"sent OpenAI Realtime client event"
|
|
996
|
-
);
|
|
997
|
-
}
|
|
998
|
-
this.emit("openai_client_event_queued", event);
|
|
999
|
-
if (this._options.isAzure && this._options.apiVersion) {
|
|
1000
|
-
normalizeAzureClientEvent(event);
|
|
1001
|
-
}
|
|
1002
|
-
wsConn.send(JSON.stringify(event));
|
|
1003
|
-
} catch (error) {
|
|
1004
|
-
break;
|
|
1005
|
-
}
|
|
1006
|
-
}
|
|
1007
|
-
wsConn.close();
|
|
1008
|
-
};
|
|
1009
|
-
const wsCloseFuture = new import_agents.Future();
|
|
1010
|
-
wsConn.onerror = (error) => {
|
|
1011
|
-
wsCloseFuture.resolve(new import_agents.APIConnectionError({ message: error.message }));
|
|
1012
|
-
};
|
|
1013
|
-
wsConn.onclose = () => {
|
|
1014
|
-
wsCloseFuture.resolve();
|
|
1015
|
-
};
|
|
1016
|
-
wsConn.onmessage = (message) => {
|
|
1017
|
-
const event = JSON.parse(message.data);
|
|
1018
|
-
this.emit("openai_server_event_received", event);
|
|
1019
|
-
if (lkOaiDebug) {
|
|
1020
|
-
this.#logger.debug(
|
|
1021
|
-
{
|
|
1022
|
-
eventType: event.type,
|
|
1023
|
-
"lk.pii.event": this.loggableEvent(event)
|
|
1024
|
-
},
|
|
1025
|
-
"received OpenAI Realtime server event"
|
|
1026
|
-
);
|
|
1027
|
-
}
|
|
1028
|
-
try {
|
|
1029
|
-
switch (event.type) {
|
|
1030
|
-
case "input_audio_buffer.speech_started":
|
|
1031
|
-
this.handleInputAudioBufferSpeechStarted(event);
|
|
1032
|
-
break;
|
|
1033
|
-
case "input_audio_buffer.speech_stopped":
|
|
1034
|
-
this.handleInputAudioBufferSpeechStopped(event);
|
|
1035
|
-
break;
|
|
1036
|
-
case "response.created":
|
|
1037
|
-
this.handleResponseCreated(event);
|
|
1038
|
-
break;
|
|
1039
|
-
case "response.output_item.added":
|
|
1040
|
-
this.handleResponseOutputItemAdded(event);
|
|
1041
|
-
break;
|
|
1042
|
-
case "conversation.item.added":
|
|
1043
|
-
case "conversation.item.created":
|
|
1044
|
-
this.handleConversationItemCreated(event);
|
|
1045
|
-
break;
|
|
1046
|
-
case "conversation.item.deleted":
|
|
1047
|
-
this.handleConversationItemDeleted(event);
|
|
1048
|
-
break;
|
|
1049
|
-
case "conversation.item.input_audio_transcription.delta":
|
|
1050
|
-
this.handleConversationItemInputAudioTranscriptionDelta(event);
|
|
1051
|
-
break;
|
|
1052
|
-
case "conversation.item.input_audio_transcription.completed":
|
|
1053
|
-
this.handleConversationItemInputAudioTranscriptionCompleted(event);
|
|
1054
|
-
break;
|
|
1055
|
-
case "conversation.item.input_audio_transcription.failed":
|
|
1056
|
-
this.handleConversationItemInputAudioTranscriptionFailed(event);
|
|
1057
|
-
break;
|
|
1058
|
-
case "response.content_part.added":
|
|
1059
|
-
this.handleResponseContentPartAdded(event);
|
|
1060
|
-
break;
|
|
1061
|
-
case "response.content_part.done":
|
|
1062
|
-
this.handleResponseContentPartDone(event);
|
|
1063
|
-
break;
|
|
1064
|
-
case "response.output_text.delta":
|
|
1065
|
-
case "response.text.delta":
|
|
1066
|
-
this.handleResponseTextDelta(event);
|
|
1067
|
-
break;
|
|
1068
|
-
case "response.output_text.done":
|
|
1069
|
-
case "response.text.done":
|
|
1070
|
-
this.handleResponseTextDone(event);
|
|
1071
|
-
break;
|
|
1072
|
-
case "response.output_audio_transcript.delta":
|
|
1073
|
-
case "response.audio_transcript.delta":
|
|
1074
|
-
this.handleResponseAudioTranscriptDelta(event);
|
|
1075
|
-
break;
|
|
1076
|
-
case "response.output_audio.delta":
|
|
1077
|
-
case "response.audio.delta":
|
|
1078
|
-
this.handleResponseAudioDelta(event);
|
|
1079
|
-
break;
|
|
1080
|
-
case "response.output_audio_transcript.done":
|
|
1081
|
-
case "response.audio_transcript.done":
|
|
1082
|
-
this.handleResponseAudioTranscriptDone(event);
|
|
1083
|
-
break;
|
|
1084
|
-
case "response.output_audio.done":
|
|
1085
|
-
case "response.audio.done":
|
|
1086
|
-
this.handleResponseAudioDone(event);
|
|
1087
|
-
break;
|
|
1088
|
-
case "response.output_item.done":
|
|
1089
|
-
this.handleResponseOutputItemDone(event);
|
|
1090
|
-
break;
|
|
1091
|
-
case "response.done":
|
|
1092
|
-
this.handleResponseDone(event);
|
|
1093
|
-
break;
|
|
1094
|
-
case "error":
|
|
1095
|
-
this.handleError(event);
|
|
1096
|
-
break;
|
|
1097
|
-
default:
|
|
1098
|
-
if (lkOaiDebug) {
|
|
1099
|
-
this.#logger.debug(`unhandled event: ${event.type}`);
|
|
1100
|
-
}
|
|
1101
|
-
break;
|
|
1102
|
-
}
|
|
1103
|
-
} catch (error) {
|
|
1104
|
-
if ((0, import_agents.isAPIError)(error) && !error.retryable) {
|
|
1105
|
-
wsCloseFuture.resolve(error);
|
|
1106
|
-
wsConn.close();
|
|
1107
|
-
return;
|
|
1108
|
-
}
|
|
1109
|
-
this.#logger.error(
|
|
1110
|
-
{
|
|
1111
|
-
error,
|
|
1112
|
-
"lk.pii.event": event
|
|
1113
|
-
},
|
|
1114
|
-
"Failed to handle OpenAI Realtime API event"
|
|
1115
|
-
);
|
|
1116
|
-
}
|
|
1117
|
-
};
|
|
1118
|
-
const sendTask = import_agents.Task.from(({ signal }) => forwardEvents(signal));
|
|
1119
|
-
const wsTask = import_agents.Task.from(({ signal }) => {
|
|
1120
|
-
const abortPromise = new Promise((resolve) => {
|
|
1121
|
-
signal.addEventListener("abort", () => {
|
|
1122
|
-
resolve();
|
|
1123
|
-
});
|
|
1124
|
-
});
|
|
1125
|
-
return Promise.race([wsCloseFuture.await, abortPromise]);
|
|
1126
|
-
});
|
|
1127
|
-
const waitReconnectTask = import_agents.Task.from(async ({ signal }) => {
|
|
1128
|
-
await (0, import_agents.delay)(this._options.maxSessionDuration, { signal });
|
|
1129
|
-
return new import_agents.APIConnectionError({
|
|
1130
|
-
message: "OpenAI Realtime API connection timeout"
|
|
1131
|
-
});
|
|
1132
|
-
});
|
|
1133
|
-
try {
|
|
1134
|
-
const result = await Promise.race([wsTask.result, sendTask.result, waitReconnectTask.result]);
|
|
1135
|
-
const currentGeneration = this.currentGeneration;
|
|
1136
|
-
if (waitReconnectTask.done && currentGeneration) {
|
|
1137
|
-
if (currentGeneration instanceof DiscardedGeneration) {
|
|
1138
|
-
this.currentGeneration = void 0;
|
|
1139
|
-
} else {
|
|
1140
|
-
await currentGeneration._doneFut.await;
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
if (result instanceof Error) {
|
|
1144
|
-
throw result;
|
|
1145
|
-
}
|
|
1146
|
-
} finally {
|
|
1147
|
-
await (0, import_agents.cancelAndWait)([wsTask, sendTask, waitReconnectTask], 2e3);
|
|
1148
|
-
wsConn.close();
|
|
1149
|
-
}
|
|
1150
|
-
}
|
|
1151
|
-
async close() {
|
|
1152
|
-
this.resetInputTurnState();
|
|
1153
|
-
super.close();
|
|
1154
|
-
this.#closed = true;
|
|
1155
|
-
await this.#task;
|
|
1156
|
-
this.rejectResponseCreatedFutures("Session closed");
|
|
1157
|
-
for (const fut of Object.values(this.itemCreateFutures)) {
|
|
1158
|
-
if (!fut.done) {
|
|
1159
|
-
fut.reject(new Error("Session closed"));
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
this.itemCreateFutures = {};
|
|
1163
|
-
for (const fut of Object.values(this.itemDeleteFutures)) {
|
|
1164
|
-
if (!fut.done) {
|
|
1165
|
-
fut.reject(new Error("Session closed"));
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
this.itemDeleteFutures = {};
|
|
1169
|
-
this.inputTranscriptAccumulators.clear();
|
|
1170
|
-
this.closeCurrentGeneration("Session closed");
|
|
1171
|
-
this.messageChannel.items.length = 0;
|
|
1172
|
-
}
|
|
1173
|
-
resetInputTurnState() {
|
|
1174
|
-
this.inputTranscriptAccumulators.clear();
|
|
1175
|
-
}
|
|
1176
|
-
handleInputAudioBufferSpeechStarted(_event) {
|
|
1177
|
-
this.emit("input_speech_started", {});
|
|
1178
|
-
}
|
|
1179
|
-
handleInputAudioBufferSpeechStopped(_event) {
|
|
1180
|
-
this.emit("input_speech_stopped", {
|
|
1181
|
-
userTranscriptionEnabled: this._options.inputAudioTranscription !== null
|
|
1182
|
-
});
|
|
1183
|
-
}
|
|
1184
|
-
handleResponseCreated(event) {
|
|
1185
|
-
var _a;
|
|
1186
|
-
if (!event.response.id) {
|
|
1187
|
-
throw new Error("response.id is missing");
|
|
1188
|
-
}
|
|
1189
|
-
const clientEventId = (_a = event.response.metadata) == null ? void 0 : _a.client_event_id;
|
|
1190
|
-
if (clientEventId && this.discardedEventIds.has(clientEventId)) {
|
|
1191
|
-
this.discardedEventIds.delete(clientEventId);
|
|
1192
|
-
this.sendEvent({
|
|
1193
|
-
type: "response.cancel",
|
|
1194
|
-
response_id: event.response.id
|
|
1195
|
-
});
|
|
1196
|
-
this.currentGeneration = new DiscardedGeneration();
|
|
1197
|
-
this.#logger.warn("discarding response that arrived after it was timed out or interrupted");
|
|
1198
|
-
return;
|
|
1199
|
-
}
|
|
1200
|
-
const currentGeneration = {
|
|
1201
|
-
messageChannel: import_agents.stream.createStreamChannel(),
|
|
1202
|
-
functionChannel: import_agents.stream.createStreamChannel(),
|
|
1203
|
-
messages: /* @__PURE__ */ new Map(),
|
|
1204
|
-
_doneFut: new import_agents.Future(),
|
|
1205
|
-
_createdTimestamp: Date.now()
|
|
1206
|
-
};
|
|
1207
|
-
this.currentGeneration = currentGeneration;
|
|
1208
|
-
const generationEv = {
|
|
1209
|
-
messageStream: currentGeneration.messageChannel.stream(),
|
|
1210
|
-
functionStream: currentGeneration.functionChannel.stream(),
|
|
1211
|
-
userInitiated: false,
|
|
1212
|
-
responseId: event.response.id
|
|
1213
|
-
};
|
|
1214
|
-
if (clientEventId) {
|
|
1215
|
-
const handle = this.responseCreatedFutures[clientEventId];
|
|
1216
|
-
if (handle) {
|
|
1217
|
-
delete this.responseCreatedFutures[clientEventId];
|
|
1218
|
-
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1219
|
-
generationEv.userInitiated = true;
|
|
1220
|
-
if (!handle.doneFut.done) {
|
|
1221
|
-
handle.doneFut.resolve(generationEv);
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
this.emit("generation_created", generationEv);
|
|
1226
|
-
}
|
|
1227
|
-
handleResponseOutputItemAdded(event) {
|
|
1228
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1229
|
-
if (!this.currentGeneration) {
|
|
1230
|
-
throw new Error("currentGeneration is not set");
|
|
1231
|
-
}
|
|
1232
|
-
if (!event.item.type) {
|
|
1233
|
-
throw new Error("item.type is not set");
|
|
1234
|
-
}
|
|
1235
|
-
const itemType = event.item.type;
|
|
1236
|
-
if (itemType !== "message") {
|
|
1237
|
-
this.textModeRecoveryRetries = 0;
|
|
1238
|
-
return;
|
|
1239
|
-
}
|
|
1240
|
-
const itemId = event.item.id;
|
|
1241
|
-
if (!itemId) {
|
|
1242
|
-
throw new Error("item.id is not set");
|
|
1243
|
-
}
|
|
1244
|
-
const modalitiesFut = new import_agents.Future();
|
|
1245
|
-
const itemGeneration = {
|
|
1246
|
-
messageId: itemId,
|
|
1247
|
-
textChannel: import_agents.stream.createStreamChannel(),
|
|
1248
|
-
audioChannel: import_agents.stream.createStreamChannel(),
|
|
1249
|
-
audioTranscript: "",
|
|
1250
|
-
modalities: modalitiesFut
|
|
1251
|
-
};
|
|
1252
|
-
if (!this.oaiRealtimeModel.capabilities.audioOutput) {
|
|
1253
|
-
itemGeneration.audioChannel.close();
|
|
1254
|
-
modalitiesFut.resolve(["text"]);
|
|
1255
|
-
}
|
|
1256
|
-
this.currentGeneration.messageChannel.write({
|
|
1257
|
-
messageId: itemId,
|
|
1258
|
-
textStream: itemGeneration.textChannel.stream(),
|
|
1259
|
-
audioStream: itemGeneration.audioChannel.stream(),
|
|
1260
|
-
modalities: modalitiesFut.await
|
|
1261
|
-
});
|
|
1262
|
-
this.currentGeneration.messages.set(itemId, itemGeneration);
|
|
1263
|
-
}
|
|
1264
|
-
handleConversationItemCreated(event) {
|
|
1265
|
-
if (!event.item.id) {
|
|
1266
|
-
throw new Error("item.id is not set");
|
|
1267
|
-
}
|
|
1268
|
-
const serverEventType = event.type;
|
|
1269
|
-
const incomingItem = openAIItemToLivekitItem(event.item);
|
|
1270
|
-
const existingItem = this.remoteChatCtx.get(event.item.id);
|
|
1271
|
-
const pendingCreateFuture = this.itemCreateFutures[event.item.id];
|
|
1272
|
-
if (existingItem && serverEventType === "conversation.item.added" && !pendingCreateFuture) {
|
|
1273
|
-
return;
|
|
1274
|
-
}
|
|
1275
|
-
try {
|
|
1276
|
-
this.remoteChatCtx.insert(event.previous_item_id, incomingItem);
|
|
1277
|
-
} catch (error) {
|
|
1278
|
-
this.#logger.error({ error, itemId: event.item.id }, "failed to insert conversation item");
|
|
1279
|
-
}
|
|
1280
|
-
const fut = pendingCreateFuture;
|
|
1281
|
-
if (fut) {
|
|
1282
|
-
if (!fut.done) fut.resolve();
|
|
1283
|
-
delete this.itemCreateFutures[event.item.id];
|
|
1284
|
-
}
|
|
1285
|
-
}
|
|
1286
|
-
handleConversationItemDeleted(event) {
|
|
1287
|
-
if (!event.item_id) {
|
|
1288
|
-
throw new Error("item_id is not set");
|
|
1289
|
-
}
|
|
1290
|
-
this.audioCapableItemIds.delete(event.item_id);
|
|
1291
|
-
this.inputTranscriptAccumulators.delete(event.item_id);
|
|
1292
|
-
try {
|
|
1293
|
-
this.remoteChatCtx.delete(event.item_id);
|
|
1294
|
-
} catch (error) {
|
|
1295
|
-
this.#logger.error({ error, itemId: event.item_id }, "failed to delete conversation item");
|
|
1296
|
-
}
|
|
1297
|
-
const fut = this.itemDeleteFutures[event.item_id];
|
|
1298
|
-
if (fut) {
|
|
1299
|
-
if (!fut.done) fut.resolve();
|
|
1300
|
-
delete this.itemDeleteFutures[event.item_id];
|
|
1301
|
-
}
|
|
1302
|
-
}
|
|
1303
|
-
handleConversationItemInputAudioTranscriptionDelta(event) {
|
|
1304
|
-
if (!event.delta) return;
|
|
1305
|
-
const contentIndex = event.content_index ?? 0;
|
|
1306
|
-
let byIndex = this.inputTranscriptAccumulators.get(event.item_id);
|
|
1307
|
-
if (!byIndex) {
|
|
1308
|
-
byIndex = /* @__PURE__ */ new Map();
|
|
1309
|
-
this.inputTranscriptAccumulators.set(event.item_id, byIndex);
|
|
1310
|
-
}
|
|
1311
|
-
const accumulated = (byIndex.get(contentIndex) ?? "") + event.delta;
|
|
1312
|
-
byIndex.set(contentIndex, accumulated);
|
|
1313
|
-
this.emit("input_audio_transcription_completed", {
|
|
1314
|
-
itemId: event.item_id,
|
|
1315
|
-
transcript: accumulated,
|
|
1316
|
-
isFinal: false
|
|
1317
|
-
});
|
|
1318
|
-
}
|
|
1319
|
-
clearAccumulator(itemId, contentIndex) {
|
|
1320
|
-
const byIndex = this.inputTranscriptAccumulators.get(itemId);
|
|
1321
|
-
if (!byIndex) return void 0;
|
|
1322
|
-
const partial = byIndex.get(contentIndex);
|
|
1323
|
-
byIndex.delete(contentIndex);
|
|
1324
|
-
if (byIndex.size === 0) this.inputTranscriptAccumulators.delete(itemId);
|
|
1325
|
-
return partial;
|
|
1326
|
-
}
|
|
1327
|
-
handleConversationItemInputAudioTranscriptionCompleted(event) {
|
|
1328
|
-
if (event.status === "in_progress") {
|
|
1329
|
-
this.emit("input_audio_transcription_completed", {
|
|
1330
|
-
itemId: event.item_id,
|
|
1331
|
-
transcript: event.transcript,
|
|
1332
|
-
isFinal: false
|
|
1333
|
-
});
|
|
1334
|
-
return;
|
|
1335
|
-
}
|
|
1336
|
-
this.clearAccumulator(event.item_id, event.content_index ?? 0);
|
|
1337
|
-
const remoteItem = this.remoteChatCtx.get(event.item_id);
|
|
1338
|
-
if (remoteItem) {
|
|
1339
|
-
const item = remoteItem.item;
|
|
1340
|
-
if (item instanceof import_agents.llm.ChatMessage) {
|
|
1341
|
-
item.content.push(event.transcript);
|
|
1342
|
-
} else {
|
|
1343
|
-
throw new Error("item is not a chat message");
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
this.emit("input_audio_transcription_completed", {
|
|
1347
|
-
itemId: event.item_id,
|
|
1348
|
-
transcript: event.transcript,
|
|
1349
|
-
isFinal: true
|
|
1350
|
-
});
|
|
1351
|
-
}
|
|
1352
|
-
handleConversationItemInputAudioTranscriptionFailed(event) {
|
|
1353
|
-
this.#logger.error(
|
|
1354
|
-
{ error: event.error },
|
|
1355
|
-
"OpenAI Realtime API failed to transcribe input audio"
|
|
1356
|
-
);
|
|
1357
|
-
this.finalizePartialOnTranscriptionFailure(event.item_id, event.content_index ?? 0);
|
|
1358
|
-
}
|
|
1359
|
-
// Close any open partial stream so consumers waiting for isFinal don't hang.
|
|
1360
|
-
finalizePartialOnTranscriptionFailure(itemId, contentIndex) {
|
|
1361
|
-
const partial = this.clearAccumulator(itemId, contentIndex);
|
|
1362
|
-
if (partial === void 0) return;
|
|
1363
|
-
this.emit("input_audio_transcription_completed", {
|
|
1364
|
-
itemId,
|
|
1365
|
-
transcript: partial,
|
|
1366
|
-
isFinal: true
|
|
1367
|
-
});
|
|
1368
|
-
}
|
|
1369
|
-
handleResponseContentPartAdded(event) {
|
|
1370
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1371
|
-
if (!this.currentGeneration) {
|
|
1372
|
-
throw new Error("currentGeneration is not set");
|
|
1373
|
-
}
|
|
1374
|
-
const itemId = event.item_id;
|
|
1375
|
-
const itemType = event.part.type;
|
|
1376
|
-
const itemGeneration = this.currentGeneration.messages.get(itemId);
|
|
1377
|
-
if (!itemGeneration) {
|
|
1378
|
-
this.#logger.warn(`itemGeneration not found for itemId=${itemId}`);
|
|
1379
|
-
return;
|
|
1380
|
-
}
|
|
1381
|
-
const isTextType = itemType === "text" || itemType === "output_text";
|
|
1382
|
-
if (isTextType && this.oaiRealtimeModel.capabilities.audioOutput) {
|
|
1383
|
-
this.#logger.warn("Text response received from OpenAI Realtime API in audio modality.");
|
|
1384
|
-
}
|
|
1385
|
-
if (!itemGeneration.modalities.done) {
|
|
1386
|
-
const modalityResult = isTextType ? ["text"] : ["audio", "text"];
|
|
1387
|
-
itemGeneration.modalities.resolve(modalityResult);
|
|
1388
|
-
if (!isTextType) {
|
|
1389
|
-
this.audioCapableItemIds.add(itemId);
|
|
1390
|
-
}
|
|
1391
|
-
}
|
|
1392
|
-
if (this.currentGeneration._firstTokenTimestamp === void 0) {
|
|
1393
|
-
this.currentGeneration._firstTokenTimestamp = Date.now();
|
|
1394
|
-
}
|
|
1395
|
-
}
|
|
1396
|
-
handleResponseContentPartDone(event) {
|
|
1397
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1398
|
-
if (!event.part) {
|
|
1399
|
-
return;
|
|
1400
|
-
}
|
|
1401
|
-
if (event.part.type !== "text") {
|
|
1402
|
-
return;
|
|
1403
|
-
}
|
|
1404
|
-
if (!this.currentGeneration) {
|
|
1405
|
-
throw new Error("currentGeneration is not set");
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
handleResponseTextDelta(event) {
|
|
1409
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1410
|
-
if (!this.currentGeneration) {
|
|
1411
|
-
throw new Error("currentGeneration is not set");
|
|
1412
|
-
}
|
|
1413
|
-
const itemGeneration = this.currentGeneration.messages.get(event.item_id);
|
|
1414
|
-
if (!itemGeneration) {
|
|
1415
|
-
throw new Error("itemGeneration is not set");
|
|
1416
|
-
}
|
|
1417
|
-
if (!this.oaiRealtimeModel.capabilities.audioOutput && !this.currentGeneration._firstTokenTimestamp) {
|
|
1418
|
-
this.currentGeneration._firstTokenTimestamp = Date.now();
|
|
1419
|
-
}
|
|
1420
|
-
itemGeneration.textChannel.write(event.delta);
|
|
1421
|
-
itemGeneration.audioTranscript += event.delta;
|
|
1422
|
-
}
|
|
1423
|
-
handleResponseTextDone(_event) {
|
|
1424
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1425
|
-
if (!this.currentGeneration) {
|
|
1426
|
-
throw new Error("currentGeneration is not set");
|
|
1427
|
-
}
|
|
1428
|
-
}
|
|
1429
|
-
handleResponseAudioTranscriptDelta(event) {
|
|
1430
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1431
|
-
if (!this.currentGeneration) {
|
|
1432
|
-
throw new Error("currentGeneration is not set");
|
|
1433
|
-
}
|
|
1434
|
-
const itemId = event.item_id;
|
|
1435
|
-
let delta = event.delta;
|
|
1436
|
-
if (event.start_time !== void 0) {
|
|
1437
|
-
delta = (0, import_agents.createTimedString)({ text: event.delta, startTime: event.start_time });
|
|
1438
|
-
}
|
|
1439
|
-
const itemGeneration = this.currentGeneration.messages.get(itemId);
|
|
1440
|
-
if (!itemGeneration) {
|
|
1441
|
-
throw new Error("itemGeneration is not set");
|
|
1442
|
-
} else {
|
|
1443
|
-
itemGeneration.textChannel.write(delta);
|
|
1444
|
-
itemGeneration.audioTranscript += event.delta;
|
|
1445
|
-
}
|
|
1446
|
-
}
|
|
1447
|
-
handleResponseAudioDelta(event) {
|
|
1448
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1449
|
-
if (!this.currentGeneration) {
|
|
1450
|
-
throw new Error("currentGeneration is not set");
|
|
1451
|
-
}
|
|
1452
|
-
const itemGeneration = this.currentGeneration.messages.get(event.item_id);
|
|
1453
|
-
if (!itemGeneration) {
|
|
1454
|
-
throw new Error("itemGeneration is not set");
|
|
1455
|
-
}
|
|
1456
|
-
if (this.currentGeneration._firstTokenTimestamp === void 0) {
|
|
1457
|
-
this.currentGeneration._firstTokenTimestamp = Date.now();
|
|
1458
|
-
}
|
|
1459
|
-
if (!itemGeneration.modalities.done) {
|
|
1460
|
-
itemGeneration.modalities.resolve(["audio", "text"]);
|
|
1461
|
-
}
|
|
1462
|
-
const binaryString = atob(event.delta);
|
|
1463
|
-
const len = binaryString.length;
|
|
1464
|
-
const bytes = new Uint8Array(len);
|
|
1465
|
-
for (let i = 0; i < len; i++) {
|
|
1466
|
-
bytes[i] = binaryString.charCodeAt(i);
|
|
1467
|
-
}
|
|
1468
|
-
itemGeneration.audioChannel.write(
|
|
1469
|
-
new import_rtc_node.AudioFrame(
|
|
1470
|
-
new Int16Array(bytes.buffer),
|
|
1471
|
-
api_proto.SAMPLE_RATE,
|
|
1472
|
-
api_proto.NUM_CHANNELS,
|
|
1473
|
-
bytes.length / 2
|
|
1474
|
-
)
|
|
1475
|
-
);
|
|
1476
|
-
}
|
|
1477
|
-
handleResponseAudioTranscriptDone(_event) {
|
|
1478
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1479
|
-
if (!this.currentGeneration) {
|
|
1480
|
-
throw new Error("currentGeneration is not set");
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
handleResponseAudioDone(_event) {
|
|
1484
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1485
|
-
if (!this.currentGeneration) {
|
|
1486
|
-
throw new Error("currentGeneration is not set");
|
|
1487
|
-
}
|
|
1488
|
-
}
|
|
1489
|
-
handleResponseOutputItemDone(event) {
|
|
1490
|
-
if (this.currentGeneration instanceof DiscardedGeneration) return;
|
|
1491
|
-
if (!this.currentGeneration) {
|
|
1492
|
-
throw new Error("currentGeneration is not set");
|
|
1493
|
-
}
|
|
1494
|
-
const itemId = event.item.id;
|
|
1495
|
-
const itemType = event.item.type;
|
|
1496
|
-
if (itemType === "function_call") {
|
|
1497
|
-
const item = event.item;
|
|
1498
|
-
if (!item.call_id || !item.name || !item.arguments) {
|
|
1499
|
-
throw new Error("item is not a function call");
|
|
1500
|
-
}
|
|
1501
|
-
this.currentGeneration.functionChannel.write(
|
|
1502
|
-
import_agents.llm.FunctionCall.create({
|
|
1503
|
-
callId: item.call_id,
|
|
1504
|
-
name: item.name,
|
|
1505
|
-
args: item.arguments
|
|
1506
|
-
})
|
|
1507
|
-
);
|
|
1508
|
-
} else if (itemType === "message") {
|
|
1509
|
-
const itemGeneration = this.currentGeneration.messages.get(itemId);
|
|
1510
|
-
if (!itemGeneration) {
|
|
1511
|
-
return;
|
|
1512
|
-
}
|
|
1513
|
-
itemGeneration.textChannel.close();
|
|
1514
|
-
itemGeneration.audioChannel.close();
|
|
1515
|
-
if (!itemGeneration.modalities.done) {
|
|
1516
|
-
itemGeneration.modalities.resolve(this._options.modalities);
|
|
1517
|
-
}
|
|
1518
|
-
}
|
|
1519
|
-
}
|
|
1520
|
-
handleResponseDone(_event) {
|
|
1521
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
|
|
1522
|
-
if (this.currentGeneration instanceof DiscardedGeneration) {
|
|
1523
|
-
this.currentGeneration = void 0;
|
|
1524
|
-
return;
|
|
1525
|
-
}
|
|
1526
|
-
if (!this.currentGeneration) {
|
|
1527
|
-
return;
|
|
1528
|
-
}
|
|
1529
|
-
const createdTimestamp = this.currentGeneration._createdTimestamp;
|
|
1530
|
-
const firstTokenTimestamp = this.currentGeneration._firstTokenTimestamp;
|
|
1531
|
-
this.#logger.debug(
|
|
1532
|
-
{
|
|
1533
|
-
messageCount: this.currentGeneration.messages.size
|
|
1534
|
-
},
|
|
1535
|
-
"Closing generation channels in handleResponseDone"
|
|
1536
|
-
);
|
|
1537
|
-
for (const generation of this.currentGeneration.messages.values()) {
|
|
1538
|
-
generation.textChannel.close();
|
|
1539
|
-
generation.audioChannel.close();
|
|
1540
|
-
if (!generation.modalities.done) {
|
|
1541
|
-
generation.modalities.resolve(this._options.modalities);
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
this.currentGeneration.functionChannel.close();
|
|
1545
|
-
this.currentGeneration.messageChannel.close();
|
|
1546
|
-
for (const itemId of this.currentGeneration.messages.keys()) {
|
|
1547
|
-
const remoteItem = this.remoteChatCtx.get(itemId);
|
|
1548
|
-
if (remoteItem && remoteItem.item instanceof import_agents.llm.ChatMessage) {
|
|
1549
|
-
remoteItem.item.content.push(this.currentGeneration.messages.get(itemId).audioTranscript);
|
|
1550
|
-
}
|
|
1551
|
-
}
|
|
1552
|
-
this.currentGeneration._doneFut.resolve();
|
|
1553
|
-
this.currentGeneration = void 0;
|
|
1554
|
-
const usage = _event.response.usage;
|
|
1555
|
-
const ttftMs = firstTokenTimestamp ? firstTokenTimestamp - createdTimestamp : -1;
|
|
1556
|
-
const durationMs = Date.now() - createdTimestamp;
|
|
1557
|
-
const realtimeMetrics = {
|
|
1558
|
-
type: "realtime_model_metrics",
|
|
1559
|
-
timestamp: createdTimestamp,
|
|
1560
|
-
requestId: _event.response.id || "",
|
|
1561
|
-
ttftMs,
|
|
1562
|
-
durationMs,
|
|
1563
|
-
cancelled: _event.response.status === "cancelled",
|
|
1564
|
-
label: "openai_realtime",
|
|
1565
|
-
inputTokens: (usage == null ? void 0 : usage.input_tokens) ?? 0,
|
|
1566
|
-
outputTokens: (usage == null ? void 0 : usage.output_tokens) ?? 0,
|
|
1567
|
-
totalTokens: (usage == null ? void 0 : usage.total_tokens) ?? 0,
|
|
1568
|
-
tokensPerSecond: durationMs > 0 ? ((usage == null ? void 0 : usage.output_tokens) ?? 0) / (durationMs / 1e3) : 0,
|
|
1569
|
-
inputTokenDetails: {
|
|
1570
|
-
audioTokens: ((_a = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _a.audio_tokens) ?? 0,
|
|
1571
|
-
textTokens: ((_b = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _b.text_tokens) ?? 0,
|
|
1572
|
-
imageTokens: 0,
|
|
1573
|
-
// Not supported yet
|
|
1574
|
-
cachedTokens: ((_c = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _c.cached_tokens) ?? 0,
|
|
1575
|
-
cachedTokensDetails: ((_d = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _d.cached_tokens_details) ? {
|
|
1576
|
-
audioTokens: ((_f = (_e = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _e.cached_tokens_details) == null ? void 0 : _f.audio_tokens) ?? 0,
|
|
1577
|
-
textTokens: ((_h = (_g = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _g.cached_tokens_details) == null ? void 0 : _h.text_tokens) ?? 0,
|
|
1578
|
-
imageTokens: ((_j = (_i = usage == null ? void 0 : usage.input_token_details) == null ? void 0 : _i.cached_tokens_details) == null ? void 0 : _j.image_tokens) ?? 0
|
|
1579
|
-
} : void 0
|
|
1580
|
-
},
|
|
1581
|
-
outputTokenDetails: {
|
|
1582
|
-
textTokens: ((_k = usage == null ? void 0 : usage.output_token_details) == null ? void 0 : _k.text_tokens) ?? 0,
|
|
1583
|
-
audioTokens: ((_l = usage == null ? void 0 : usage.output_token_details) == null ? void 0 : _l.audio_tokens) ?? 0,
|
|
1584
|
-
imageTokens: 0
|
|
1585
|
-
}
|
|
1586
|
-
};
|
|
1587
|
-
this.emit("metrics_collected", realtimeMetrics);
|
|
1588
|
-
this.handleResponseDoneButNotComplete(_event);
|
|
1589
|
-
}
|
|
1590
|
-
handleResponseDoneButNotComplete(event) {
|
|
1591
|
-
if (event.response.status === "completed") {
|
|
1592
|
-
return;
|
|
1593
|
-
}
|
|
1594
|
-
const statusDetails = event.response.status_details;
|
|
1595
|
-
if (event.response.status === "failed") {
|
|
1596
|
-
const errorBody = typeof statusDetails !== "string" && (statusDetails == null ? void 0 : statusDetails.type) === "failed" ? statusDetails.error : void 0;
|
|
1597
|
-
const errorTypeValue = errorBody && "type" in errorBody ? errorBody.type : void 0;
|
|
1598
|
-
const errorType = typeof errorTypeValue === "string" ? errorTypeValue : "unknown";
|
|
1599
|
-
const recoverable = !isFatalError(errorBody);
|
|
1600
|
-
const error = new import_agents.APIError(
|
|
1601
|
-
`OpenAI Realtime API response failed with error type: ${errorType}`,
|
|
1602
|
-
{
|
|
1603
|
-
body: errorBody ?? null,
|
|
1604
|
-
retryable: recoverable
|
|
1605
|
-
}
|
|
1606
|
-
);
|
|
1607
|
-
if (!recoverable) {
|
|
1608
|
-
throw error;
|
|
1609
|
-
}
|
|
1610
|
-
this.emitError({ error, recoverable: true });
|
|
1611
|
-
} else if (event.response.status === "cancelled" || event.response.status === "incomplete") {
|
|
1612
|
-
let statusType;
|
|
1613
|
-
let statusReason;
|
|
1614
|
-
if (typeof statusDetails === "string") {
|
|
1615
|
-
statusType = statusDetails;
|
|
1616
|
-
} else {
|
|
1617
|
-
statusType = statusDetails == null ? void 0 : statusDetails.type;
|
|
1618
|
-
statusReason = statusDetails && "reason" in statusDetails ? statusDetails.reason : void 0;
|
|
1619
|
-
}
|
|
1620
|
-
this.#logger.debug(
|
|
1621
|
-
{
|
|
1622
|
-
eventId: event.response.id,
|
|
1623
|
-
eventResponseStatus: event.response.status,
|
|
1624
|
-
eventResponseStatusType: statusType,
|
|
1625
|
-
eventResponseStatusReason: statusReason
|
|
1626
|
-
},
|
|
1627
|
-
`OpenAI Realtime API response done but not complete with status: ${event.response.status} (type=${statusType}, reason=${statusReason})`
|
|
1628
|
-
);
|
|
1629
|
-
} else {
|
|
1630
|
-
this.#logger.debug({ eventResponseStatus: event.response.status }, "Unknown response status");
|
|
1631
|
-
}
|
|
1632
|
-
}
|
|
1633
|
-
handleError(event) {
|
|
1634
|
-
const eventId = event.error.event_id;
|
|
1635
|
-
if (eventId) {
|
|
1636
|
-
const future = this.chatCtxEventFutures[eventId];
|
|
1637
|
-
if (future) {
|
|
1638
|
-
delete this.chatCtxEventFutures[eventId];
|
|
1639
|
-
if (!future.done) future.reject(new Error(event.error.message));
|
|
1640
|
-
if (!isFatalError(event.error)) return;
|
|
1641
|
-
}
|
|
1642
|
-
}
|
|
1643
|
-
if (event.error.message.startsWith("Cancellation failed")) {
|
|
1644
|
-
return;
|
|
1645
|
-
}
|
|
1646
|
-
this.#logger.error({ error: event.error }, "OpenAI Realtime API returned an error");
|
|
1647
|
-
if (eventId) {
|
|
1648
|
-
const handle = this.responseCreatedFutures[eventId];
|
|
1649
|
-
if (handle) {
|
|
1650
|
-
delete this.responseCreatedFutures[eventId];
|
|
1651
|
-
if (handle.timeout) clearTimeout(handle.timeout);
|
|
1652
|
-
if (!handle.doneFut.done) {
|
|
1653
|
-
handle.doneFut.reject(new Error(event.error.message));
|
|
1654
|
-
}
|
|
1655
|
-
}
|
|
1656
|
-
}
|
|
1657
|
-
const recoverable = !isFatalError(event.error);
|
|
1658
|
-
const error = new import_agents.APIError(event.error.message, {
|
|
1659
|
-
body: event.error,
|
|
1660
|
-
retryable: recoverable
|
|
1661
|
-
});
|
|
1662
|
-
if (!recoverable) {
|
|
1663
|
-
throw error;
|
|
1664
|
-
}
|
|
1665
|
-
this.emitError({ error, recoverable: true });
|
|
1666
|
-
}
|
|
1667
|
-
emitError({ error, recoverable }) {
|
|
1668
|
-
this.emit("error", {
|
|
1669
|
-
type: "realtime_model_error",
|
|
1670
|
-
timestamp: Date.now(),
|
|
1671
|
-
// TODO(brian): add label
|
|
1672
|
-
label: "",
|
|
1673
|
-
error,
|
|
1674
|
-
recoverable
|
|
1675
|
-
});
|
|
1676
|
-
}
|
|
1677
|
-
*resampleAudio(frame) {
|
|
1678
|
-
yield frame;
|
|
1679
|
-
}
|
|
1680
|
-
createResponse({
|
|
1681
|
-
userInitiated,
|
|
1682
|
-
instructions,
|
|
1683
|
-
oldHandle
|
|
1684
|
-
}) {
|
|
1685
|
-
const handle = oldHandle || new CreateResponseHandle({ instructions });
|
|
1686
|
-
if (oldHandle && instructions) {
|
|
1687
|
-
handle.instructions = instructions;
|
|
1688
|
-
}
|
|
1689
|
-
const eventId = (0, import_agents.shortuuid)("response_create_");
|
|
1690
|
-
this.discardedEventIds ??= /* @__PURE__ */ new Set();
|
|
1691
|
-
if (userInitiated) {
|
|
1692
|
-
this.responseCreatedFutures[eventId] = handle;
|
|
1693
|
-
handle.timeout = setTimeout(() => {
|
|
1694
|
-
if (this.responseCreatedFutures[eventId] === handle) {
|
|
1695
|
-
delete this.responseCreatedFutures[eventId];
|
|
1696
|
-
}
|
|
1697
|
-
if (!handle.doneFut.done) {
|
|
1698
|
-
this.discardedEventIds.add(eventId);
|
|
1699
|
-
handle.doneFut.reject(new Error("generateReply timed out."));
|
|
1700
|
-
}
|
|
1701
|
-
}, 1e4);
|
|
1702
|
-
}
|
|
1703
|
-
const response = {};
|
|
1704
|
-
if (instructions) response.instructions = instructions;
|
|
1705
|
-
if (userInitiated) response.metadata = { client_event_id: eventId };
|
|
1706
|
-
this.sendEvent({
|
|
1707
|
-
type: "response.create",
|
|
1708
|
-
event_id: eventId,
|
|
1709
|
-
response: Object.keys(response).length > 0 ? response : void 0
|
|
1710
|
-
});
|
|
1711
|
-
return handle;
|
|
1712
|
-
}
|
|
1713
|
-
}
|
|
1714
|
-
async function livekitItemToOpenAIItem(item) {
|
|
1715
|
-
switch (item.type) {
|
|
1716
|
-
case "function_call":
|
|
1717
|
-
return {
|
|
1718
|
-
id: item.id,
|
|
1719
|
-
type: "function_call",
|
|
1720
|
-
call_id: item.callId,
|
|
1721
|
-
name: item.name,
|
|
1722
|
-
arguments: item.args
|
|
1723
|
-
};
|
|
1724
|
-
case "function_call_output":
|
|
1725
|
-
return {
|
|
1726
|
-
id: item.id,
|
|
1727
|
-
type: "function_call_output",
|
|
1728
|
-
call_id: item.callId,
|
|
1729
|
-
output: item.output
|
|
1730
|
-
};
|
|
1731
|
-
case "message":
|
|
1732
|
-
const role = item.role === "developer" ? "system" : item.role;
|
|
1733
|
-
const contentList = [];
|
|
1734
|
-
for (const c of item.content) {
|
|
1735
|
-
if (typeof c === "string") {
|
|
1736
|
-
contentList.push({
|
|
1737
|
-
type: role === "assistant" ? "output_text" : "input_text",
|
|
1738
|
-
text: c
|
|
1739
|
-
});
|
|
1740
|
-
} else if (c.type === "image_content") {
|
|
1741
|
-
if (role !== "user") continue;
|
|
1742
|
-
const serialized = await import_agents.llm.serializeImage(c);
|
|
1743
|
-
if (serialized.externalUrl) {
|
|
1744
|
-
(0, import_agents.log)().warn("External URL is not supported for input_image in realtime API");
|
|
1745
|
-
continue;
|
|
1746
|
-
}
|
|
1747
|
-
if (!serialized.base64Data) {
|
|
1748
|
-
(0, import_agents.log)().warn("Serialized image has no data bytes");
|
|
1749
|
-
continue;
|
|
1750
|
-
}
|
|
1751
|
-
contentList.push({
|
|
1752
|
-
type: "input_image",
|
|
1753
|
-
image_url: `data:${serialized.mimeType};base64,${serialized.base64Data}`
|
|
1754
|
-
});
|
|
1755
|
-
} else if (c.type === "audio_content") {
|
|
1756
|
-
if (role === "user") {
|
|
1757
|
-
const encodedAudio = Buffer.from((0, import_rtc_node.combineAudioFrames)(c.frame).data).toString("base64");
|
|
1758
|
-
contentList.push({
|
|
1759
|
-
type: "input_audio",
|
|
1760
|
-
audio: encodedAudio
|
|
1761
|
-
});
|
|
1762
|
-
}
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
return {
|
|
1766
|
-
id: item.id,
|
|
1767
|
-
type: "message",
|
|
1768
|
-
role,
|
|
1769
|
-
content: contentList
|
|
1770
|
-
};
|
|
1771
|
-
default:
|
|
1772
|
-
throw new Error(`Unsupported item type: ${item.type}`);
|
|
1773
|
-
}
|
|
1774
|
-
}
|
|
1775
|
-
function openAIItemToLivekitItem(item) {
|
|
1776
|
-
if (!item.id) {
|
|
1777
|
-
throw new Error("item.id is not set");
|
|
1778
|
-
}
|
|
1779
|
-
switch (item.type) {
|
|
1780
|
-
case "function_call":
|
|
1781
|
-
return import_agents.llm.FunctionCall.create({
|
|
1782
|
-
id: item.id,
|
|
1783
|
-
callId: item.call_id,
|
|
1784
|
-
name: item.name,
|
|
1785
|
-
args: item.arguments
|
|
1786
|
-
});
|
|
1787
|
-
case "function_call_output":
|
|
1788
|
-
return import_agents.llm.FunctionCallOutput.create({
|
|
1789
|
-
id: item.id,
|
|
1790
|
-
callId: item.call_id,
|
|
1791
|
-
output: item.output,
|
|
1792
|
-
isError: false
|
|
1793
|
-
});
|
|
1794
|
-
case "message":
|
|
1795
|
-
const content = [];
|
|
1796
|
-
const contents = Array.isArray(item.content) ? item.content : [item.content];
|
|
1797
|
-
for (const c of contents) {
|
|
1798
|
-
if (c.type === "text" || c.type === "input_text" || c.type === "output_text") {
|
|
1799
|
-
content.push(c.text);
|
|
1800
|
-
} else if (c.type === "input_image" && c.image_url) {
|
|
1801
|
-
content.push(
|
|
1802
|
-
import_agents.llm.createImageContent({ image: c.image_url })
|
|
1803
|
-
);
|
|
1804
|
-
}
|
|
1805
|
-
}
|
|
1806
|
-
return import_agents.llm.ChatMessage.create({
|
|
1807
|
-
id: item.id,
|
|
1808
|
-
role: item.role,
|
|
1809
|
-
content
|
|
1810
|
-
});
|
|
1811
|
-
}
|
|
1812
|
-
}
|
|
1813
|
-
function createMockAudioItem(durationSeconds = 2) {
|
|
1814
|
-
const audioData = Buffer.alloc(durationSeconds * SAMPLE_RATE);
|
|
1815
|
-
return import_agents.llm.ChatMessage.create({
|
|
1816
|
-
id: (0, import_agents.shortuuid)(MOCK_AUDIO_ID_PREFIX),
|
|
1817
|
-
role: "user",
|
|
1818
|
-
content: [
|
|
1819
|
-
{
|
|
1820
|
-
type: "audio_content",
|
|
1821
|
-
frame: [
|
|
1822
|
-
new import_rtc_node.AudioFrame(
|
|
1823
|
-
new Int16Array(audioData.buffer),
|
|
1824
|
-
SAMPLE_RATE,
|
|
1825
|
-
NUM_CHANNELS,
|
|
1826
|
-
audioData.length / 2
|
|
1827
|
-
)
|
|
1828
|
-
]
|
|
1829
|
-
}
|
|
1830
|
-
]
|
|
1831
|
-
});
|
|
1832
|
-
}
|
|
1833
|
-
function toOaiToolChoice(toolChoice) {
|
|
1834
|
-
if (typeof toolChoice === "string") {
|
|
1835
|
-
return toolChoice;
|
|
1836
|
-
}
|
|
1837
|
-
if ((toolChoice == null ? void 0 : toolChoice.type) === "function") {
|
|
1838
|
-
return toolChoice.function.name;
|
|
1839
|
-
}
|
|
1840
|
-
return "auto";
|
|
1841
|
-
}
|
|
18
|
+
__reExport(realtime_model_exports, require("@livekit/agents/llm/openai_realtime/realtime_model"), module.exports);
|
|
1842
19
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1843
20
|
0 && (module.exports = {
|
|
1844
|
-
|
|
1845
|
-
RealtimeModel,
|
|
1846
|
-
RealtimeSession,
|
|
1847
|
-
isFatalError,
|
|
1848
|
-
livekitItemToOpenAIItem,
|
|
1849
|
-
processBaseURL
|
|
21
|
+
...require("@livekit/agents/llm/openai_realtime/realtime_model")
|
|
1850
22
|
});
|
|
1851
23
|
//# sourceMappingURL=realtime_model.cjs.map
|