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

transcription.test.ts

562 lines17.2 KB

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