SDKs

JavaScript and TypeScript

Transcribe audio, build speaker timelines, and synthesize speech from Node.js or Bun with @humain-voice/sdk 0.18.1.

Install

npm install @humain-voice/[email protected]

Configure a client

Each workflow has its own client. Every client constructor takes one options object:

NameTypeDefaultMeaning
api_urlstringRequiredService base URL.
api_keystringRequiredAPI key.
api_pathstring/socket.ioSocket.IO path. Every client except batch.
api_versionstringv1REST version. BatchTranscribeClient only.

Examples read these from API_URL, API_KEY, API_PATH, and API_VERSION; see Connection settings.

WorkflowClientClean up with
Batch transcriptionBatchTranscribeClientclose()
Fast transcriptionFastTranscriptionClientclose()
Realtime transcriptionRealtimeClientdisconnect()
Live diarizationRealtimeDiarizationClientdisconnect()
Text to speechTTSClientclose()
Voice Agent sessionsAgentClient (from @humain-voice/sdk/agent)Nothing to close

Socket.IO clients connect on first use; call connect() first to fail fast on a bad key or URL. Clean up in finally. Language and model values are in Models and voices.

Batch transcription

transcribe(audio, lang, options) uploads a complete file, polls until the job is done, and returns the transcript with word offsets. To poll from a worker, call submit(audio, lang, options), then getResult(jobId, lang, { saveResult }) until done, failed, or cleared (see Batch is a job).

NameTypeDefaultMeaning
audioArrayBuffer, Uint8Array, Blob, or FileRequiredAudio to upload.
langLanguage or stringRequiredSpoken language.
asrBatchTranscriptionModel or stringUnsetASR model.
diarizationBatchDiarizationUnsetOn, D1, or D2 labels speakers.
itnbooleanUnsetInverse text normalization.
redactBatchRedactUnsetBatchRedact.On turns on redaction.
saveResultbooleanfalseKeep the result readable after it's fetched; see Read the result again. Not on submit().
pollIntervalnumber2Seconds between result reads. transcribe() only.
timeoutnumber300Polling limit in seconds. transcribe() only.
onProgress(status: TranscriptionResponse) => voidUnsetCalled with each result read. transcribe() only.
batch-transcription.ts
import { readFile, writeFile } from 'node:fs/promises';

import {
  BatchDiarization,
  BatchTranscribeClient,
  BatchTranscriptionModel,
  Language,
  Subtitles,
} from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

async function main(): Promise<void> {
  const inputPath = process.argv[2] ?? 'recording.wav';
  const outputPath = process.argv[3] ?? 'recording.vtt';
  const client = new BatchTranscribeClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    api_version: process.env.API_VERSION ?? 'v1',
  });

  try {
    const result = await client.transcribe(
      await readFile(inputPath),
      Language.ArEn,
      {
        asr: BatchTranscriptionModel.BayanArEn,
        diarization: BatchDiarization.On,
        saveResult: true,
        pollInterval: 2,
        timeout: 300,
        onProgress: ({ status }) => console.info('status:', status),
      },
    );

    console.info(result.results?.transcript ?? '');
    await writeFile(outputPath, Subtitles.fromResponse(result).toVtt(), 'utf8');
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative):

status: queued
status: processing
status: done
Hello and welcome to the meeting.

With diarization on, each word offset carries a speaker label. This example groups words into speaker turns:

batch-speakers.ts
import { readFile } from 'node:fs/promises';

import {
  BatchDiarization,
  BatchTranscribeClient,
  BatchTranscriptionModel,
  Language,
} from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

async function main(): Promise<void> {
  const inputPath = process.argv[2] ?? 'recording.wav';
  const client = new BatchTranscribeClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    api_version: process.env.API_VERSION ?? 'v1',
  });

  try {
    const result = await client.transcribe(await readFile(inputPath), Language.ArEn, {
      asr: BatchTranscriptionModel.BayanArEn,
      diarization: BatchDiarization.On,
      saveResult: true,
      timeout: 300,
      onProgress: ({ status }) => console.info('status:', status),
    });

    const turns: { speaker: string; words: string[] }[] = [];
    for (const offset of result.results?.offsets ?? []) {
      const speaker = offset.speaker ?? 'UNKNOWN_SPEAKER';
      const last = turns[turns.length - 1];
      if (last?.speaker === speaker) last.words.push(offset.word);
      else turns.push({ speaker, words: [offset.word] });
    }
    for (const turn of turns) console.info(`${turn.speaker}: ${turn.words.join(' ')}`);
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative; labels are opaque strings):

