Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tts.ts

569 lines19.8 KB

1import { BaseTTSAdapter } from '@tanstack/ai/adapters'
2import { generateId } from '@tanstack/ai-utils'
3import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
4import {
5 BYTEPLUS_VOICE_BASE_URL,
6 bytePlusVoiceError,
7 bytePlusVoiceHeaders,
8 getBytePlusVoiceApiKeyFromEnv,
9 readJsonBody,
10 withBytePlusVoiceDefaults,
11} from '../utils/client'
12import type {
13 TTSAlignment,
14 TTSCapabilities,
15 TTSOptions,
16 TTSSegment,
17 TTSTurn,
18} from '@tanstack/ai'
19import type { InternalLogger } from '@tanstack/ai/adapter-internals'
20import type { BytePlusVoiceConfig } from '../utils/client'
21import type { BytePlusTTSModel } from '../model-meta'
22import type {
23 BytePlusTTSAudioConfig,
24 BytePlusTTSAudioFormat,
25 BytePlusTTSCreateRequest,
26 BytePlusTTSCreateResponse,
27 BytePlusTTSReference,
28 BytePlusTTSSubtitle,
29 BytePlusTTSSubtitleEntry,
30} from '../audio/wire-types'
31import type {
32 BytePlusTTSProviderOptions,
33 BytePlusTTSResult,
34} from '../audio/tts-provider-options'
35​
36/** Path of the synchronous Seed Speech synthesis endpoint. */
37const TTS_CREATE_PATH = '/api/v3/tts/create'
38​
39/**
40 * Name of the request field carrying the text to speak.
41 *
42 * **`text_prompt` is correct — do not "fix" this to `text`.** The endpoint
43 * schema (docs.byteplus.com/en/docs/byteplusvoice/seedaudio-01) lists this
44 * body as exactly `model`, `text_prompt`, `references`, `audio_config`,
45 * `watermark`; there is no request-side `text`. The `text` spelling belongs
46 * to the *other* endpoint, `/tts/unidirectional` (TTS 2.0), where it sits
47 * under `req_params.text`. The name stays isolated here so the two spellings
48 * never get conflated.
49 */
50const TTS_TEXT_FIELD = 'text_prompt' satisfies keyof BytePlusTTSCreateRequest
51​
52/**
53 * Sample rate used when the caller doesn't pick one. The endpoint documents a
54 * default of 40000, which is not among the rates it accepts — so the adapter
55 * never relies on the server default and always sends this instead.
56 */
57const DEFAULT_SAMPLE_RATE = 24000
58​
59/**
60 * True when a Seed Speech envelope's `code` means success.
61 *
62 * Seed Speech uses `0` for success and a flat numeric code otherwise
63 * (`45000010 Invalid X-Api-Key`). The success envelope has not been confirmed
64 * against a live key, so `code` is accepted as a number, its string form, or
65 * absent — an envelope that omits `code` entirely is treated as success, which
66 * is what the HTTP status already told us.
67 */
68function isZeroCode(code: number | string | undefined): boolean {
69 if (code === undefined) return true
70 return Number(code) === 0
72​
73/**
74 * Voice used when neither `TTSOptions.voice` nor `modelOptions.speaker` is
75 * set — the English female "Stokie" voice from the TTS 2.0 generation.
76 */
77export const BYTEPLUS_DEFAULT_TTS_SPEAKER = 'en_female_stokie_uranus_bigtts'
78​
79/**
80 * Hard cap on a single Seed Speech synthesis, in seconds. Longer scripts must
81 * be split across calls and stitched client-side.
82 *
83 * The cap applies to the *pre-rate* length the service bills on — the
84 * `original_duration` it returns. The delivered clip can run longer than this
85 * when `speech_rate` slows it down.
86 */
87export const BYTEPLUS_TTS_MAX_OUTPUT_SECONDS = 120
88​
89/**
90 * Hard cap on the `references` array, and therefore on the number of distinct
91 * voices one dialogue request can use. The markers that cite them in
92 * `text_prompt` run `@Audio1`..`@Audio3`.
93 */
94export const BYTEPLUS_TTS_MAX_REFERENCES = 3
95​
96/**
97 * BytePlus Seed Speech text-to-speech adapter.
98 *
99 * Talks to `POST {baseURL}/api/v3/tts/create` on the Seed Speech voice host.
100 * Two things differ from the Ark-hosted adapters in this package:
101 *
102 * - **Separate API key.** Seed Speech authenticates with `X-Api-Key` and its
103 * own key (`BYTEPLUS_VOICE_API_KEY`). An `ARK_API_KEY` sent here is
104 * rejected with `45000010 Invalid X-Api-Key`.
105 * - **120 s output cap.** A single call synthesises at most
106 * {@link BYTEPLUS_TTS_MAX_OUTPUT_SECONDS} seconds of audio; longer scripts
107 * have to be split and stitched client-side. The cap is measured before
108 * `speech_rate` is applied, so a slowed clip can play for longer than that
109 * — `result.duration` is the delivered length and `result.originalDuration`
110 * is the metered one.
111 *
112 * Streaming synthesis (`tts/unidirectional` and the WebSocket API) is not
113 * covered by this adapter — note that endpoint spells the text field `text`,
114 * while this one uses `text_prompt`.
115 *
116 * @example
117 * ```ts
118 * const adapter = byteplusSpeech('seed-audio-1.0')
119 * const result = await generateSpeech({
120 * adapter,
121 * text: 'welcome to the guitar store',
122 * voice: 'en_female_stokie_uranus_bigtts',
123 * format: 'mp3',
124 * })
125 * ```
126 */
127export class BytePlusTTSAdapter<
128 TModel extends BytePlusTTSModel = BytePlusTTSModel,
129> extends BaseTTSAdapter<TModel, BytePlusTTSProviderOptions> {
130 readonly name = 'byteplus' as const
131​
132 /**
133 * Seed Audio 1.0 does multi-role dialogue in one pass, addressed through
134 * `references` (capped at 3 entries), and returns word/sentence timings
135 * when `audio_config.enable_subtitle` is set.
136 */
137 override readonly capabilities: TTSCapabilities = {
138 maxSpeakers: BYTEPLUS_TTS_MAX_REFERENCES,
139 timestamps: true,
140 }
141​
142 private readonly apiKey: string
143 private readonly baseURL: string
144 private readonly defaultHeaders: Record<string, string>
145 private readonly fetchImpl: typeof fetch
146​
147 constructor(model: TModel, config: BytePlusVoiceConfig) {
148 super(model, config)
149 const resolved = withBytePlusVoiceDefaults(config)
150 this.apiKey = resolved.apiKey
151 this.baseURL = resolved.baseURL ?? BYTEPLUS_VOICE_BASE_URL
152 this.defaultHeaders = resolved.defaultHeaders ?? {}
153 this.fetchImpl = resolved.fetch ?? globalThis.fetch.bind(globalThis)
154 }
155​
156 async generateSpeech(
157 options: TTSOptions<BytePlusTTSProviderOptions>,
158 ): Promise<BytePlusTTSResult> {
159 const { logger, model, text, voice, format, speed, modelOptions, turns } =
160 options
161​
162 logger.request(`activity=generateSpeech provider=byteplus model=${model}`, {
163 provider: 'byteplus',
164 model,
165 })
166​
167 const { body, audioFormat, sampleRate } = buildTTSRequestBody({
168 model,
169 text,
170 turns,
171 voice,
172 format,
173 speed,
174 modelOptions,
175 timestamps: options.timestamps,
176 logger,
177 })
178​
179 try {
180 const response = await this.fetchImpl(
181 `${this.baseURL}${TTS_CREATE_PATH}`,
182 {
183 method: 'POST',
184 headers: bytePlusVoiceHeaders(this.apiKey, {
185 ...this.defaultHeaders,
186 // Client-generated per-request id. BytePlus echoes it in their
187 // request logs, which is what support asks for when diagnosing a
188 // synthesis failure.
189 'X-Api-Request-Id': newRequestId(),
190 }),
191 body: JSON.stringify(body),
192 },
193 )
194​
195 const payload = await readJsonBody(response)
196​
197 if (!response.ok) {
198 throw bytePlusVoiceError(response.status, payload, 'text-to-speech')
199 }
200​
201 const data = payload as BytePlusTTSCreateResponse
202​
203 // Seed Speech reports status in the body, not only in the HTTP status:
204 // a 200 can carry a non-zero `code`. Check it before looking at `audio`,
205 // because a failed call may still return a partial or placeholder
206 // payload that would otherwise be handed back as if it were valid.
207 //
208 // `code` is accepted as a number *or* a string. The success envelope was
209 // never confirmed against a live key (no voice key yet — see
210 // `audio/wire-types.ts`), and `readStringField` already tolerates both
211 // forms when rendering the error, so requiring a number here would let
212 // `{"code": "45000010"}` through both this gate and the one below.
213 if (!isZeroCode(data.code)) {
214 throw bytePlusVoiceError(response.status, payload, 'text-to-speech')
215 }
216​
217 // Belt and braces for a 200 that reports success but carries nothing to
218 // play. Say that the adapter rejected it, rather than reusing the
219 // envelope-error phrasing — a bare "failed (200)" gives no hint that the
220 // response was well-formed and simply empty.
221 if (typeof data.audio !== 'string' || data.audio.length === 0) {
222 throw new Error(
223 `BytePlus Seed Speech text-to-speech returned a success response ` +
224 `with no audio (model ${model}).`,
225 )
226 }
227​
228 const duration = toDurationSeconds(data.duration)
229 const originalDuration = toDurationSeconds(data.original_duration)
230​
231 return {
232 id: generateId(this.name),
233 model,
234 audio: data.audio,
235 format: audioFormat,
236 contentType: getContentType(audioFormat, sampleRate),
237 ...(duration !== undefined && { duration }),
238 ...(originalDuration !== undefined && { originalDuration }),
239 ...(data.subtitle !== undefined && { subtitle: data.subtitle }),
240 ...toAlignmentFields(data.subtitle),
241 ...(data.url !== undefined && { url: data.url }),
242 }
243 } catch (error) {
244 logger.errors('byteplus.generateSpeech fatal', {
245 error: toRunErrorPayload(error, 'byteplus.generateSpeech failed'),
246 source: 'byteplus.generateSpeech',
247 })
248 throw error
249 }
250 }
252​
253/**
254 * Build the JSON body for `POST /api/v3/tts/create`, resolving the voice,
255 * output format and rate fields in one place.
256 *
257 * Returns the request `body`, the resolved `audioFormat` and the
258 * `sampleRate`, which the caller reports on the result and turns into a
259 * `contentType`.
260 */
261export function buildTTSRequestBody(options: {
262 model: string
263 text: string
264 /** Dialogue turns, when the caller asked for multi-role synthesis. */
265 turns?: Array<TTSTurn>
266 voice: string | undefined
267 format: TTSOptions['format'] | undefined
268 speed: number | undefined
269 modelOptions: BytePlusTTSProviderOptions | undefined
270 /** Core `timestamps: true` — turns on `audio_config.enable_subtitle`. */
271 timestamps?: boolean
272 logger: InternalLogger
273}): {
274 body: BytePlusTTSCreateRequest
275 audioFormat: BytePlusTTSAudioFormat
276 sampleRate: number
277} {
278 const { model, text, turns, voice, format, speed, modelOptions, logger } =
279 options
280​
281 const audioFormat = pickAudioFormat(modelOptions?.format, format, logger)
282 // Always explicit: the documented server default (40000) is not one of the
283 // rates the endpoint accepts, so relying on it is a coin flip.
284 const sampleRate = modelOptions?.sample_rate ?? DEFAULT_SAMPLE_RATE
285​
286 const audioConfig: BytePlusTTSAudioConfig = {
287 format: audioFormat,
288 sample_rate: sampleRate,
289 }
290 if (modelOptions?.pitch_rate !== undefined) {
291 audioConfig.pitch_rate = modelOptions.pitch_rate
292 }
293 if (modelOptions?.loudness_rate !== undefined) {
294 audioConfig.loudness_rate = modelOptions.loudness_rate
295 }
296 // `modelOptions.enable_subtitle` still wins, so an explicit `false` can
297 // opt out of the flag even when core asked for timestamps. A `timestamps`
298 // the caller never set stays off the body entirely.
299 const enableSubtitle =
300 modelOptions?.enable_subtitle ?? (options.timestamps || undefined)
301 if (enableSubtitle !== undefined) {
302 audioConfig.enable_subtitle = enableSubtitle
303 }
304​
305 // An explicit `speech_rate` always wins over the derived one — it is the
306 // native unit and the only way to reach the extremes precisely.
307 const speechRate =
308 modelOptions?.speech_rate ??
309 (speed !== undefined ? toSpeechRate(speed, logger) : undefined)
310 if (speechRate !== undefined) {
311 audioConfig.speech_rate = speechRate
312 }
313​
314 const dialogue = turns ? buildDialoguePrompt(turns) : undefined
315​
316 const body: BytePlusTTSCreateRequest = {
317 model,
318 [TTS_TEXT_FIELD]: dialogue?.textPrompt ?? text,
319 // The voice belongs inside `references`, not at the top level — a
320 // top-level `speaker` is silently ignored by the server.
321 references: modelOptions?.references ??
322 dialogue?.references ?? [
323 {
324 speaker:
325 modelOptions?.speaker ?? voice ?? BYTEPLUS_DEFAULT_TTS_SPEAKER,
326 },
327 ],
328 audio_config: audioConfig,
329 }
330 if (modelOptions?.watermark !== undefined) {
331 // The endpoint wants an object. `true` means the audible marker, which is
332 // what a caller passing a boolean is asking for.
333 body.watermark =
334 typeof modelOptions.watermark === 'boolean'
335 ? { aigc_watermark: modelOptions.watermark }
336 : modelOptions.watermark
337 }
338​
339 return { body, audioFormat, sampleRate }
341​
342/**
343 * Convert the cross-provider `TTSOptions.speed` multiplier into Seed Speech's
344 * `speech_rate` percentage.
345 *
346 * ```
347 * speech_rate = clamp(round((speed - 1) * 100), -50, 100)
348 * ```
349 *
350 * so `0.5 → -50`, `1.0 → 0`, `1.5 → 50`, `2.0 → 100`.
351 *
352 * The range `-50`..`100` and both multiplier anchors (`-50` = 0.5×,
353 * `100` = 2×) are documented, and hold on both the `/tts/create` and
354 * `/tts/unidirectional` endpoints.
355 *
356 * `TTSOptions.speed` spans a wider 0.25×–4× than the endpoint supports, so
357 * anything outside 0.5×–2× clamps (and warns) rather than erroring.
358 */
359export function toSpeechRate(speed: number, logger?: InternalLogger): number {
360 const rate = Math.round((speed - 1) * 100)
361 const clamped = Math.min(100, Math.max(-50, rate))
362 if (clamped !== rate) {
363 logger?.warn(
364 `Speed ${speed}× is outside the range BytePlus Seed Speech documents (0.5×–2×) — clamping speech_rate from ${rate} to ${clamped}.`,
365 { provider: 'byteplus', requestedSpeed: speed, speechRate: clamped },
366 )
367 }
368 return clamped
370​
371/**
372 * Map the cross-provider `TTSOptions.format` onto a Seed Speech output
373 * format. An explicit `modelOptions.format` always wins.
374 *
375 * Seed Speech produces `wav`, `mp3`, `pcm` and `ogg_opus`. The generic
376 * `opus` maps onto `ogg_opus`; `aac` and `flac` have no equivalent and fall
377 * back to `mp3` (matching how the other non-OpenAI TTS adapters in this repo
378 * handle unsupported codecs). The fallback is logged so it isn't silent.
379 */
380function pickAudioFormat(
381 override: BytePlusTTSAudioFormat | undefined,
382 format: TTSOptions['format'] | undefined,
383 logger: InternalLogger,
384): BytePlusTTSAudioFormat {
385 if (override) return override
386 if (!format) return 'mp3'
387 switch (format) {
388 case 'mp3':
389 case 'wav':
390 case 'pcm':
391 return format
392 case 'opus':
393 return 'ogg_opus'
394 case 'aac':
395 case 'flac':
396 logger.warn(
397 `BytePlus Seed Speech does not support ${format} output — falling back to mp3. Set modelOptions.format to choose between wav, mp3, pcm and ogg_opus.`,
398 { provider: 'byteplus', requestedFormat: format },
399 )
400 return 'mp3'
401 }
403​
404/**
405 * Build a per-request id for the `X-Api-Request-Id` header. Falls back to the
406 * package's own id generator on runtimes without `crypto.randomUUID`.
407 */
408function newRequestId(): string {
409 return globalThis.crypto?.randomUUID?.() ?? generateId('byteplus-tts')
411​
412/**
413 * MIME type for a Seed Speech output format.
414 *
415 * `pcm` is raw little-endian 16-bit samples, so its media type has to carry
416 * the sample rate (RFC 3551/3555). The adapter always resolves a rate, so one
417 * is always available here.
418 */
419export function getContentType(
420 format: BytePlusTTSAudioFormat,
421 sampleRate?: number,
422): string {
423 switch (format) {
424 case 'mp3':
425 return 'audio/mpeg'
426 case 'wav':
427 return 'audio/wav'
428 case 'ogg_opus':
429 return 'audio/ogg;codecs=opus'
430 case 'pcm':
431 return `audio/L16;rate=${sampleRate ?? 24000}`
432 }
434​
435/**
436 * Turn dialogue turns into the one-prompt form Seed Audio 1.0 takes: each
437 * distinct voice becomes a `references` entry, and every line of the script
438 * cites its voice by the reference's 1-based position (`@Audio1`..`@Audio3`),
439 * which is the marker convention the reference array already uses.
440 *
441 * **The prompt form is unprobed.** The flat `references[]` member shape is
442 * confirmed (see `BytePlusTTSReference`), and the model card documents
443 * multi-role dialogue and positional reference markers, but no worked
444 * multi-speaker example was available and no Seed Speech key existed to
445 * confirm how lines should cite their voice.
446 */
447function buildDialoguePrompt(turns: Array<TTSTurn>): {
448 textPrompt: string
449 references: Array<BytePlusTTSReference>
450} {
451 const voices = [...new Set(turns.map((turn) => turn.voice))]
452 return {
453 textPrompt: turns
454 .map((turn) => `@Audio${voices.indexOf(turn.voice) + 1}: ${turn.text}`)
455 .join('\n'),
456 references: voices.map((speaker) => ({ speaker })),
457 }
459​
460/**
461 * Map the BytePlus `subtitle` block onto the cross-provider `alignment` /
462 * `segments` fields.
463 *
464 * `words` is the finest granularity Seed Speech reports, so it becomes
465 * `alignment`; `sentences` is utterance segmentation, so it becomes
466 * `segments`. **Subtitle times are milliseconds** while the rest of the
467 * response is seconds — the conversion happens here, once.
468 *
469 * The raw block stays on {@link BytePlusTTSResult.subtitle} for callers
470 * already reading it.
471 */
472function toAlignmentFields(subtitle: BytePlusTTSSubtitle | undefined): {
473 alignment?: TTSAlignment
474 segments?: Array<TTSSegment>
475} {
476 if (!subtitle) return {}
477 const fields: { alignment?: TTSAlignment; segments?: Array<TTSSegment> } = {}
478 const words = subtitle.words?.filter(isTimedEntry)
479 if (words && words.length > 0) {
480 fields.alignment = {
481 unit: 'word',
482 texts: words.map((word) => word.text ?? ''),
483 startSeconds: words.map((word) => word.start_time / 1000),
484 endSeconds: words.map((word) => word.end_time / 1000),
485 }
486 }
487 const sentences = subtitle.sentences?.filter(isTimedEntry)
488 if (sentences && sentences.length > 0) {
489 fields.segments = sentences.map((sentence) => ({
490 startSeconds: sentence.start_time / 1000,
491 endSeconds: sentence.end_time / 1000,
492 ...(sentence.text !== undefined && { text: sentence.text }),
493 }))
494 }
495 return fields
497​
498/** Both times present, so the entry can be placed on the timeline. */
499function isTimedEntry(
500 entry: BytePlusTTSSubtitleEntry,
501): entry is BytePlusTTSSubtitleEntry & {
502 start_time: number
503 end_time: number
504} {
505 return (
506 typeof entry.start_time === 'number' && typeof entry.end_time === 'number'
507 )
509​
510/**
511 * Coerce a `duration` / `original_duration` field to a usable number of
512 * seconds.
513 *
514 * Both are documented as float **seconds**, so this only parses the string
515 * form and drops values that can't be a length (zero, negative, non-numeric).
516 * Note that `duration` may legitimately exceed
517 * {@link BYTEPLUS_TTS_MAX_OUTPUT_SECONDS} — a clip synthesised at
518 * `speech_rate: -50` runs at half speed, so up to 120 s of billed audio can
519 * be delivered as up to 240 s of playback. Do not "correct" a large value
520 * here; the cap applies to `original_duration`.
521 *
522 * The subtitle timings are the mixed-unit exception: those are milliseconds
523 * and are passed through untouched on {@link BytePlusTTSResult.subtitle}.
524 */
525export function toDurationSeconds(
526 raw: number | string | undefined,
527): number | undefined {
528 const value = typeof raw === 'string' ? Number(raw) : raw
529 if (value === undefined || !Number.isFinite(value) || value <= 0) {
530 return undefined
531 }
532 return value
534​
535/**
536 * Creates a BytePlus Seed Speech TTS adapter with an explicit API key.
537 *
538 * The key is the **Seed Speech** key, not the Ark key used by the chat, image
539 * and video adapters.
540 *
541 * @example
542 * ```ts
543 * const adapter = createBytePlusSpeech('seed-audio-1.0', process.env.BYTEPLUS_VOICE_API_KEY!)
544 * ```
545 */
546export function createBytePlusSpeech<
547 TModel extends BytePlusTTSModel = BytePlusTTSModel,
548>(
549 model: TModel,
550 apiKey: string,
551 config?: Omit<BytePlusVoiceConfig, 'apiKey'>,
552): BytePlusTTSAdapter<TModel> {
553 return new BytePlusTTSAdapter(model, { ...config, apiKey })
555​
556/**
557 * Creates a BytePlus Seed Speech TTS adapter, reading the API key from
558 * `BYTEPLUS_VOICE_API_KEY`.
559 *
560 * @throws Error if `BYTEPLUS_VOICE_API_KEY` is not set.
561 */
562export function byteplusSpeech<
563 TModel extends BytePlusTTSModel = BytePlusTTSModel,
564>(
565 model: TModel,
566 config?: Omit<BytePlusVoiceConfig, 'apiKey'>,
567): BytePlusTTSAdapter<TModel> {
568 return createBytePlusSpeech(model, getBytePlusVoiceApiKeyFromEnv(), config)