Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { generateTranscription } from '@tanstack/ai'
3import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
4import {
5 BytePlusTranscriptionAdapter,
6 createBytePlusTranscription,
7 mapRecognizeResponse,
8 normalizeAudioInput,
9} from '../src/adapters/transcription'
10import type { Logger } from '@tanstack/ai'
11import type { BytePlusTranscriptionWord } from '../src/adapters/transcription'
12
13const BASE_URL = 'https://voice.test'
14
15/** Captures what the adapter routes through `logger.warn`. */
16function captureLogger(): Logger & { warnings: Array<string> } {
17 const warnings: Array<string> = []
18 return {
19 warnings,
20 debug: () => {},
21 info: () => {},
22 warn: (message: string) => {
23 warnings.push(message)
24 },
25 error: () => {},
26 }
27}
28
29const RECOGNIZE_RESPONSE = {
30 audio_info: { duration: 2499 },
31 result: {
32 text: 'a guitar being played in a store',
33 utterances: [
34 {
35 text: 'a guitar being played',
36 start_time: 450,
37 end_time: 1530,
38 words: [
39 { text: 'a', start_time: 450, end_time: 600 },
40 { text: 'guitar', start_time: 600, end_time: 1100 },
41 ],
42 },
43 {
44 text: 'in a store',
45 start_time: 1530,
46 end_time: 2400,
47 additions: { speaker: '2' },
48 },
49 ],
50 },
51}
52
53function jsonResponse(body: unknown, status = 200): Response {
54 return new Response(JSON.stringify(body), {
55 status,
56 headers: { 'Content-Type': 'application/json' },
57 })
58}
59
60// A fresh `Response` per call — a `Response` body can only be read once, so a
61// shared instance breaks any test that fetches twice.
62function asrFetch(body: unknown = RECOGNIZE_RESPONSE, status = 200) {
63 return vi
64 .fn<typeof fetch>()
65 .mockImplementation(() => Promise.resolve(jsonResponse(body, status)))
66}
67
68function adapterWith(
69 fetchImpl: typeof fetch,
70 defaultHeaders?: Record<string, string>,
71) {
72 return new BytePlusTranscriptionAdapter('seed-asr', {
73 apiKey: 'voice-key',
74 baseURL: BASE_URL,
75 fetch: fetchImpl,
76 ...(defaultHeaders && { defaultHeaders }),
77 })
78}
79
80function lastRequest(fetchMock: ReturnType<typeof asrFetch>) {
81 const call = fetchMock.mock.calls.at(-1)
82 if (!call) throw new Error('fetch was not called')
83 const [url, init] = call
84 return {
85 url: String(url),
86 init: init as RequestInit,
87 headers: new Headers(init?.headers),
88 body: JSON.parse(String(init?.body)),
89 }
90}
91
92describe('BytePlusTranscriptionAdapter', () => {
93 it('posts to the flash endpoint with the ASR resource header', async () => {
94 const fetchMock = asrFetch()
95 await generateTranscription({
96 adapter: adapterWith(fetchMock),
97 audio: 'https://example.com/guitar.mp3',
98 })
99
100 const { url, init, headers, body } = lastRequest(fetchMock)
101 expect(url).toBe(`${BASE_URL}/api/v3/auc/bigmodel/recognize/flash`)
102 expect(init.method).toBe('POST')
103 expect(headers.get('x-api-key')).toBe('voice-key')
104 expect(headers.get('x-api-resource-id')).toBe('volc.seedasr.auc_turbo')
105
106 expect(body).toEqual({
107 user: { uid: 'tanstack-ai' },
108 audio: { url: 'https://example.com/guitar.mp3', format: 'mp3' },
109 request: { model_name: 'bigmodel', show_utterances: true },
110 })
111 })
112
113 it('maps transcript, segments, words and duration into seconds', async () => {
114 const result = await generateTranscription({
115 adapter: adapterWith(asrFetch()),
116 audio: 'https://example.com/guitar.mp3',
117 language: 'en-US',
118 })
119
120 expect(result.text).toBe('a guitar being played in a store')
121 expect(result.language).toBe('en-US')
122 expect(result.duration).toBe(2.499)
123 expect(result.segments).toEqual([
124 { id: 0, start: 0.45, end: 1.53, text: 'a guitar being played' },
125 { id: 1, start: 1.53, end: 2.4, text: 'in a store', speaker: '2' },
126 ])
127 expect(result.words).toEqual([
128 { word: 'a', start: 0.45, end: 0.6 },
129 { word: 'guitar', start: 0.6, end: 1.1 },
130 ])
131 expect(result.usage).toEqual({
132 promptTokens: 0,
133 completionTokens: 0,
134 totalTokens: 0,
135 billed: { quantity: 2.499, unit: 'seconds' },
136 durationSeconds: 2.499,
137 })
138 expect(result.id).toMatch(/^byteplus-/)
139 })
140
141 it('reads the flat transcript spelling when result is absent', async () => {
142 const result = await generateTranscription({
143 adapter: adapterWith(
144 asrFetch({
145 transcript: 'flat shape',
146 utterances: [{ text: 'flat shape', start_time: 0, end_time: 1000 }],
147 }),
148 ),
149 audio: 'https://example.com/a.wav',
150 })
151 expect(result.text).toBe('flat shape')
152 expect(result.segments).toEqual([
153 { id: 0, start: 0, end: 1, text: 'flat shape' },
154 ])
155 })
156
157 it('forwards recognition options and the language hint', async () => {
158 const fetchMock = asrFetch()
159 await generateTranscription({
160 adapter: adapterWith(fetchMock),
161 audio: 'https://example.com/a.mp3',
162 language: 'en-US',
163 modelOptions: {
164 enable_itn: true,
165 enable_punc: true,
166 enable_ddc: false,
167 enable_speaker_info: true,
168 show_utterances: false,
169 model_name: 'bigmodel',
170 uid: 'tenant-42',
171 },
172 })
173
174 const { body } = lastRequest(fetchMock)
175 expect(body.user).toEqual({ uid: 'tenant-42' })
176 expect(body.request).toEqual({
177 model_name: 'bigmodel',
178 show_utterances: false,
179 enable_itn: true,
180 enable_punc: true,
181 enable_ddc: false,
182 enable_speaker_info: true,
183 language: 'en-US',
184 })
185 })
186
187 it('lets modelOptions.language override the generic language', async () => {
188 const fetchMock = asrFetch()
189 const result = await generateTranscription({
190 adapter: adapterWith(fetchMock),
191 audio: 'https://example.com/a.mp3',
192 language: 'en',
193 modelOptions: { language: 'zh-CN' },
194 })
195 expect(lastRequest(fetchMock).body.request.language).toBe('zh-CN')
196 // The result reports the language actually sent, not the overridden hint.
197 expect(result.language).toBe('zh-CN')
198 })
199
200 describe('audio input normalisation', () => {
201 it('passes http(s) urls through and infers the container', async () => {
202 await expect(
203 normalizeAudioInput('https://example.com/a.wav?token=1', undefined),
204 ).resolves.toEqual({
205 url: 'https://example.com/a.wav?token=1',
206 format: 'wav',
207 })
208 })
209
210 it('splits data urls into base64 data plus a format', async () => {
211 await expect(
212 normalizeAudioInput('data:audio/mpeg;base64,QUJD', undefined),
213 ).resolves.toEqual({ data: 'QUJD', format: 'mp3' })
214 })
215
216 it('treats a bare string as base64 data', async () => {
217 await expect(normalizeAudioInput('QUJD', undefined)).resolves.toEqual({
218 data: 'QUJD',
219 })
220 })
221
222 it('base64-encodes binary inputs', async () => {
223 const bytes = new Uint8Array([1, 2, 3])
224 const expected = Buffer.from(bytes).toString('base64')
225
226 await expect(
227 normalizeAudioInput(bytes.buffer as ArrayBuffer, undefined),
228 ).resolves.toEqual({ data: expected })
229
230 await expect(
231 normalizeAudioInput(
232 new File([bytes], 'clip.flac', { type: 'audio/flac' }),
233 undefined,
234 ),
235 ).resolves.toEqual({ data: expected, format: 'flac' })
236
237 await expect(
238 normalizeAudioInput(
239 new Blob([bytes], { type: 'audio/ogg' }),
240 undefined,
241 ),
242 ).resolves.toEqual({ data: expected, format: 'ogg' })
243 })
244
245 it('lets modelOptions.audio_format win over the inferred container', async () => {
246 await expect(
247 normalizeAudioInput('https://example.com/a.wav', 'pcm'),
248 ).resolves.toEqual({ url: 'https://example.com/a.wav', format: 'pcm' })
249 })
250
251 it('sends encoded bytes as audio.data on a real request', async () => {
252 const fetchMock = asrFetch()
253 await generateTranscription({
254 adapter: adapterWith(fetchMock),
255 audio: new Uint8Array([1, 2, 3]).buffer as ArrayBuffer,
256 modelOptions: { audio_format: 'wav' },
257 })
258 expect(lastRequest(fetchMock).body.audio).toEqual({
259 data: Buffer.from([1, 2, 3]).toString('base64'),
260 format: 'wav',
261 })
262 })
263 })
264
265 describe('errors', () => {
266 it('surfaces the numeric Seed Speech error envelope on a 401', async () => {
267 const fetchMock = asrFetch(
268 { code: 45000010, message: 'Invalid X-Api-Key' },
269 401,
270 )
271 await expect(
272 generateTranscription({
273 adapter: adapterWith(fetchMock),
274 audio: 'https://example.com/a.mp3',
275 debug: false,
276 }),
277 ).rejects.toThrow(
278 'BytePlus Seed Speech transcription failed (401 45000010): Invalid X-Api-Key',
279 )
280 })
281
282 it('fails when a 200 response carries no transcript', async () => {
283 const fetchMock = asrFetch({ code: 45000151, message: 'Audio too long' })
284 await expect(
285 generateTranscription({
286 adapter: adapterWith(fetchMock),
287 audio: 'https://example.com/a.mp3',
288 debug: false,
289 }),
290 ).rejects.toThrow(
291 'BytePlus Seed Speech transcription failed (200 45000151): Audio too long',
292 )
293 })
294 })
295
296 describe('headers', () => {
297 it('merges configured default headers into the request', async () => {
298 const fetchMock = asrFetch()
299 await generateTranscription({
300 adapter: adapterWith(fetchMock, { 'X-Test-Id': 'abc' }),
301 audio: 'https://example.com/a.mp3',
302 })
303 expect(lastRequest(fetchMock).headers.get('x-test-id')).toBe('abc')
304 })
305
306 it('does not let default headers clobber the auth or resource headers', async () => {
307 const fetchMock = asrFetch()
308 await generateTranscription({
309 adapter: adapterWith(fetchMock, {
310 'X-Api-Key': 'attacker-key',
311 'X-Api-Resource-Id': 'volc.wrong.model',
312 'Content-Type': 'text/plain',
313 }),
314 audio: 'https://example.com/a.mp3',
315 })
316 const { headers } = lastRequest(fetchMock)
317 expect(headers.get('x-api-key')).toBe('voice-key')
318 expect(headers.get('x-api-resource-id')).toBe('volc.seedasr.auc_turbo')
319 expect(headers.get('content-type')).toBe('application/json')
320 })
321 })
322
323 describe('warnings for options the endpoint cannot honour', () => {
324 it('warns that prompt is ignored', async () => {
325 const logger = captureLogger()
326 await generateTranscription({
327 adapter: adapterWith(asrFetch()),
328 audio: 'https://example.com/a.mp3',
329 prompt: 'guitar shop vocabulary',
330 debug: { logger },
331 })
332 expect(
333 logger.warnings.some((w) => w.includes('`prompt` option is ignored')),
334 ).toBe(true)
335 })
336
337 it('warns that a non-json responseFormat is ignored', async () => {
338 const logger = captureLogger()
339 await generateTranscription({
340 adapter: adapterWith(asrFetch()),
341 audio: 'https://example.com/a.mp3',
342 responseFormat: 'srt',
343 debug: { logger },
344 })
345 expect(
346 logger.warnings.some(
347 (w) => w.includes('always returns JSON') && w.includes('"srt"'),
348 ),
349 ).toBe(true)
350 })
351
352 it('stays quiet for responseFormat json', async () => {
353 const logger = captureLogger()
354 await generateTranscription({
355 adapter: adapterWith(asrFetch()),
356 audio: 'https://example.com/a.mp3',
357 responseFormat: 'json',
358 debug: { logger },
359 })
360 expect(logger.warnings).toHaveLength(0)
361 })
362 })
363
364 describe('response mapping edges', () => {
365 it('skips utterances with no timings', async () => {
366 const mapped = mapRecognizeResponse(
367 {
368 result: {
369 text: 'partial',
370 utterances: [
371 { text: 'no timings' },
372 { text: 'timed', start_time: 0, end_time: 500 },
373 ],
374 },
375 },
376 'partial',
377 )
378 expect(mapped.segments).toEqual([
379 { id: 0, start: 0, end: 0.5, text: 'timed' },
380 ])
381 })
382
383 it('omits segments, words and usage entirely when nothing is timed', async () => {
384 const mapped = mapRecognizeResponse(
385 { result: { text: 'bare', utterances: [{ text: 'bare' }] } },
386 'bare',
387 )
388 expect(mapped.segments).toBeUndefined()
389 expect(mapped.words).toBeUndefined()
390 expect(mapped.usage).toBeUndefined()
391 expect(mapped.duration).toBeUndefined()
392 })
393
394 // The word-level drop filter had no coverage: every fixture in this file
395 // and in the e2e mount is fully timed, so a field rename upstream
396 // (`word.text` → `word.word`) would have emptied `words` — or shipped
397 // `{ word: undefined, start: NaN }` — with nothing failing.
398 it('drops words with missing or non-numeric timings', async () => {
399 const mapped = mapRecognizeResponse(
400 {
401 result: {
402 text: 'a b c',
403 utterances: [
404 {
405 text: 'a b c',
406 start_time: 0,
407 end_time: 900,
408 words: [
409 { text: 'a', start_time: 0, end_time: 300 },
410 { text: 'b', start_time: 300 },
411 { start_time: 600, end_time: 900 },
412 ],
413 },
414 ],
415 },
416 },
417 'a b c',
418 )
419
420 expect(mapped.words).toEqual([{ word: 'a', start: 0, end: 0.3 }])
421 })
422
423 it('warns when words are dropped rather than dropping them silently', async () => {
424 const logger = captureLogger()
425 mapRecognizeResponse(
426 {
427 result: {
428 text: 'a b',
429 utterances: [
430 {
431 text: 'a b',
432 start_time: 0,
433 end_time: 600,
434 words: [
435 { text: 'a', start_time: 0, end_time: 300 },
436 { text: 'b', start_time: 300 },
437 ],
438 },
439 ],
440 },
441 },
442 'a b',
443 resolveDebugOption({ logger }),
444 )
445
446 expect(
447 logger.warnings.some((w) => w.includes('dropped 1 of 2 word(s)')),
448 ).toBe(true)
449 })
450
451 it('warns when utterances are dropped rather than dropping them silently', async () => {
452 const logger = captureLogger()
453 mapRecognizeResponse(
454 {
455 result: {
456 text: 'partial',
457 utterances: [
458 { text: 'no timings' },
459 { text: 'timed', start_time: 0, end_time: 500 },
460 ],
461 },
462 },
463 'partial',
464 resolveDebugOption({ logger }),
465 )
466
467 expect(
468 logger.warnings.some((w) => w.includes('dropped 1 of 2 utterance(s)')),
469 ).toBe(true)
470 })
471
472 // An empty transcript is legitimate for silent audio, so it isn't an
473 // error — but it is also what a 200-wrapped failure looks like, and it
474 // used to be returned as a plain success with no signal at all.
475 it('warns on an empty transcript with no utterances', async () => {
476 const logger = captureLogger()
477 await generateTranscription({
478 adapter: adapterWith(asrFetch({ result: { text: '' } })),
479 audio: 'https://example.com/guitar.mp3',
480 debug: { logger },
481 })
482
483 expect(logger.warnings.some((w) => w.includes('empty transcript'))).toBe(
484 true,
485 )
486 })
487
488 it('surfaces per-word confidence for callers that narrow the type', async () => {
489 const result = await generateTranscription({
490 adapter: adapterWith(
491 asrFetch({
492 result: {
493 text: 'hi',
494 utterances: [
495 {
496 text: 'hi',
497 start_time: 0,
498 end_time: 500,
499 words: [
500 {
501 text: 'hi',
502 start_time: 0,
503 end_time: 500,
504 confidence: 0.98,
505 },
506 ],
507 },
508 ],
509 },
510 }),
511 ),
512 audio: 'https://example.com/a.mp3',
513 })
514 const words = result.words as Array<BytePlusTranscriptionWord> | undefined
515 expect(words?.[0]?.confidence).toBe(0.98)
516 })
517 })
518
519 it('keeps non-JSON error bodies diagnosable', async () => {
520 const fetchMock = vi
521 .fn<typeof fetch>()
522 .mockImplementation(() =>
523 Promise.resolve(new Response('<html>502</html>', { status: 502 })),
524 )
525 await expect(
526 generateTranscription({
527 adapter: adapterWith(fetchMock),
528 audio: 'https://example.com/a.mp3',
529 debug: false,
530 }),
531 ).rejects.toThrow('<html>502</html>')
532 })
533
534 it('createBytePlusTranscription wires the explicit key through', async () => {
535 const fetchMock = asrFetch()
536 const adapter = createBytePlusTranscription('seed-asr', 'explicit-key', {
537 baseURL: BASE_URL,
538 fetch: fetchMock,
539 })
540 await generateTranscription({
541 adapter,
542 audio: 'https://example.com/a.mp3',
543 })
544 expect(lastRequest(fetchMock).headers.get('x-api-key')).toBe('explicit-key')
545 })
546})