status: processing
status: done
SPEAKER_1: Hello and welcome to the meeting.
SPEAKER_2: Thanks for having me.

Fast transcription

FastTranscriptionClient.transcribe(audio_source, language, asr_model, options) sends one short, complete clip over Socket.IO and resolves with the final result. The SDK sets no deadline, so wrap the call in your own, as the example does. Send longer recordings to batch; see Fast transcription limits.

NameTypeDefaultMeaning
audio_sourceArrayBuffer, Uint8Array, or BlobRequiredClip to transcribe.
languageLanguageRequiredSpoken language.
asr_modelFastTranscriptionModel or stringRequiredASR model.
onResponsefunctionUnsetReceives partial results, then the final one.
onFileUploadfunctionUnsetReceives the upload receipt.
onErrorfunctionUnsetReceives an ErrorResponse.
fast-transcription.ts
import { readFile, writeFile } from 'node:fs/promises';

import {
  FastTranscriptionClient,
  FastTranscriptionModel,
  Language,
  Subtitles,
} from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

function socketPath(): { api_path?: string } {
  const value = process.env.API_PATH;
  return value ? { api_path: value } : {};
}

async function withDeadline<T>(operation: Promise<T>, milliseconds: number): Promise<T> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  try {
    return await Promise.race([
      operation,
      new Promise<never>((_, reject) => {
        timer = setTimeout(
          () => reject(new Error('Fast transcription deadline exceeded')),
          milliseconds,
        );
      }),
    ]);
  } finally {
    if (timer) clearTimeout(timer);
  }
}

async function main(): Promise<void> {
  const inputPath = process.argv[2] ?? 'recording.wav';
  const outputPath = process.argv[3] ?? 'recording.vtt';
  const client = new FastTranscriptionClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    ...socketPath(),
  });

  try {
    await client.connect();
    const result = await withDeadline(
      client.transcribe(
        await readFile(inputPath),
        Language.ArEn,
        FastTranscriptionModel.BayanArEn,
        {
          onFileUpload: (response) => console.info('status:', 'uploaded', response?.id),
          onResponse: (response) => {
            console.info(response.is_final ? 'final:' : 'partial:', response.transcription);
          },
          onError: (error) => console.error('error:', error.code, error.message),
        },
      ),
      60_000,
    );

    if (!result) throw new Error('Fast transcription ended without a final result');
    await writeFile(outputPath, Subtitles.fromResponse(result).toVtt(), 'utf8');
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative):

status: uploaded 3f1c2a9e-5b7d-4e8a-9c41-0d2e6f8b7a15
partial: Hello and
final: Hello and welcome to the meeting.

Realtime transcription

RealtimeClient.startStream(language, options) opens a stream. Send PCM16 little-endian, 16 kHz, mono audio with stream.send(), then call stream.close() to wait for is_final; stream.stop() ends without waiting. See Streaming results are state, not a log.

CallArgumentTypeDefaultMeaning
startStream()languageLanguageRequiredSpoken language.
startStream()onResponsefunctionUnsetReceives provisional and final results.
startStream()onErrorfunctionUnsetReceives an ErrorResponse.
stream.send()audioBytesUint8ArrayRequiredOne audio chunk.
stream.close()timeoutSecondsnumber1Wait for is_final. Pass 5.

The example sends 3,200-byte (100 ms) chunks and writes captions from the final words. To make recording.pcm, see Prepare audio.

realtime-transcription.ts
import { readFile, writeFile } from 'node:fs/promises';

import {
  type ErrorResponse,
  Language,
  RealtimeClient,
  Subtitles,
  type WordSegment,
} from '@humain-voice/sdk';

const CHUNK_BYTES = 3_200; // 100 ms of PCM16LE, 16 kHz, mono audio.

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

function socketPath(): { api_path?: string } {
  const value = process.env.API_PATH;
  return value ? { api_path: value } : {};
}

