@pipedog/openai 0.0.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/stt.d.ts ADDED
@@ -0,0 +1,409 @@
1
+ /**
2
+ * OpenAI Speech-to-Text service implementations.
3
+ *
4
+ * Provides two STT services:
5
+ *
6
+ * - `OpenAISTTService`: REST-based transcription using the Audio API
7
+ * (Whisper / GPT transcription models).
8
+ * - `OpenAIRealtimeSTTService`: WebSocket-based streaming transcription
9
+ * using the Realtime API in transcription-only mode.
10
+ *
11
+ * Porting notes:
12
+ * - `OpenAISTTService` uses the `openai` JS SDK client built by
13
+ * `BaseWhisperSTTService` (`@pipedog/whisper`).
14
+ * - `OpenAIRealtimeSTTService` uses the global `WebSocket` through
15
+ * `WebsocketService._websocketConnect()`. The `Authorization` header is sent
16
+ * on the opening handshake, which the Bun, Node and Deno `WebSocket`
17
+ * support; on Cloudflare Workers override `_connectWebsocket()` or the
18
+ * connect options to open the socket through `fetch`.
19
+ * - Deprecated APIs are not ported: the `model`, `language`, `prompt`,
20
+ * `temperature` (`OpenAISTTService`) and `model`, `language`, `prompt`,
21
+ * `noiseReduction` (`OpenAIRealtimeSTTService`) constructor options.
22
+ */
23
+ import { type Task } from "@pipedog/asyncio";
24
+ import type { BaseAudioResampler } from "@pipedog/core/audio/resamplers/base_audio_resampler";
25
+ import { type CancelFrame, type EndFrame, type Frame, type STTMetadataFrame } from "@pipedog/core/frames/frames";
26
+ import type { FrameDirection, FrameProcessorSetup } from "@pipedog/core/processors/frame_processor";
27
+ import { STTSettings, type STTSettingsOptions } from "@pipedog/core/services/settings";
28
+ import { WebsocketSTTService, type WebsocketSTTServiceOptions } from "@pipedog/core/services/stt_service";
29
+ import { Language } from "@pipedog/core/transcriptions/language";
30
+ import { type NotGiven } from "@pipedog/core/utils/types";
31
+ import { BaseWhisperSTTService, type BaseWhisperSTTServiceOptions, BaseWhisperSTTSettings, type BaseWhisperSTTSettingsOptions, type Transcription } from "@pipedog/whisper/base_stt";
32
+ type Dict = Record<string, any>;
33
+ export interface OpenAISTTSettingsOptions extends BaseWhisperSTTSettingsOptions {
34
+ /**
35
+ * Words or phrases that guide transcription of the input audio, such as
36
+ * product names or acronyms. Supported by "gpt-transcribe".
37
+ */
38
+ keywords?: string[] | null | NotGiven;
39
+ }
40
+ /**
41
+ * Settings for the OpenAI STT service.
42
+ *
43
+ * - `keywords`: words or phrases that guide transcription of the input
44
+ * audio, such as product names or acronyms. Supported by
45
+ * "gpt-transcribe".
46
+ */
47
+ export declare class OpenAISTTSettings extends BaseWhisperSTTSettings {
48
+ keywords: string[] | null | NotGiven;
49
+ constructor(options?: OpenAISTTSettingsOptions);
50
+ }
51
+ export interface OpenAISTTServiceOptions extends BaseWhisperSTTServiceOptions {
52
+ /** Runtime-updatable settings. */
53
+ settings?: OpenAISTTSettings | null;
54
+ }
55
+ /**
56
+ * OpenAI Speech-to-Text service that generates text from audio.
57
+ *
58
+ * Uses OpenAI's transcription API to convert audio to text. Requires an
59
+ * OpenAI API key set via the apiKey option or OPENAI_API_KEY environment
60
+ * variable.
61
+ *
62
+ * With `includeProbMetrics: true`, GPT transcription models report per-token
63
+ * logprobs and Whisper models report per-segment logprobs. Diarization models
64
+ * support neither, so they report no probabilities.
65
+ */
66
+ export declare class OpenAISTTService extends BaseWhisperSTTService {
67
+ static Settings: typeof OpenAISTTSettings;
68
+ protected _settings: OpenAISTTSettings;
69
+ /**
70
+ * Model already reported as unable to supply probabilities, so that warning
71
+ * is logged once per model rather than once per utterance.
72
+ */
73
+ protected _probMetricsWarnedModel: string | null;
74
+ /**
75
+ * Initialize OpenAI STT service.
76
+ *
77
+ * @param options.apiKey OpenAI API key. Defaults to null.
78
+ * @param options.baseUrl API base URL. Defaults to null.
79
+ * @param options.settings Runtime-updatable settings. Its given fields
80
+ * override the defaults (model "gpt-transcribe", language English).
81
+ * @param options.ttfsP99Latency P99 latency from speech end to final
82
+ * transcript in seconds. Override for your deployment. See
83
+ * https://github.com/pipecat-ai/stt-benchmark
84
+ * Other options are passed to BaseWhisperSTTService.
85
+ */
86
+ constructor(options?: OpenAISTTServiceOptions);
87
+ protected _transcribe(audio: Uint8Array): Promise<Transcription>;
88
+ }
89
+ export type OpenAIRealtimeNoiseReduction = "near_field" | "far_field";
90
+ export type OpenAIRealtimeDelay = "minimal" | "low" | "medium" | "high" | "xhigh";
91
+ export interface OpenAIRealtimeSTTSettingsOptions extends STTSettingsOptions {
92
+ /**
93
+ * Optional prompt text to guide transcription style. Not supported by
94
+ * "gpt-realtime-whisper".
95
+ */
96
+ prompt?: string | null | NotGiven;
97
+ /**
98
+ * Noise reduction mode. "near_field" for close microphones, "far_field"
99
+ * for distant microphones, or null to disable.
100
+ */
101
+ noiseReduction?: OpenAIRealtimeNoiseReduction | null | NotGiven;
102
+ /**
103
+ * How long the model waits before emitting transcription text, trading
104
+ * latency for accuracy. Only supported by "gpt-realtime-whisper".
105
+ */
106
+ delay?: OpenAIRealtimeDelay | null | NotGiven;
107
+ }
108
+ /**
109
+ * Settings for OpenAIRealtimeSTTService.
110
+ *
111
+ * - `prompt`: optional prompt text to guide transcription style. Not
112
+ * supported by "gpt-realtime-whisper".
113
+ * - `noiseReduction`: noise reduction mode. "near_field" for close
114
+ * microphones, "far_field" for distant microphones, or null to disable.
115
+ * - `delay`: how long the model waits before emitting transcription text,
116
+ * trading latency for accuracy. Only supported by "gpt-realtime-whisper".
117
+ */
118
+ export declare class OpenAIRealtimeSTTSettings extends STTSettings {
119
+ prompt: string | null | NotGiven;
120
+ noiseReduction: OpenAIRealtimeNoiseReduction | null | NotGiven;
121
+ delay: OpenAIRealtimeDelay | null | NotGiven;
122
+ constructor(options?: OpenAIRealtimeSTTSettingsOptions);
123
+ }
124
+ export interface OpenAIRealtimeSTTServiceOptions extends WebsocketSTTServiceOptions {
125
+ /** OpenAI API key for authentication. */
126
+ apiKey: string;
127
+ /**
128
+ * WebSocket base URL for the Realtime API. Defaults to
129
+ * "wss://api.openai.com/v1/realtime".
130
+ */
131
+ baseUrl?: string;
132
+ /**
133
+ * Server-side VAD configuration. Defaults to `false` (disabled), which
134
+ * relies on a local VAD processor in the pipeline. Pass an object to enable
135
+ * it — at minimum `{ type: "server_vad" }`, optionally with custom settings
136
+ * (e.g. `{ type: "server_vad", threshold: 0.5 }`). Requires a model that
137
+ * supports turn detection. `null` omits the field entirely, leaving the
138
+ * session's own default in place.
139
+ */
140
+ turnDetection?: Dict | false | null;
141
+ /**
142
+ * Whether to interrupt bot output when speech is detected by server-side
143
+ * VAD. Only applies when turn detection is enabled. Passed along to the
144
+ * user turn strategies this service recommends, which own the
145
+ * interruption; a user-supplied `userTurnStrategies` overrides the
146
+ * recommendation and this setting with it. Defaults to true.
147
+ */
148
+ shouldInterrupt?: boolean;
149
+ /** Runtime-updatable settings. */
150
+ settings?: OpenAIRealtimeSTTSettings | null;
151
+ }
152
+ /**
153
+ * OpenAI Realtime Speech-to-Text service using WebSocket transcription sessions.
154
+ *
155
+ * Uses OpenAI's Realtime API in transcription-only mode for real-time
156
+ * streaming speech recognition with optional server-side VAD and noise
157
+ * reduction. The model does not generate conversational responses — only
158
+ * transcription output.
159
+ *
160
+ * This service supports two VAD modes:
161
+ *
162
+ * **Local VAD** (default): Disable server-side VAD and use a local VAD
163
+ * processor in the pipeline instead. When a `VADUserStoppedSpeakingFrame` is
164
+ * received, the service commits the audio buffer so that the server begins
165
+ * transcription for the completed speech segment.
166
+ *
167
+ * **Server-side VAD** (`turnDetection: { type: "server_vad" }`): The OpenAI
168
+ * server performs voice-activity detection. The service proposes turn
169
+ * boundaries when the server detects them, and recommends the external user
170
+ * turn strategies that resolve those proposals into turn frames. Do **not**
171
+ * use a separate VAD processor in the pipeline in this mode. Requires a model
172
+ * that supports turn detection — `gpt-transcribe` does, the default
173
+ * `gpt-realtime-whisper` does not.
174
+ *
175
+ * Audio is sent as 24 kHz 16-bit mono PCM as required by the OpenAI Realtime
176
+ * API. If the pipeline runs at a different sample rate (e.g. 16 kHz for
177
+ * Silero VAD compatibility), audio is automatically upsampled before sending.
178
+ *
179
+ * @example
180
+ * const stt = new OpenAIRealtimeSTTService({
181
+ * apiKey: "sk-...",
182
+ * settings: new OpenAIRealtimeSTTService.Settings({
183
+ * model: "gpt-realtime-whisper",
184
+ * noiseReduction: "near_field",
185
+ * }),
186
+ * });
187
+ */
188
+ export declare class OpenAIRealtimeSTTService extends WebsocketSTTService {
189
+ static Settings: typeof OpenAIRealtimeSTTSettings;
190
+ protected _settings: OpenAIRealtimeSTTSettings;
191
+ protected _apiKey: string;
192
+ protected _baseUrl: string;
193
+ protected _turnDetection: Dict | false | null;
194
+ protected _shouldInterrupt: boolean;
195
+ protected _receiveTask: Task<unknown> | null;
196
+ protected _sessionReady: boolean;
197
+ protected _resampler: BaseAudioResampler;
198
+ protected _serverVadEnabled: boolean;
199
+ /**
200
+ * Initialize the OpenAI Realtime STT service.
201
+ *
202
+ * @param options.apiKey OpenAI API key for authentication.
203
+ * @param options.baseUrl WebSocket base URL for the Realtime API. Defaults
204
+ * to "wss://api.openai.com/v1/realtime".
205
+ * @param options.turnDetection Server-side VAD configuration. Defaults to
206
+ * `false` (disabled).
207
+ * @param options.shouldInterrupt Whether to interrupt bot output when speech
208
+ * is detected by server-side VAD. Defaults to true.
209
+ * @param options.settings Runtime-updatable settings. Its given fields
210
+ * override the defaults (model "gpt-realtime-whisper", language English).
211
+ * @param options.ttfsP99Latency P99 latency from speech end to final
212
+ * transcript in seconds. Override for your deployment. See
213
+ * https://github.com/pipecat-ai/stt-benchmark
214
+ * Other options are passed to parent WebsocketSTTService.
215
+ */
216
+ constructor(options: OpenAIRealtimeSTTServiceOptions);
217
+ /** Drop prompt settings that are not accepted by the selected model. */
218
+ static _omitUnsupportedPrompt(settings: OpenAIRealtimeSTTSettings): Record<string, unknown>;
219
+ /**
220
+ * Convert a Language value to an ISO-639-1 code.
221
+ *
222
+ * @param language The Language value.
223
+ * @returns Two-letter ISO-639-1 language code.
224
+ */
225
+ static _languageToCode(language: Language | string): string;
226
+ /**
227
+ * Check if the service can generate processing metrics.
228
+ *
229
+ * @returns True, as this service supports metrics generation.
230
+ */
231
+ canGenerateMetrics(): boolean;
232
+ /**
233
+ * Request external turn strategies when server-side VAD drives turns.
234
+ *
235
+ * With server-side VAD enabled the OpenAI server detects speech boundaries
236
+ * and this service proposes turns from them, so the user aggregator
237
+ * resolves those rather than running local VAD/smart-turn. With
238
+ * `turnDetection: false` (the default) the server emits no VAD events and
239
+ * the defaults are left in place. Applied unless the user passed their own
240
+ * `userTurnStrategies`.
241
+ */
242
+ serviceMetadataFrame(): STTMetadataFrame;
243
+ /**
244
+ * Apply a settings delta and send session update if needed.
245
+ *
246
+ * Sends a `session.update` to the server when the session is active.
247
+ *
248
+ * @param delta An STTSettings (or `OpenAIRealtimeSTTService.Settings`) delta.
249
+ * @returns Record mapping changed field names to their previous values.
250
+ */
251
+ protected _updateSettings(delta: STTSettings): Promise<Record<string, unknown>>;
252
+ /**
253
+ * Set up the service and connect.
254
+ *
255
+ * @param setup Configuration object containing setup parameters.
256
+ */
257
+ setup(setup: FrameProcessorSetup): Promise<void>;
258
+ /**
259
+ * Stop the service and close WebSocket connection.
260
+ *
261
+ * @param frame The end frame triggering service shutdown.
262
+ */
263
+ stop(frame: EndFrame): Promise<void>;
264
+ /**
265
+ * Cancel the service and close WebSocket connection.
266
+ *
267
+ * @param frame The cancel frame triggering service cancellation.
268
+ */
269
+ cancel(frame: CancelFrame): Promise<void>;
270
+ /**
271
+ * Send audio data to the transcription session.
272
+ *
273
+ * Audio is streamed over the WebSocket. Transcription results arrive
274
+ * asynchronously via the receive task and are pushed as
275
+ * `InterimTranscriptionFrame` or `TranscriptionFrame`.
276
+ *
277
+ * @param audio Raw audio bytes (16-bit mono PCM at the pipeline sample
278
+ * rate). Automatically resampled to 24 kHz.
279
+ * @returns null — results are delivered via the WebSocket receive task.
280
+ */
281
+ runStt(audio: Uint8Array): AsyncGenerator<Frame | null, void, unknown>;
282
+ /**
283
+ * Process frames from the pipeline.
284
+ *
285
+ * Extends the base STT service to handle local VAD events when server-side
286
+ * VAD is disabled. On `VADUserStoppedSpeakingFrame`, commits the audio
287
+ * buffer so the server begins transcription for the completed speech
288
+ * segment.
289
+ *
290
+ * @param frame The frame to process.
291
+ * @param direction The direction of frame flow in the pipeline.
292
+ */
293
+ processFrame(frame: Frame, direction: FrameDirection): Promise<void>;
294
+ /** Connect to the transcription endpoint and start receiving. */
295
+ _connect(): Promise<void>;
296
+ /** Disconnect and clean up background tasks. */
297
+ _disconnect(): Promise<void>;
298
+ /** Establish the WebSocket connection to the transcription endpoint. */
299
+ _connectWebsocket(): Promise<void>;
300
+ /** Close the WebSocket connection. */
301
+ _disconnectWebsocket(): Promise<void>;
302
+ /**
303
+ * Send a JSON message over the WebSocket.
304
+ *
305
+ * @param message The message object to serialize and send.
306
+ */
307
+ protected _wsSend(message: Dict): Promise<void>;
308
+ /** Send `session.update` to configure the transcription session. */
309
+ protected _sendSessionUpdate(): Promise<void>;
310
+ /**
311
+ * Send audio data via `input_audio_buffer.append`.
312
+ *
313
+ * Resamples from the pipeline sample rate to 24 kHz if needed.
314
+ *
315
+ * @param audio Raw audio bytes at the pipeline sample rate.
316
+ */
317
+ protected _sendAudio(audio: Uint8Array): Promise<void>;
318
+ /** Commit the current audio buffer for transcription. */
319
+ protected _commitAudioBuffer(): Promise<void>;
320
+ /** Clear the current audio buffer. */
321
+ protected _clearAudioBuffer(): Promise<void>;
322
+ /**
323
+ * Receive and dispatch server events from the transcription session.
324
+ *
325
+ * Called by `WebsocketService._receiveTaskHandler` which wraps this method
326
+ * with automatic reconnection on connection errors.
327
+ */
328
+ _receiveMessages(): Promise<void>;
329
+ /**
330
+ * Handle `session.created`.
331
+ *
332
+ * Sent immediately after connecting. We respond by configuring the session
333
+ * with our desired settings.
334
+ *
335
+ * @param _evt The session created event from the server.
336
+ */
337
+ protected _handleSessionCreated(_evt: Dict): Promise<void>;
338
+ /**
339
+ * Handle `session.updated`.
340
+ *
341
+ * The session is now fully configured and ready to transcribe.
342
+ *
343
+ * @param _evt The session updated event from the server.
344
+ */
345
+ protected _handleSessionUpdated(_evt: Dict): Promise<void>;
346
+ /**
347
+ * Handle incremental transcription text.
348
+ *
349
+ * For "gpt-realtime-whisper", "gpt-live-transcribe", and "gpt-transcribe",
350
+ * deltas contain low-latency streaming partial text.
351
+ *
352
+ * @param evt The delta event from the server.
353
+ */
354
+ protected _handleTranscriptionDelta(evt: Dict): Promise<void>;
355
+ /**
356
+ * Handle a completed transcription for a speech segment.
357
+ *
358
+ * Pushes a `TranscriptionFrame` and records the result for tracing.
359
+ *
360
+ * @param evt The completed event containing the full transcript.
361
+ */
362
+ protected _handleTranscriptionCompleted(evt: Dict): Promise<void>;
363
+ /**
364
+ * Record transcription result for tracing.
365
+ *
366
+ * @param _transcript The transcribed text.
367
+ * @param _isFinal Whether this is a final transcription result.
368
+ * @param _language Optional language of the transcription.
369
+ */
370
+ protected _handleTranscriptionTrace(_transcript: string, _isFinal: boolean, _language?: Language | null): Promise<void>;
371
+ /**
372
+ * Handle server-side VAD speech start.
373
+ *
374
+ * Proposes a turn start, which the user turn strategies resolve into a
375
+ * `UserStartedSpeakingFrame` and an interruption.
376
+ *
377
+ * @param _evt The `input_audio_buffer.speech_started` event.
378
+ */
379
+ protected _handleSpeechStarted(_evt: Dict): Promise<void>;
380
+ /**
381
+ * Handle server-side VAD speech stop.
382
+ *
383
+ * Proposes a turn stop. The audio buffer is automatically committed by the
384
+ * server when VAD is enabled.
385
+ *
386
+ * @param _evt The `input_audio_buffer.speech_stopped` event.
387
+ */
388
+ protected _handleSpeechStopped(_evt: Dict): Promise<void>;
389
+ /**
390
+ * Handle a transcription failure for a speech segment.
391
+ *
392
+ * Logs the error but does not treat it as fatal — the session remains
393
+ * active for subsequent turns.
394
+ *
395
+ * @param evt The failed event containing error details.
396
+ */
397
+ protected _handleTranscriptionFailed(evt: Dict): Promise<void>;
398
+ /**
399
+ * Handle a fatal error from the transcription session.
400
+ *
401
+ * Throws so that `WebsocketService` can decide whether to attempt
402
+ * reconnection.
403
+ *
404
+ * @param evt The error event.
405
+ */
406
+ protected _handleError(evt: Dict): Promise<void>;
407
+ }
408
+ export {};
409
+ //# sourceMappingURL=stt.d.ts.map