diff --git a/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextDriver.test.ts b/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextDriver.test.ts index 8d4b1aec4..028db91ed 100644 --- a/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextDriver.test.ts +++ b/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextDriver.test.ts @@ -769,7 +769,7 @@ describe('SpeechToTextDriver metering', () => { }); const result = await withActor(actor, () => driver.transcribe({ - file: dataUrl(Buffer.from('a'), 'audio/mp3'), + file: dataUrl(Buffer.alloc(8000, 0), 'audio/mp3'), response_format: 'text', }), ); diff --git a/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextProvider.test.ts b/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextProvider.test.ts new file mode 100644 index 000000000..0e1c650cf --- /dev/null +++ b/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextProvider.test.ts @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Puter is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Puter. If not, see . + */ + +import { describe, expect, it } from 'vitest'; +import { billableAudioSeconds } from './SpeechToTextProvider.js'; + +describe('billableAudioSeconds', () => { + it('bills the reported seconds, rounded up', () => { + expect(billableAudioSeconds(3.2, 60, 64_000)).toBe(4); + expect(billableAudioSeconds(0.1, 60, 64_000)).toBe(1); + }); + + it('holds the reported seconds to what the file could contain', () => { + // 125,000 bytes hold at most 1,000 seconds of audio. + expect(billableAudioSeconds(2 ** 53, 60, 125_000)).toBe(1000); + expect(billableAudioSeconds(1e308, 60, 125_000)).toBe(1000); + expect(billableAudioSeconds(600, 28, 441_078)).toBe(600); + }); + + it('bills the estimate when nothing usable is reported', () => { + for (const reported of [undefined, null, '42', NaN, Infinity, 0, -5]) { + expect(billableAudioSeconds(reported, 60, 64_000)).toBe(60); + } + }); +}); diff --git a/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextProvider.ts b/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextProvider.ts index 68808e1b2..b7e118e3e 100644 --- a/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextProvider.ts +++ b/src/backend/drivers/ai/interfaces/speechToText/SpeechToTextProvider.ts @@ -32,6 +32,27 @@ import type { ITranscribeArgs, } from './types.js'; +// Speech codecs don't go below about 1 kbps, so a file can't hold more audio +// than its size at that rate. +const MIN_AUDIO_BYTES_PER_SECOND = 125; + +/** + * Whole seconds to bill for a transcription: what the provider reports, held to + * the longest audio `audioBytes` could contain, or `estimatedSeconds` when it + * reports nothing usable. + */ +export const billableAudioSeconds = ( + reported: unknown, + estimatedSeconds: number, + audioBytes: number, +): number => + typeof reported === 'number' && Number.isFinite(reported) && reported > 0 + ? Math.min( + Math.max(1, Math.ceil(reported)), + Math.max(1, Math.ceil(audioBytes / MIN_AUDIO_BYTES_PER_SECOND)), + ) + : estimatedSeconds; + export abstract class SpeechToTextProvider implements ISpeechToTextProvider { abstract readonly providerName: string; diff --git a/src/backend/drivers/ai/providers/openai/speechToText/OpenAISpeechToTextProvider.ts b/src/backend/drivers/ai/providers/openai/speechToText/OpenAISpeechToTextProvider.ts index bc672895c..02a4ceca1 100644 --- a/src/backend/drivers/ai/providers/openai/speechToText/OpenAISpeechToTextProvider.ts +++ b/src/backend/drivers/ai/providers/openai/speechToText/OpenAISpeechToTextProvider.ts @@ -27,7 +27,11 @@ import type { ISpeechToTextModel, ITranscribeArgs, } from '../../../interfaces/speechToText/types.js'; -import { SpeechToTextProvider } from '../../../interfaces/speechToText/SpeechToTextProvider.js'; +import { jsonCheckedFetch } from '../../../shared/jsonCheckedFetch.js'; +import { + billableAudioSeconds, + SpeechToTextProvider, +} from '../../../interfaces/speechToText/SpeechToTextProvider.js'; /** * Wraps OpenAI's audio transcription API. No current OpenAI model serves @@ -73,7 +77,7 @@ export class OpenAISpeechToTextProvider extends SpeechToTextProvider { constructor(deps: ISpeechToTextDeps, config: { apiKey?: string }) { super(deps); this.#openai = config.apiKey - ? new OpenAI({ apiKey: config.apiKey }) + ? new OpenAI({ apiKey: config.apiKey, fetch: jsonCheckedFetch }) : null; } @@ -138,7 +142,9 @@ export class OpenAISpeechToTextProvider extends SpeechToTextProvider { ); const selectedModel = args.model || DEFAULT_TRANSCRIBE_MODEL; - const caps = MODEL_CAPS[selectedModel]; + const caps = Object.hasOwn(MODEL_CAPS, selectedModel) + ? MODEL_CAPS[selectedModel] + : undefined; if (!caps) { throw new HttpError(400, `Unsupported model: ${selectedModel}`, { legacyCode: 'bad_request', @@ -228,13 +234,33 @@ export class OpenAISpeechToTextProvider extends SpeechToTextProvider { payload.extra_body = extra; } - const result = await this.#openai.audio.transcriptions.create( - payload as unknown as Parameters< - OpenAI['audio']['transcriptions']['create'] - >[0], - ); + const result = await this.#openai.audio.transcriptions + .create( + payload as unknown as Parameters< + OpenAI['audio']['transcriptions']['create'] + >[0], + ) + .catch((error: unknown) => { + // The SDK can't write a null inside a list or an object + // into the form it sends. + if ( + error instanceof TypeError && + error.message.startsWith('Received null for') + ) { + throw new HttpError( + 400, + 'language and extra_body must not contain null', + { legacyCode: 'bad_request' }, + ); + } + throw error; + }); - const billedSeconds = reportedSeconds(result) ?? estimatedSeconds; + const billedSeconds = billableAudioSeconds( + reportedSeconds(result), + estimatedSeconds, + loaded.buffer.byteLength, + ); this.deps.metering.incrementUsage( actor, usageType, @@ -246,7 +272,7 @@ export class OpenAISpeechToTextProvider extends SpeechToTextProvider { if (args.response_format === 'text') { return typeof result === 'string' ? result - : ((result as { text?: string }).text ?? ''); + : ((result as { text?: string } | null)?.text ?? ''); } return result; } finally { @@ -255,17 +281,12 @@ export class OpenAISpeechToTextProvider extends SpeechToTextProvider { } } -/** Whole seconds of audio OpenAI reports billing for, if it reports them. */ -function reportedSeconds(result: unknown): number | undefined { +/** The seconds of audio OpenAI reports billing for, if it reports them. */ +function reportedSeconds(result: unknown): unknown { if (!result || typeof result !== 'object') return undefined; const { usage, duration } = result as { usage?: { type?: string; seconds?: unknown }; duration?: unknown; }; - const seconds = usage?.type === 'duration' ? usage.seconds : duration; - return typeof seconds === 'number' && - Number.isFinite(seconds) && - seconds > 0 - ? Math.max(1, Math.ceil(seconds)) - : undefined; + return usage?.type === 'duration' ? usage.seconds : duration; } diff --git a/src/backend/drivers/ai/providers/xai/speechToText/XAISpeechToTextProvider.test.ts b/src/backend/drivers/ai/providers/xai/speechToText/XAISpeechToTextProvider.test.ts index 8ed2e4d85..c1d8b935a 100644 --- a/src/backend/drivers/ai/providers/xai/speechToText/XAISpeechToTextProvider.test.ts +++ b/src/backend/drivers/ai/providers/xai/speechToText/XAISpeechToTextProvider.test.ts @@ -584,7 +584,7 @@ describe('XAISpeechToTextProvider metering', () => { await withActor(actor, () => driver.transcribe({ - file: dataUrl(Buffer.from('a'), 'audio/mp3'), + file: dataUrl(Buffer.alloc(8000, 0), 'audio/mp3'), }), ); diff --git a/src/backend/drivers/ai/providers/xai/speechToText/XAISpeechToTextProvider.ts b/src/backend/drivers/ai/providers/xai/speechToText/XAISpeechToTextProvider.ts index fd47b6f7d..cd0bb243f 100644 --- a/src/backend/drivers/ai/providers/xai/speechToText/XAISpeechToTextProvider.ts +++ b/src/backend/drivers/ai/providers/xai/speechToText/XAISpeechToTextProvider.ts @@ -21,13 +21,20 @@ import { HttpError } from '../../../../../core/http/HttpError.js'; import type { Actor } from '../../../../../core/actor.js'; import { withAiCreditHold } from '../../../../../util/aiCostFactor.js'; import { loadFileInput } from '../../../../util/fileInput.js'; -import { upstreamFetch } from '../../../../util/upstreamErrors.js'; +import { + malformedUpstreamResponse, + upstreamFetch, + upstreamJson, +} from '../../../../util/upstreamErrors.js'; import type { ISpeechToTextDeps, ISpeechToTextModel, ITranscribeArgs, } from '../../../interfaces/speechToText/types.js'; -import { SpeechToTextProvider } from '../../../interfaces/speechToText/SpeechToTextProvider.js'; +import { + billableAudioSeconds, + SpeechToTextProvider, +} from '../../../interfaces/speechToText/SpeechToTextProvider.js'; /** * Speech-to-text via the xAI (Grok) STT API. @@ -168,12 +175,14 @@ export class XAISpeechToTextProvider extends SpeechToTextProvider { // be known upfront, so the hold covers a conservative 60 seconds. // Actual usage is metered from the duration xAI reports. let estimatedSeconds = 60; + let audioBytes = MAX_AUDIO_FILE_SIZE; if (this.#isHttpUrl(args.file)) { formData.append('url', args.file); } else { // The file must be the last field, per xAI's docs. const { blob, filename } = await this.#loadAudio(args.file, actor); estimatedSeconds = Math.max(1, Math.ceil(blob.size / 16000)); + audioBytes = blob.size; formData.append('file', blob, filename); } @@ -194,11 +203,19 @@ export class XAISpeechToTextProvider extends SpeechToTextProvider { }, { providerLabel: 'xAI STT', timeoutMs: STT_TIMEOUT_MS }, ); - const result = await response.json(); - const actualSeconds = - typeof result.duration === 'number' - ? Math.ceil(result.duration) - : estimatedSeconds; + const result = (await upstreamJson( + 'xai', + 'xAI STT', + response, + )) as { duration?: unknown } | null; + if (!result || typeof result !== 'object') { + throw malformedUpstreamResponse('xai', 'xAI STT'); + } + const actualSeconds = billableAudioSeconds( + result.duration, + estimatedSeconds, + audioBytes, + ); metering.incrementUsage( actor, 'xai:stt:second',