async function pause(milliseconds: number): Promise<void> {
  await new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
}

async function main(): Promise<void> {
  const inputPath = process.argv[2] ?? 'recording.pcm';
  const outputPath = process.argv[3] ?? 'recording.vtt';
  const client = new RealtimeClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    ...socketPath(),
  });
  const finalizedWords: WordSegment[] = [];
  let serverError: ErrorResponse | undefined;
  let protocolFinalObserved = false;

  try {
    const stream = await client.startStream(Language.ArEn, {
      onResponse: (response) => {
        const kind = response.is_final
          ? 'final'
          : response.is_speech_final
            ? 'speech-final'
            : 'partial';
        console.info(`${kind}:`, response.transcription);
        if (response.is_final) protocolFinalObserved = true;
        if (response.is_final || response.is_speech_final) {
          // seq is not guaranteed to increase, so keep words in arrival order.
          finalizedWords.push(...response.words);
        }
      },
      onError: (error) => {
        console.error('error:', error.code, error.message);
        serverError = error;
      },
    });

    const pcm = await readFile(inputPath);
    try {
      for (let offset = 0; offset < pcm.length; offset += CHUNK_BYTES) {
        if (serverError) break;
        await stream.send(pcm.subarray(offset, offset + CHUNK_BYTES));
        await pause(100);
      }
      // Resolves (does not throw) if is_final has not arrived within 5 s.
      if (!serverError) await stream.close(5);
    } catch (error: unknown) {
      // The SDK drops the stream on a server error, so send() and close() throw.
      if (!serverError) throw error;
    }
    if (serverError) {
      throw new Error(serverError.message ?? serverError.code ?? 'Realtime stream failed');
    }
    if (!protocolFinalObserved) {
      throw new Error('Realtime stream ended before protocol is_final');
    }
    await writeFile(outputPath, Subtitles.fromWords(finalizedWords).toVtt(), 'utf8');
  } finally {
    await client.disconnect();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative):

partial: Hello and
speech-final: Hello and welcome to the meeting.
partial: Let's start
final: Let's start with the agenda.

Live diarization

RealtimeDiarizationClient.startStream({ onUpdate }) reports who is speaking while you send() realtime-format PCM in 15,360-byte (480 ms) chunks, DIARIZATION_RECOMMENDED_CHUNK_BYTES. Each update carries the full timeline in segments and new final segments in newlyFinalized. stream.close(5) resolves with the final timeline, and toRttm() renders it as RTTM.

realtime-diarization.ts
import { readFile, writeFile } from 'node:fs/promises';

import {
  DIARIZATION_RECOMMENDED_CHUNK_BYTES,
  RealtimeDiarizationClient,
  type SpeakerSegment,
  toRttm,
} from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

function socketPath(): { api_path?: string } {
  const value = process.env.API_PATH;
  return value ? { api_path: value } : {};
}

async function pause(milliseconds: number): Promise<void> {
  await new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
}

async function main(): Promise<void> {
  const inputPath = process.argv[2] ?? 'recording.pcm';
  const outputPath = process.argv[3] ?? 'recording.rttm';
  const client = new RealtimeDiarizationClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    ...socketPath(),
  });

  try {
    let finalObserved = false;
    const stream = await client.startStream({
      onError: (error) => console.error('error:', error.code, error.message),
      onUpdate: (update) => {
        finalObserved ||= update.isFinal;
        for (const segment of update.newlyFinalized) {
          console.info(segment.speaker, segment.start_time, segment.end_time);
        }
      },
    });
    const pcm = await readFile(inputPath);

    if (pcm.length === 0 || pcm.length % 2 !== 0) {
      throw new Error('Input must be nonempty PCM16 with an even byte length');
    }
    for (
      let offset = 0;
      offset < pcm.length;
      offset += DIARIZATION_RECOMMENDED_CHUNK_BYTES
    ) {
      await stream.send(
        pcm.subarray(offset, offset + DIARIZATION_RECOMMENDED_CHUNK_BYTES),
      );
      await pause(480);
    }

    // Returns the best-known timeline after 5 s even without a final update.
    const timeline: SpeakerSegment[] = await stream.close(5);
    const destination = finalObserved ? outputPath : `${outputPath}.partial`;
    await writeFile(destination, toRttm(timeline, 'recording'), 'utf8');
    if (!finalObserved) {
      console.info(
        'status:',
        `Final result not observed; wrote incomplete output to ${destination}`,
      );
    }
  } finally {
    await client.disconnect();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative):

