@livekit/agents-plugin-openai 0.0.0-next-20260624041820

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.
Files changed (179) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +18 -0
  3. package/dist/index.cjs +74 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +9 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +30 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/llm.cjs +382 -0
  11. package/dist/llm.cjs.map +1 -0
  12. package/dist/llm.d.cts +230 -0
  13. package/dist/llm.d.ts +230 -0
  14. package/dist/llm.d.ts.map +1 -0
  15. package/dist/llm.js +357 -0
  16. package/dist/llm.js.map +1 -0
  17. package/dist/llm.test.cjs +36 -0
  18. package/dist/llm.test.cjs.map +1 -0
  19. package/dist/llm.test.d.cts +2 -0
  20. package/dist/llm.test.d.ts +2 -0
  21. package/dist/llm.test.d.ts.map +1 -0
  22. package/dist/llm.test.js +35 -0
  23. package/dist/llm.test.js.map +1 -0
  24. package/dist/models.cjs +50 -0
  25. package/dist/models.cjs.map +1 -0
  26. package/dist/models.d.cts +26 -0
  27. package/dist/models.d.ts +26 -0
  28. package/dist/models.d.ts.map +1 -0
  29. package/dist/models.js +25 -0
  30. package/dist/models.js.map +1 -0
  31. package/dist/realtime/api_proto.cjs +41 -0
  32. package/dist/realtime/api_proto.cjs.map +1 -0
  33. package/dist/realtime/api_proto.d.cts +501 -0
  34. package/dist/realtime/api_proto.d.ts +501 -0
  35. package/dist/realtime/api_proto.d.ts.map +1 -0
  36. package/dist/realtime/api_proto.js +13 -0
  37. package/dist/realtime/api_proto.js.map +1 -0
  38. package/dist/realtime/index.cjs +25 -0
  39. package/dist/realtime/index.cjs.map +1 -0
  40. package/dist/realtime/index.d.cts +3 -0
  41. package/dist/realtime/index.d.ts +3 -0
  42. package/dist/realtime/index.d.ts.map +1 -0
  43. package/dist/realtime/index.js +3 -0
  44. package/dist/realtime/index.js.map +1 -0
  45. package/dist/realtime/realtime_model.cjs +1658 -0
  46. package/dist/realtime/realtime_model.cjs.map +1 -0
  47. package/dist/realtime/realtime_model.d.cts +202 -0
  48. package/dist/realtime/realtime_model.d.ts +202 -0
  49. package/dist/realtime/realtime_model.d.ts.map +1 -0
  50. package/dist/realtime/realtime_model.js +1637 -0
  51. package/dist/realtime/realtime_model.js.map +1 -0
  52. package/dist/realtime/realtime_model.test.cjs +596 -0
  53. package/dist/realtime/realtime_model.test.cjs.map +1 -0
  54. package/dist/realtime/realtime_model.test.d.cts +2 -0
  55. package/dist/realtime/realtime_model.test.d.ts +2 -0
  56. package/dist/realtime/realtime_model.test.d.ts.map +1 -0
  57. package/dist/realtime/realtime_model.test.js +600 -0
  58. package/dist/realtime/realtime_model.test.js.map +1 -0
  59. package/dist/responses/index.cjs +23 -0
  60. package/dist/responses/index.cjs.map +1 -0
  61. package/dist/responses/index.d.cts +2 -0
  62. package/dist/responses/index.d.ts +2 -0
  63. package/dist/responses/index.d.ts.map +1 -0
  64. package/dist/responses/index.js +2 -0
  65. package/dist/responses/index.js.map +1 -0
  66. package/dist/responses/llm.cjs +353 -0
  67. package/dist/responses/llm.cjs.map +1 -0
  68. package/dist/responses/llm.d.cts +52 -0
  69. package/dist/responses/llm.d.ts +52 -0
  70. package/dist/responses/llm.d.ts.map +1 -0
  71. package/dist/responses/llm.js +327 -0
  72. package/dist/responses/llm.js.map +1 -0
  73. package/dist/responses/llm.test.cjs +37 -0
  74. package/dist/responses/llm.test.cjs.map +1 -0
  75. package/dist/responses/llm.test.d.cts +2 -0
  76. package/dist/responses/llm.test.d.ts +2 -0
  77. package/dist/responses/llm.test.d.ts.map +1 -0
  78. package/dist/responses/llm.test.js +36 -0
  79. package/dist/responses/llm.test.js.map +1 -0
  80. package/dist/stt.cjs +627 -0
  81. package/dist/stt.cjs.map +1 -0
  82. package/dist/stt.d.cts +105 -0
  83. package/dist/stt.d.ts +105 -0
  84. package/dist/stt.d.ts.map +1 -0
  85. package/dist/stt.js +605 -0
  86. package/dist/stt.js.map +1 -0
  87. package/dist/stt.test.cjs +132 -0
  88. package/dist/stt.test.cjs.map +1 -0
  89. package/dist/stt.test.d.cts +2 -0
  90. package/dist/stt.test.d.ts +2 -0
  91. package/dist/stt.test.d.ts.map +1 -0
  92. package/dist/stt.test.js +131 -0
  93. package/dist/stt.test.js.map +1 -0
  94. package/dist/tool_utils.cjs +53 -0
  95. package/dist/tool_utils.cjs.map +1 -0
  96. package/dist/tool_utils.d.cts +4 -0
  97. package/dist/tool_utils.d.ts +4 -0
  98. package/dist/tool_utils.d.ts.map +1 -0
  99. package/dist/tool_utils.js +29 -0
  100. package/dist/tool_utils.js.map +1 -0
  101. package/dist/tool_utils.test.cjs +77 -0
  102. package/dist/tool_utils.test.cjs.map +1 -0
  103. package/dist/tool_utils.test.d.cts +2 -0
  104. package/dist/tool_utils.test.d.ts +2 -0
  105. package/dist/tool_utils.test.d.ts.map +1 -0
  106. package/dist/tool_utils.test.js +76 -0
  107. package/dist/tool_utils.test.js.map +1 -0
  108. package/dist/tools.cjs +117 -0
  109. package/dist/tools.cjs.map +1 -0
  110. package/dist/tools.d.cts +88 -0
  111. package/dist/tools.d.ts +88 -0
  112. package/dist/tools.d.ts.map +1 -0
  113. package/dist/tools.js +90 -0
  114. package/dist/tools.js.map +1 -0
  115. package/dist/tts.cjs +141 -0
  116. package/dist/tts.cjs.map +1 -0
  117. package/dist/tts.d.cts +42 -0
  118. package/dist/tts.d.ts +42 -0
  119. package/dist/tts.d.ts.map +1 -0
  120. package/dist/tts.js +116 -0
  121. package/dist/tts.js.map +1 -0
  122. package/dist/tts.test.cjs +17 -0
  123. package/dist/tts.test.cjs.map +1 -0
  124. package/dist/tts.test.d.cts +2 -0
  125. package/dist/tts.test.d.ts +2 -0
  126. package/dist/tts.test.d.ts.map +1 -0
  127. package/dist/tts.test.js +16 -0
  128. package/dist/tts.test.js.map +1 -0
  129. package/dist/ws/index.cjs +29 -0
  130. package/dist/ws/index.cjs.map +1 -0
  131. package/dist/ws/index.d.cts +3 -0
  132. package/dist/ws/index.d.ts +3 -0
  133. package/dist/ws/index.d.ts.map +1 -0
  134. package/dist/ws/index.js +5 -0
  135. package/dist/ws/index.js.map +1 -0
  136. package/dist/ws/llm.cjs +523 -0
  137. package/dist/ws/llm.cjs.map +1 -0
  138. package/dist/ws/llm.d.cts +96 -0
  139. package/dist/ws/llm.d.ts +96 -0
  140. package/dist/ws/llm.d.ts.map +1 -0
  141. package/dist/ws/llm.js +505 -0
  142. package/dist/ws/llm.js.map +1 -0
  143. package/dist/ws/llm.test.cjs +69 -0
  144. package/dist/ws/llm.test.cjs.map +1 -0
  145. package/dist/ws/llm.test.d.cts +2 -0
  146. package/dist/ws/llm.test.d.ts +2 -0
  147. package/dist/ws/llm.test.d.ts.map +1 -0
  148. package/dist/ws/llm.test.js +68 -0
  149. package/dist/ws/llm.test.js.map +1 -0
  150. package/dist/ws/types.cjs +129 -0
  151. package/dist/ws/types.cjs.map +1 -0
  152. package/dist/ws/types.d.cts +172 -0
  153. package/dist/ws/types.d.ts +172 -0
  154. package/dist/ws/types.d.ts.map +1 -0
  155. package/dist/ws/types.js +96 -0
  156. package/dist/ws/types.js.map +1 -0
  157. package/package.json +56 -0
  158. package/src/index.ts +25 -0
  159. package/src/llm.test.ts +38 -0
  160. package/src/llm.ts +553 -0
  161. package/src/models.ts +235 -0
  162. package/src/realtime/api_proto.ts +714 -0
  163. package/src/realtime/index.ts +5 -0
  164. package/src/realtime/realtime_model.test.ts +793 -0
  165. package/src/realtime/realtime_model.ts +2116 -0
  166. package/src/responses/index.ts +4 -0
  167. package/src/responses/llm.test.ts +39 -0
  168. package/src/responses/llm.ts +452 -0
  169. package/src/stt.test.ts +167 -0
  170. package/src/stt.ts +793 -0
  171. package/src/tool_utils.test.ts +84 -0
  172. package/src/tool_utils.ts +46 -0
  173. package/src/tools.ts +166 -0
  174. package/src/tts.test.ts +19 -0
  175. package/src/tts.ts +158 -0
  176. package/src/ws/index.ts +17 -0
  177. package/src/ws/llm.test.ts +83 -0
  178. package/src/ws/llm.ts +710 -0
  179. package/src/ws/types.ts +132 -0