SPEAKER_01 0 3.84
SPEAKER_02 3.84 7.2
SPEAKER_01 7.2 11.52

Text to speech

TTSClient returns raw PCM16 little-endian mono audio at getSampleRate(model) Hz (24,000 for the default TtsModel.Nebula). listVoices({ timeoutSeconds }) resolves with { id, label, profile? } objects:

list-voices.ts
import { TTSClient } from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

function socketPath(): { api_path?: string } {
  const value = process.env.API_PATH;
  return value ? { api_path: value } : {};
}

async function main(): Promise<void> {
  const client = new TTSClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    ...socketPath(),
  });

  try {
    for (const voice of await client.listVoices({ timeoutSeconds: 5 })) {
      const dialect = voice.profile?.speaker.dialect ?? '';
      const languages = voice.profile?.languages.join(',') ?? '';
      console.info(voice.id, voice.label, dialect, languages);
    }
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative; IDs vary by environment):

42e38a63-849a-481a-b5bf-3c1b7a985de3 mul_nourah ars ar,en
af52a907-1086-46f7-8f5d-72317875d7bd mul_youssef arz ar,en

In 0.18.1, or 0.19.0-beta.3 or later, profile can also have emotions and styles (string[]). They're absent where emotion and speaking style aren't enabled; see Voice list.

synthesize(text, options) resolves with the whole clip as one Uint8Array; synthesizeStream(text, options) yields { id, is_last, audio } chunks. Pass exactly one of voice_id or voice_references.

NameTypeDefaultMeaning
textstringRequiredText to speak.
voice_idstringUnsetVoice ID from listVoices().
voice_references{ text: string; audio: string }[]UnsetReference clips to clone; audio is base64 WAV.
modelTtsModel or stringTtsModel.NebulaTTS model.
timeoutSecondsnumber30Wait for each next chunk; 0 turns it off.
onAudiofunctionUnsetReceives each chunk. synthesize() only.
onErrorfunctionUnsetReceives an ErrorResponse.
request_idstringGeneratedRequest ID.

This example adds a WAV header and writes speech.wav:

tts-to-wav.ts
import { writeFile } from 'node:fs/promises';

import {
  TTSClient,
  TtsModel,
  getSampleRate,
} from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

function socketPath(): { api_path?: string } {
  const value = process.env.API_PATH;
  return value ? { api_path: value } : {};
}

function pcm16ToWav(pcm: Uint8Array, sampleRate: number): Buffer {
  const header = Buffer.alloc(44);
  header.write('RIFF', 0);
  header.writeUInt32LE(36 + pcm.byteLength, 4);
  header.write('WAVE', 8);
  header.write('fmt ', 12);
  header.writeUInt32LE(16, 16);
  header.writeUInt16LE(1, 20); // Linear PCM.
  header.writeUInt16LE(1, 22); // Mono.
  header.writeUInt32LE(sampleRate, 24);
  header.writeUInt32LE(sampleRate * 2, 28);
  header.writeUInt16LE(2, 32);
  header.writeUInt16LE(16, 34);
  header.write('data', 36);
  header.writeUInt32LE(pcm.byteLength, 40);

  return Buffer.concat([
    header,
    Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength),
  ]);
}

async function main(): Promise<void> {
  const text = process.argv[2] ?? 'Hello from HUMAIN Voice';
  const outputPath = process.argv[3] ?? 'speech.wav';
  const client = new TTSClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    ...socketPath(),
  });

  try {
    const voices = await client.listVoices({ timeoutSeconds: 5 });
    const voice = voices.find((candidate) => candidate.profile) ?? voices[0];
    if (!voice) throw new Error('No TTS voices are available');
    if (voice.profile) {
      console.info(
        'status:',
        'voice',
        voice.label,
        voice.profile.speaker.dialect,
        voice.profile.languages,
      );
    }

    const model = TtsModel.Nebula;
    const pcm = await client.synthesize(text, {
      voice_id: voice.id,
      model,
      // Inactivity timeout per audio chunk, not a total deadline.
      timeoutSeconds: 30,
      onError: (error) => console.error('error:', error.code, error.message),
    });

    await writeFile(outputPath, pcm16ToWav(pcm, getSampleRate(model)));
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative):

status: voice mul_nourah ars [ 'ar', 'en' ]

This example streams audio to stdout:

node tts-stream.ts "Hello from HUMAIN Voice" | ffplay -f s16le -ar 24000 -ch_layout mono -
tts-stream.ts
import { TTSClient, TtsModel, getSampleRate } from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

function socketPath(): { api_path?: string } {
  const value = process.env.API_PATH;
  return value ? { api_path: value } : {};
}

async function main(): Promise<void> {
  const text = process.argv[2] ?? 'Hello from HUMAIN Voice';
  const model = TtsModel.Nebula;
  const client = new TTSClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    ...socketPath(),
  });

  try {
    const [voice] = await client.listVoices({ timeoutSeconds: 5 });
    if (!voice) throw new Error('No TTS voices are available');

    // Audio goes to stdout, so logs go to stderr.
    console.error('status: sample rate', getSampleRate(model));
    for await (const chunk of client.synthesizeStream(text, {
      voice_id: voice.id,
      model,
      timeoutSeconds: 30,
      onError: (error) => console.error('error:', error.code, error.message),
    })) {
      process.stdout.write(chunk.audio);
    }
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output on stderr (illustrative):

status: sample rate 24000

See Speech output to choose a mode and Models and voices for voices.

Voice agent sessions

AgentClient, imported from @humain-voice/sdk/agent, starts Voice Agent sessions from your server. It needs the beta release:

npm install @humain-voice/[email protected]

It takes api_url and api_key and holds no connection, so there's nothing to close. createSession(options) sends one session request:

NameTypeDefaultMeaning
participant{ identity: string; name?: string; gender?: 'male' | 'female' }RequiredThe user who joins the call.
agentAgentConfigUnsetprompt, intro, voiceId, clientTools, and toolAcknowledgments (with afterMs). Tool parameters are sent unchanged.
variablesRecord<string, string | number | boolean>UnsetValues for {{name}} placeholders.
idempotencyKeystringUnsetSent as Idempotency-Key, so a retry returns the first session.
timeoutSecondsnumber10Request timeout.

It returns AgentSessionCredentials with serverUrl, participantToken, sessionId, expiresAt (Date), effective, and limits. effective and limits use camelCase names, and a null limit means none. tokenResponse() returns { server_url, participant_token } to send to the browser:

import { AgentClient, AgentError } from '@humain-voice/sdk/agent';

const agent = new AgentClient({ api_url: process.env.API_URL!, api_key: process.env.API_KEY! });

try {
  const session = await agent.createSession({
    participant: { identity: 'user-123' },
    agent: { prompt: 'You help {{name}} with their orders.', intro: 'Hi {{name}}!' },
    variables: { name: 'Sara' },
  });
  console.log('session:', session.sessionId, session.expiresAt.toISOString());
} catch (err) {
  if (err instanceof AgentError) console.error('error:', err.code, err.statusCode, err.data);
  throw err;
}

A failed request throws AgentError with statusCode, code, retryable, retryAfter (seconds), and data; validation problems are in data.errors. AgentAuthError (401) and AgentRateLimitError (429) are subclasses, as with batch errors. The browser side is @humain-voice/agent.

Subtitles

Subtitles.fromResponse(result, options) builds cues from a batch or fast result; Subtitles.fromWords(words, options) takes any word list. toVtt(options) and toSrt(options) render them and accept maxCharsPerLine, maxLines, and strict.

NameTypeDefaultMeaning
maxDurationSecondsnumber6Longest cue.
maxGapSecondsnumber0.7Silence that starts a new cue.
minDurationSecondsnumber0.5Shortest cue.
maxCharsPerLinenumber42Line width.
maxLinesnumber2Lines per cue.
splitOnSpeakerChangebooleantrueStart a new cue when the speaker changes.
strictbooleanfalseThrow SubtitleError on malformed timing instead of fixing or skipping it.

For realtime captions, collect the words of each is_speech_final and is_final result and call Subtitles.fromWords(), as the realtime example does.

Errors

Batch methods throw subclasses of BatchTranscribeError:

ClassWhenFields
BatchTranscribeErrorAny non-2xx response, or empty api_url / api_keystatusCode, code, retryable, jobId, capacity, rawBody
BatchTranscribeAuthError401Same as above
BatchTranscribeRateLimitError429retryAfter (seconds; unset unless Retry-After is an integer)
BatchTranscribeJobFailedErrorThe job reached failederror, errorCode
BatchTranscribeTimeoutErrortranscribe() ran past timeoutjobId, elapsed

Network failures from fetch throw TypeError; retry them on getResult() reads. Socket.IO clients pass an ErrorResponse to onError: branch on code and retryable, and read retry_after_seconds, data, and retry_scope (new_stream means open a new stream). Diarization iterators throw DiarizationStreamError, whose response is the ErrorResponse. Codes and retry rules are in Errors and limits.

This example retries a batch result read, including after a network failure, with backoff and saveResult: true:

batch-error-retry.ts
import {
  BatchTranscribeClient,
  BatchTranscribeError,
  BatchTranscribeRateLimitError,
  Language,
  type TranscriptionResponse,
} from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

async function pause(milliseconds: number): Promise<void> {
  await new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
}

async function getResultWithRetry(
  client: BatchTranscribeClient,
  jobId: string,
  attempts = 5,
): Promise<TranscriptionResponse> {
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
    try {
      // saveResult keeps the stored result readable for a retry.
      return await client.getResult(jobId, Language.ArEn, { saveResult: true });
    } catch (error: unknown) {
      let retryable: boolean;
      let serverDelayMs = 0;
      if (error instanceof BatchTranscribeError) {
        retryable = error instanceof BatchTranscribeRateLimitError || error.retryable === true;
        if (error instanceof BatchTranscribeRateLimitError && error.retryAfter !== undefined) {
          serverDelayMs = error.retryAfter * 1_000;
        }
        console.error('error:', error.code ?? '', error.statusCode ?? '', error.capacity ?? '');
      } else if (error instanceof TypeError) {
        // fetch reports network failures as TypeError; a result read is safe to retry.
        retryable = true;
        console.error('error:', 'network', error.message);
      } else {
        throw error;
      }
      if (!retryable || attempt === attempts) throw error;

      const exponentialDelayMs = 500 * 2 ** (attempt - 1);
      await pause(Math.max(serverDelayMs, exponentialDelayMs) + Math.random() * 250);
    }
  }

  throw new Error('Retry loop exhausted');
}