package/dist/stt.cjs ADDED
@@ -0,0 +1,627 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var stt_exports = {};
20
+ __export(stt_exports, {
21
+ STT: () => STT,
22
+ SpeechStream: () => SpeechStream,
23
+ _loadRealtimeVad: () => _loadRealtimeVad,
24
+ _normalizeRealtimeTurnDetection: () => _normalizeRealtimeTurnDetection,
25
+ _requiresRealtimeVad: () => _requiresRealtimeVad,
26
+ _validateRealtimeVad: () => _validateRealtimeVad,
27
+ buildRealtimeSttUrl: () => buildRealtimeSttUrl
28
+ });
29
+ module.exports = __toCommonJS(stt_exports);
30
+ var import_agents = require("@livekit/agents");
31
+ var import_openai = require("openai");
32
+ var import_ws = require("ws");
33
+ var import_zod = require("zod");
34
+ const REALTIME_SAMPLE_RATE = 24e3;
35
+ const REALTIME_NUM_CHANNELS = 1;
36
+ const DEFAULT_REALTIME_MODEL = "gpt-realtime-whisper";
37
+ function buildRealtimeSttUrl(baseURL, model) {
38
+ const url = new URL(baseURL || "https://api.openai.com/v1");
39
+ if (url.protocol === "https:") {
40
+ url.protocol = "wss:";
41
+ } else if (url.protocol === "http:") {
42
+ url.protocol = "ws:";
43
+ }
44
+ const path = url.pathname.replace(/\/$/, "");
45
+ if (!path || path === "/v1") {
46
+ url.pathname = `${path}/realtime`;
47
+ } else if (!path.endsWith("/realtime")) {
48
+ url.pathname = `${path}/realtime`;
49
+ }
50
+ url.searchParams.set("intent", "transcription");
51
+ if (url.hostname !== "api.openai.com") {
52
+ url.searchParams.set("model", model);
53
+ }
54
+ return url.toString();
55
+ }
56
+ const DEFAULT_REALTIME_TURN_DETECTION = {
57
+ type: "server_vad",
58
+ threshold: 0.5,
59
+ prefix_padding_ms: 600,
60
+ silence_duration_ms: 350
61
+ };
62
+ const REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION = /* @__PURE__ */ new Set([DEFAULT_REALTIME_MODEL]);
63
+ const realtimeTranscriptionSpeechStartedEventSchema = import_zod.z.object({
64
+ type: import_zod.z.literal("input_audio_buffer.speech_started"),
65
+ item_id: import_zod.z.string().optional(),
66
+ audio_start_ms: import_zod.z.number().optional()
67
+ });
68
+ const realtimeTranscriptionSpeechStoppedEventSchema = import_zod.z.object({
69
+ type: import_zod.z.literal("input_audio_buffer.speech_stopped"),
70
+ item_id: import_zod.z.string().optional(),
71
+ audio_end_ms: import_zod.z.number().optional()
72
+ });
73
+ const realtimeTranscriptionDeltaEventSchema = import_zod.z.object({
74
+ type: import_zod.z.literal("conversation.item.input_audio_transcription.delta"),
75
+ item_id: import_zod.z.string().optional(),
76
+ delta: import_zod.z.string().optional()
77
+ });
78
+ const realtimeTranscriptionCompletedEventSchema = import_zod.z.object({
79
+ type: import_zod.z.literal("conversation.item.input_audio_transcription.completed"),
80
+ item_id: import_zod.z.string().optional(),
81
+ transcript: import_zod.z.string().optional(),
82
+ usage: import_zod.z.object({
83
+ input_tokens: import_zod.z.number().optional(),
84
+ output_tokens: import_zod.z.number().optional()
85
+ }).passthrough().optional()
86
+ });
87
+ const realtimeTranscriptionErrorEventSchema = import_zod.z.object({
88
+ type: import_zod.z.literal("error"),
89
+ error: import_zod.z.object({
90
+ message: import_zod.z.string().optional()
91
+ }).passthrough().optional()
92
+ });
93
+ const knownRealtimeTranscriptionServerEventSchema = import_zod.z.discriminatedUnion("type", [
94
+ realtimeTranscriptionSpeechStartedEventSchema,
95
+ realtimeTranscriptionSpeechStoppedEventSchema,
96
+ realtimeTranscriptionDeltaEventSchema,
97
+ realtimeTranscriptionCompletedEventSchema,
98
+ realtimeTranscriptionErrorEventSchema
99
+ ]);
100
+ const knownRealtimeTranscriptionServerEventTypes = /* @__PURE__ */ new Set([
101
+ "input_audio_buffer.speech_started",
102
+ "input_audio_buffer.speech_stopped",
103
+ "conversation.item.input_audio_transcription.delta",
104
+ "conversation.item.input_audio_transcription.completed",
105
+ "error"
106
+ ]);
107
+ const unknownRealtimeTranscriptionServerEventSchema = import_zod.z.object({
108
+ type: import_zod.z.string().refine((type) => !knownRealtimeTranscriptionServerEventTypes.has(type))
109
+ }).passthrough();
110
+ function parseRealtimeTranscriptionServerEvent(data) {
111
+ const event = JSON.parse(data);
112
+ const knownEvent = knownRealtimeTranscriptionServerEventSchema.safeParse(event);
113
+ if (knownEvent.success) {
114
+ return knownEvent.data;
115
+ }
116
+ return {
117
+ type: "unknown",
118
+ event: unknownRealtimeTranscriptionServerEventSchema.parse(event)
119
+ };
120
+ }
121
+ async function _loadRealtimeVad(vad) {
122
+ if (vad) return vad;
123
+ throw new Error(
124
+ "OpenAI realtime STT models without server-side endpointing must provide a VAD via the `vad` option."
125
+ );
126
+ }
127
+ function _requiresRealtimeVad(model, turnDetection) {
128
+ return turnDetection === null || REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model);
129
+ }
130
+ function _normalizeRealtimeTurnDetection(model, turnDetection) {
131
+ if (turnDetection !== null && REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model)) {
132
+ console.warn(
133
+ `Turn detection is not supported for ${model}; ignoring the provided turnDetection and using plugin-side VAD commits instead.`
134
+ );
135
+ return null;
136
+ }
137
+ return turnDetection;
138
+ }
139
+ function _validateRealtimeVad(model, turnDetection, vad) {
140
+ if (_requiresRealtimeVad(model, turnDetection) && !vad) {
141
+ throw new Error(
142
+ `A VAD instance is required for ${model}. Pass a VAD via the \`vad\` option so the plugin can commit audio at end-of-speech.`
143
+ );
144
+ }
145
+ }
146
+ const defaultSTTOptions = {
147
+ apiKey: process.env.OPENAI_API_KEY,
148
+ language: "en",
149
+ detectLanguage: false,
150
+ model: DEFAULT_REALTIME_MODEL,
151
+ useRealtime: true
152
+ };
153
+ class STT extends import_agents.stt.STT {
154
+ #opts;
155
+ #client;
156
+ #streams = /* @__PURE__ */ new Set();
157
+ label = "openai.STT";
158
+ get model() {
159
+ return this.#opts.model;
160
+ }
161
+ get turnDetection() {
162
+ return this.#opts.turnDetection;
163
+ }
164
+ get provider() {
165
+ try {
166
+ const url = new URL(this.#client.baseURL);
167
+ return url.host;
168
+ } catch {
169
+ return "api.openai.com";
170
+ }
171
+ }
172
+ /**
173
+ * Create a new instance of OpenAI STT.
174
+ *
175
+ * @remarks
176
+ * `apiKey` must be set to your OpenAI API key, either using the argument or by setting the
177
+ * `OPENAI_API_KEY` environment variable.
178
+ */
179
+ constructor(opts = defaultSTTOptions) {
180
+ const useRealtime = opts.useRealtime ?? defaultSTTOptions.useRealtime;
181
+ const model = opts.model ?? (useRealtime ? DEFAULT_REALTIME_MODEL : "whisper-1");
182
+ super({
183
+ streaming: useRealtime,
184
+ interimResults: useRealtime,
185
+ alignedTranscript: false
186
+ });
187
+ const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;
188
+ if (apiKey === void 0) {
189
+ throw new Error("OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY");
190
+ }
191
+ const turnDetection = _normalizeRealtimeTurnDetection(
192
+ model,
193
+ opts.turnDetection !== void 0 ? opts.turnDetection : model === DEFAULT_REALTIME_MODEL ? null : DEFAULT_REALTIME_TURN_DETECTION
194
+ );
195
+ if (useRealtime) {
196
+ _validateRealtimeVad(model, turnDetection, opts.vad);
197
+ }
198
+ this.#opts = {
199
+ ...defaultSTTOptions,
200
+ ...opts,
201
+ apiKey,
202
+ language: (0, import_agents.normalizeLanguage)(opts.language ?? defaultSTTOptions.language),
203
+ model,
204
+ useRealtime,
205
+ turnDetection
206
+ };
207
+ this.#client = this.#opts.client || new import_openai.OpenAI({
208
+ baseURL: this.#opts.baseURL,
209
+ apiKey: this.#opts.apiKey
210
+ });
211
+ }
212
+ /**
213
+ * Create a new instance of Groq STT.
214
+ *
215
+ * @remarks
216
+ * `apiKey` must be set to your Groq API key, either using the argument or by setting the
217
+ * `GROQ_API_KEY` environment variable.
218
+ */
219
+ static withGroq(opts = {}) {
220
+ opts.apiKey = opts.apiKey || process.env.GROQ_API_KEY;
221
+ if (opts.apiKey === void 0) {
222
+ throw new Error("Groq API key is required, whether as an argument or as $GROQ_API_KEY");
223
+ }
224
+ return new STT({
225
+ model: "whisper-large-v3-turbo",
226
+ baseURL: "https://api.groq.com/openai/v1",
227
+ ...opts,
228
+ useRealtime: false
229
+ });
230
+ }
231
+ /**
232
+ * Create a new instance of OVHcloud AI Endpoints STT.
233
+ *
234
+ * @remarks
235
+ * `apiKey` must be set to your OVHcloud AI Endpoints API key, either using the argument or by setting the
236
+ * `OVHCLOUD_API_KEY` environment variable.
237
+ */
238
+ static withOVHcloud(opts = {}) {
239
+ opts.apiKey = opts.apiKey || process.env.OVHCLOUD_API_KEY;
240
+ if (opts.apiKey === void 0) {
241
+ throw new Error(
242
+ "OVHcloud AI Endpoints API key is required, whether as an argument or as $OVHCLOUD_API_KEY"
243
+ );
244
+ }
245
+ return new STT({
246
+ model: "whisper-large-v3-turbo",
247
+ baseURL: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1",
248
+ ...opts,
249
+ useRealtime: false
250
+ });
251
+ }
252
+ #sanitizeOptions(language) {
253
+ if (language) {
254
+ return { ...this.#opts, language: (0, import_agents.normalizeLanguage)(language) };
255
+ } else {
256
+ return this.#opts;
257
+ }
258
+ }
259
+ #createWav(frame) {
260
+ const bitsPerSample = 16;
261
+ const byteRate = frame.sampleRate * frame.channels * bitsPerSample / 8;
262
+ const blockAlign = frame.channels * bitsPerSample / 8;
263
+ const header = Buffer.alloc(44);
264
+ header.write("RIFF", 0);
265
+ header.writeUInt32LE(36 + frame.data.byteLength, 4);
266
+ header.write("WAVE", 8);
267
+ header.write("fmt ", 12);
268
+ header.writeUInt32LE(16, 16);
269
+ header.writeUInt16LE(1, 20);
270
+ header.writeUInt16LE(frame.channels, 22);
271
+ header.writeUInt32LE(frame.sampleRate, 24);
272
+ header.writeUInt32LE(byteRate, 28);
273
+ header.writeUInt16LE(blockAlign, 32);
274
+ header.writeUInt16LE(16, 34);
275
+ header.write("data", 36);
276
+ header.writeUInt32LE(frame.data.byteLength, 40);
277
+ return Buffer.concat([header, Buffer.from(frame.data.buffer)]);
278
+ }
279
+ async _recognize(buffer, abortSignal) {
280
+ const config = this.#sanitizeOptions();
281
+ buffer = (0, import_agents.mergeFrames)(buffer);
282
+ const wavBuffer = this.#createWav(buffer);
283
+ const file = new File([new Uint8Array(wavBuffer)], "audio.wav", { type: "audio/wav" });
284
+ const resp = await this.#client.audio.transcriptions.create(
285
+ {
286
+ file,
287
+ model: this.#opts.model,
288
+ language: config.language,
289
+ prompt: config.prompt,
290
+ response_format: "json"
291
+ },
292
+ {
293
+ signal: abortSignal
294
+ }
295
+ );
296
+ return {
297
+ type: import_agents.stt.SpeechEventType.FINAL_TRANSCRIPT,
298
+ alternatives: [
299
+ {
300
+ text: resp.text || "",
301
+ language: (0, import_agents.normalizeLanguage)(config.language || ""),
302
+ startTime: 0,
303
+ endTime: 0,
304
+ confidence: 0
305
+ }
306
+ ]
307
+ };
308
+ }
309
+ updateOptions(opts) {
310
+ const useRealtime = opts.useRealtime ?? this.#opts.useRealtime;
311
+ const model = opts.model ?? this.#opts.model;
312
+ const turnDetection = _normalizeRealtimeTurnDetection(
313
+ model,
314
+ opts.turnDetection !== void 0 ? opts.turnDetection : opts.model === DEFAULT_REALTIME_MODEL ? null : this.#opts.turnDetection
315
+ );
316
+ if (useRealtime) {
317
+ _validateRealtimeVad(model, turnDetection, opts.vad ?? this.#opts.vad);
318
+ }
319
+ this.#opts = {
320
+ ...this.#opts,
321
+ ...opts,
322
+ apiKey: opts.apiKey ?? this.#opts.apiKey,
323
+ language: opts.language ? (0, import_agents.normalizeLanguage)(opts.language) : this.#opts.language,
324
+ model,
325
+ useRealtime,
326
+ turnDetection
327
+ };
328
+ this.updateCapabilities({
329
+ streaming: useRealtime,
330
+ interimResults: useRealtime
331
+ });
332
+ for (const stream of this.#streams) {
333
+ if (stream.isClosed) {
334
+ this.#streams.delete(stream);
335
+ continue;
336
+ }
337
+ stream.updateOptions(this.#opts);
338
+ }
339
+ }
340
+ stream(options = {}) {
341
+ if (!this.#opts.useRealtime) {
342
+ throw new Error("Streaming is not supported on OpenAI STT unless useRealtime is enabled");
343
+ }
344
+ const stream = new SpeechStream(
345
+ this,
346
+ { ...this.#opts },
347
+ options.connOptions ?? import_agents.DEFAULT_API_CONNECT_OPTIONS,
348
+ () => this.#streams.delete(stream)
349
+ );
350
+ this.#streams.add(stream);
351
+ return stream;
352
+ }
353
+ async close() {
354
+ for (const stream of this.#streams) {
355
+ stream.close();
356
+ }
357
+ this.#streams.clear();
358
+ }
359
+ }
360
+ class SpeechStream extends import_agents.stt.SpeechStream {
361
+ label = "openai.SpeechStream";
362
+ #options;
363
+ #onClose;
364
+ #targetTranscript = "";
365
+ #currentItemId = "";
366
+ #itemAudioTiming = /* @__PURE__ */ new Map();
367
+ #speaking = false;
368
+ constructor(stt2, options, connOptions, onClose = () => {
369
+ }) {
370
+ super(stt2, REALTIME_SAMPLE_RATE, connOptions);
371
+ this.#options = options;
372
+ this.#onClose = onClose;
373
+ }
374
+ updateOptions(options) {
375
+ this.#options = { ...options };
376
+ }
377
+ get isClosed() {
378
+ return this.closed;
379
+ }
380
+ close() {
381
+ super.close();
382
+ this.#onClose();
383
+ }
384
+ async run() {
385
+ _validateRealtimeVad(this.#options.model, this.#options.turnDetection, this.#options.vad);
386
+ const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) ? await _loadRealtimeVad(this.#options.vad) : void 0;
387
+ if (vad) {
388
+ this.#options.vad = vad;
389
+ }
390
+ const vadStream = vad == null ? void 0 : vad.stream();
391
+ const ws = await this.#connect();
392
+ const abort = () => {
393
+ if (ws.readyState < import_ws.WebSocket.CLOSING) {
394
+ ws.close();
395
+ }
396
+ };
397
+ this.abortSignal.addEventListener("abort", abort, { once: true });
398
+ try {
399
+ ws.send(JSON.stringify(this.#sessionUpdateEvent()));
400
+ const tasks = [this.#forwardInput(ws, vadStream), this.#forwardEvents(ws)];
401
+ if (vadStream) {
402
+ tasks.push(this.#forwardVadEvents(ws, vadStream));
403
+ }
404
+ await Promise.all(tasks);
405
+ } finally {
406
+ this.abortSignal.removeEventListener("abort", abort);
407
+ vadStream == null ? void 0 : vadStream.close();
408
+ if (ws.readyState < import_ws.WebSocket.CLOSING) {
409
+ ws.close();
410
+ }
411
+ this.#onClose();
412
+ }
413
+ }
414
+ async #connect() {
415
+ const ws = new import_ws.WebSocket(this.#realtimeUrl(), {
416
+ headers: {
417
+ Authorization: `Bearer ${this.#options.apiKey}`
418
+ }
419
+ });
420
+ await new Promise((resolve, reject) => {
421
+ ws.onopen = () => resolve();
422
+ ws.onerror = (error) => reject(new Error(error.message));
423
+ });
424
+ return ws;
425
+ }
426
+ #realtimeUrl() {
427
+ return buildRealtimeSttUrl(this.#options.baseURL, this.#options.model);
428
+ }
429
+ #sessionUpdateEvent() {
430
+ const transcription = {
431
+ model: this.#options.model,
432
+ ...this.#options.prompt ? { prompt: this.#options.prompt } : {},
433
+ ...!this.#options.detectLanguage && this.#options.language ? { language: this.#options.language } : {}
434
+ };
435
+ return {
436
+ type: "session.update",
437
+ session: {
438
+ type: "transcription",
439
+ audio: {
440
+ input: {
441
+ format: {
442
+ type: "audio/pcm",
443
+ rate: REALTIME_SAMPLE_RATE
444
+ },
445
+ transcription,
446
+ turn_detection: this.#options.turnDetection,
447
+ ...this.#options.noiseReductionType ? { noise_reduction: { type: this.#options.noiseReductionType } } : {}
448
+ }
449
+ }
450
+ }
451
+ };
452
+ }
453
+ async #forwardInput(ws, vadStream) {
454
+ const audioStream = new import_agents.AudioByteStream(
455
+ REALTIME_SAMPLE_RATE,
456
+ REALTIME_NUM_CHANNELS,
457
+ REALTIME_SAMPLE_RATE / 20
458
+ );
459
+ for await (const item of this.input) {
460
+ if (item === SpeechStream.FLUSH_SENTINEL) {
461
+ for (const frame of audioStream.flush()) {
462
+ this.#sendAudioFrame(ws, frame);
463
+ }
464
+ if (this.#options.turnDetection === null) {
465
+ ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
466
+ }
467
+ continue;
468
+ }
469
+ vadStream == null ? void 0 : vadStream.pushFrame(item);
470
+ for (const frame of audioStream.write(item.data.buffer)) {
471
+ this.#sendAudioFrame(ws, frame);
472
+ }
473
+ }
474
+ vadStream == null ? void 0 : vadStream.endInput();
475
+ }
476
+ async #forwardVadEvents(ws, vadStream) {
477
+ for await (const event of vadStream) {
478
+ if (event.type === import_agents.VADEventType.START_OF_SPEECH) {
479
+ this.#emitStartOfSpeech();
480
+ } else if (event.type === import_agents.VADEventType.END_OF_SPEECH && this.#options.turnDetection === null) {
481
+ ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
482
+ }
483
+ }
484
+ }
485
+ async #forwardEvents(ws) {
486
+ var _a;
487
+ for await (const data of this.#messages(ws)) {
488
+ const event = parseRealtimeTranscriptionServerEvent(data);
489
+ switch (event.type) {
490
+ case "input_audio_buffer.speech_started": {
491
+ const itemId = event.item_id ?? "";
492
+ this.#currentItemId = itemId;
493
+ this.#itemAudioTiming.set(itemId, {
494
+ startMs: event.audio_start_ms
495
+ });
496
+ this.#emitStartOfSpeech();
497
+ break;
498
+ }
499
+ case "input_audio_buffer.speech_stopped": {
500
+ const itemId = event.item_id ?? this.#currentItemId;
501
+ const timing = this.#itemAudioTiming.get(itemId) ?? {};
502
+ timing.endMs = event.audio_end_ms;
503
+ this.#itemAudioTiming.set(itemId, timing);
504
+ break;
505
+ }
506
+ case "conversation.item.input_audio_transcription.delta":
507
+ this.#currentItemId = event.item_id ?? this.#currentItemId;
508
+ if (event.delta) {
509
+ this.#targetTranscript += event.delta;
510
+ this.#emitStartOfSpeech();
511
+ this.queue.put(this.#speechEvent(import_agents.stt.SpeechEventType.INTERIM_TRANSCRIPT));
512
+ }
513
+ break;
514
+ case "conversation.item.input_audio_transcription.completed": {
515
+ const itemId = event.item_id ?? this.#currentItemId;
516
+ const transcript = event.transcript ?? "";
517
+ if (transcript) {
518
+ this.#targetTranscript = transcript;
519
+ this.#emitStartOfSpeech();
520
+ this.queue.put(this.#speechEvent(import_agents.stt.SpeechEventType.FINAL_TRANSCRIPT, itemId));
521
+ }
522
+ this.#emitRecognitionUsage(event, itemId);
523
+ this.queue.put({ type: import_agents.stt.SpeechEventType.END_OF_SPEECH });
524
+ this.#targetTranscript = "";
525
+ this.#currentItemId = "";
526
+ this.#speaking = false;
527
+ break;
528
+ }
529
+ case "error": {
530
+ throw new Error(((_a = event.error) == null ? void 0 : _a.message) || "OpenAI realtime transcription error");
531
+ }
532
+ }
533
+ }
534
+ }
535
+ async *#messages(ws) {
536
+ const queue = [];
537
+ const messageEvent = new import_agents.Event();
538
+ let closed = false;
539
+ let error;
540
+ ws.onmessage = (message) => {
541
+ queue.push(
542
+ typeof message.data === "string" ? message.data : Buffer.from(message.data).toString()
543
+ );
544
+ messageEvent.set();
545
+ };
546
+ ws.onclose = () => {
547
+ closed = true;
548
+ messageEvent.set();
549
+ };
550
+ ws.onerror = (event) => {
551
+ error = new Error(event.message);
552
+ closed = true;
553
+ messageEvent.set();
554
+ };
555
+ while (!closed || queue.length > 0) {
556
+ if (queue.length > 0) {
557
+ yield queue.shift();
558
+ continue;
559
+ }
560
+ messageEvent.clear();
561
+ if (closed || queue.length > 0) continue;
562
+ await messageEvent.wait();
563
+ }
564
+ if (error) throw error;
565
+ }
566
+ #sendAudioFrame(ws, frame) {
567
+ if (frame.data.byteLength === 0 || frame.samplesPerChannel === 0) {
568
+ return;
569
+ }
570
+ ws.send(
571
+ JSON.stringify({
572
+ type: "input_audio_buffer.append",
573
+ audio: Buffer.from(
574
+ frame.data.buffer,
575
+ frame.data.byteOffset,
576
+ frame.data.byteLength
577
+ ).toString("base64")
578
+ })
579
+ );
580
+ }
581
+ #emitStartOfSpeech() {
582
+ if (this.#speaking) return;
583
+ this.#speaking = true;
584
+ this.queue.put({ type: import_agents.stt.SpeechEventType.START_OF_SPEECH });
585
+ }
586
+ #speechEvent(type, requestId = this.#currentItemId) {
587
+ return {
588
+ type,
589
+ requestId,
590
+ alternatives: [
591
+ {
592
+ text: this.#targetTranscript,
593
+ language: (0, import_agents.normalizeLanguage)(this.#options.language || ""),
594
+ startTime: 0,
595
+ endTime: 0,
596
+ confidence: 1
597
+ }
598
+ ]
599
+ };
600
+ }
601
+ #emitRecognitionUsage(event, itemId) {
602
+ var _a, _b;
603
+ const timing = this.#itemAudioTiming.get(itemId);
604
+ this.#itemAudioTiming.delete(itemId);
605
+ const audioDuration = (timing == null ? void 0 : timing.startMs) !== void 0 && timing.endMs !== void 0 && timing.endMs > timing.startMs ? (timing.endMs - timing.startMs) / 1e3 : 0;
606
+ this.queue.put({
607
+ type: import_agents.stt.SpeechEventType.RECOGNITION_USAGE,
608
+ requestId: itemId,
609
+ recognitionUsage: {
610
+ audioDuration,
611
+ inputTokens: (_a = event.usage) == null ? void 0 : _a.input_tokens,
612
+ outputTokens: (_b = event.usage) == null ? void 0 : _b.output_tokens
613
+ }
614
+ });
615
+ }
616
+ }
617
+ // Annotate the CommonJS export names for ESM import in node:
618
+ 0 && (module.exports = {
619
+ STT,
620
+ SpeechStream,
621
+ _loadRealtimeVad,
622
+ _normalizeRealtimeTurnDetection,
623
+ _requiresRealtimeVad,
624
+ _validateRealtimeVad,
625
+ buildRealtimeSttUrl
626
+ });
627
+ //# sourceMappingURL=stt.cjs.map