async function main(): Promise<void> {
  const jobId = process.argv[2];
  if (!jobId) throw new Error('Pass a batch job ID as the first argument');

  const client = new BatchTranscribeClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    api_version: process.env.API_VERSION ?? 'v1',
  });
  try {
    const result = await getResultWithRetry(client, jobId);
    console.info('status:', result.status);
    console.info(result.results?.transcript ?? '');
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Pass a job ID as the first argument. Expected output (illustrative):

error: SERVER_INTERNAL 500
status: done
Hello and welcome to the meeting.

Retry submit() only on 429 or 503. After a 500, a timeout, or a dropped connection, a job may exist; see Retries and duplicates.

Timeouts and defaults

Values are in seconds.

ClientOptionDefaultBounds
BatchTranscribeClientpollInterval2Wait between result reads in transcribe().
BatchTranscribeClienttimeout300Polling in transcribe() after the upload. Throws BatchTranscribeTimeoutError.
FastTranscriptionClientNoneNoneNo SDK timeout; apply your own deadline.
RealtimeClienttimeoutSeconds on stream.close()1Wait for is_final; resolves without an error on timeout. Pass close(5).
RealtimeDiarizationClienttimeoutSeconds on stream.close()5Wait for the final update; resolves with the best-known timeline.
TTSClienttimeoutSeconds on listVoices()5Wait for the voice list.
TTSClienttimeoutSeconds on synthesize() / synthesizeStream()30Wait for each next chunk. 0 turns it off.

The server applies its own TTS deadlines; see Timeouts.

Next steps

On this page