Skip to Content
Vatis TechAPI docs
Real-time transcription

Reconnect after a restart

Connect again after a session ends early, and send the audio from where the transcript is complete.

A live session can end before you send end: the API is updated (it is, without a break in service), a speech service restarts, the network drops, or no session is free for a moment. Connect again and send the audio from where the transcript is complete: the finals then read as one session, with no gap and nothing twice.

When the server restarts, open sessions do not just drop. It stops taking audio, sends the final messages of everything it received, then the error service_restart, and closes with code 1012. With speaker_updates=true, the final.speakers of those finals come before the error too. A connection that arrives meanwhile gets the same error before session.started, with resume_s 0.

{"type": "final", "segment_id": 7, "text": "Vă mulțumesc.", "start": 61.2, "end": 62.0, "speaker": null}
{"type": "error", "code": "service_restart", "message": "The service is restarting: connect again in a few seconds.", "resume_s": 62.0}
(close 1012)

resume_s is in seconds of the session that ends: the transcript is complete exactly up to there, the end of the last final. A word being spoken at the instant the server stops is left out of the last final, so it comes whole in the next session, never twice.

  1. Keep the audio since the start of the last final (resume_s is never earlier). A live source goes on while you connect again: keep its new audio too.
  2. Connect again after a short wait (a quarter of a second, then longer), with a new token in a web page. Stop on an error that a new session would get again (below).
  3. Send the kept audio first, from where the transcript is complete: resume_s when the error has it, else the end of the last final. Send it as fast as the API takes it, at most 1 s per frame, then the live audio as it comes.
  4. Join the new session to the last one. The new session starts again at 0: its times, its segment_id (at 1) and its speaker labels (at speaker_0; the same person may get another label). Add the point where it starts to its times, and the last segment_id you had to its ids.

With two channels, resume_s is the earlier of the two channels' points: send the audio of both again from there, and keep a channel's new words from the end of that channel's own last final. After an end without resume_s (a dropped connection, a failure), a word being spoken at that instant can come out in two pieces.

When to connect again

The session ended withConnect again
service_restart close 1012yes
transcriber_error close 1011, 1012yes: a speech service stopped or failed. While it restarts, new sessions can be refused the same way: keep trying for a few minutes.
internal_error close 1011yes
capacity close 1013a few times, for about half a minute. If it stays, all your workspace's live sessions are in use: wait for one to end.
no error message close 1006 (or 1001, 1011)yes: the connection dropped
unauthorizedinvalid_parameteraudio_chunk_too_largeidle_timeout no: a new session gets the same answer
session_time_limit close 1008yes, at once: the session ran for 4 hours, the longest a session runs. Its transcript is complete up to the audio you sent.
the workspace is paused
(an error before session.started)
close 1013
not until credit is added, or the last hour's spend is under the limit again

A program that reconnects

This program reads a WAV file as if it were a live source, carries one transcript over as many sessions as it takes, and prints each final with its time in the whole recording. A file can be sent again from any point; with a live source, keep the audio as in step 1 above.

// A live session carried over early ends: node realtime_resume.mjs speech.wav
// Needs Node.js 22 or newer, no packages. The audio: a 16 kHz 16-bit mono WAV.
import { readFileSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";

const url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
const headers = { Authorization: `Bearer ${process.env.VATIS_KEY}` };
const params = { model_id: "vatis_ro_v9_realtime" };
// errors a new session would get again: stop
const STOP = new Set(["unauthorized", "invalid_parameter", "audio_chunk_too_large", "idle_timeout"]);
const BYTES_PER_S = 16000 * 2;

const wav = readFileSync(process.argv[2]);
const audio = wav.subarray(wav.indexOf("data") + 8);

// One session, from second startS of the audio on. Resolves with where the transcript is complete, the last
// segment id, whether the session started, and its close code.
function session(startS, lastId) {
  return new Promise((resolve) => {
    const baseId = lastId;
    let completeS = startS, error = null, started = false;
    const ws = new WebSocket(`${url}?${new URLSearchParams(params)}`, { headers });

    async function sendAudio() {
      const chunk = BYTES_PER_S / 10; // 100 ms
      for (let i = Math.floor((startS * BYTES_PER_S) / 2) * 2; i < audio.length && ws.readyState === WebSocket.OPEN; i += chunk) {
        ws.send(audio.subarray(i, i + chunk));
        await sleep(100);
      }
      if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "end" }));
    }

    ws.onmessage = (event) => {
      const message = JSON.parse(event.data);
      if (message.type === "session.started") {
        started = true;
        sendAudio();
      } else if (message.type === "final") {
        // this session's times and ids start again at 0: move them
        lastId = baseId + message.segment_id;
        completeS = startS + message.end;
        console.log(`[${(startS + message.start).toFixed(2).padStart(7)}] ${message.text}`);
      } else if (message.type === "error") {
        error = message;
      }
    };
    ws.onerror = () => {}; // the close that follows says what happened
    ws.onclose = (event) => {
      if (error && STOP.has(error.code)) {
        console.error(`error ${error.code}: ${error.message}`);
        process.exit(1);
      }
      if (error?.resume_s !== undefined) completeS = startS + error.resume_s; // the server's resume point
      resolve({ completeS, lastId, started, code: event.code });
    };
  });
}

let startS = 0, lastId = 0, tries = 0;
while (tries < 15) { // about a minute without a session: stop
  const result = await session(startS, lastId);
  if (result.code === 1000) process.exit(0); // the whole recording is transcribed
  ({ completeS: startS, lastId } = result);
  tries = result.started ? 1 : tries + 1;
  console.log(`connecting again from ${startS.toFixed(2)} s`);
  await sleep(Math.min(250 * 2 ** (tries - 1), 5000));
}
console.error("no session for a minute: stopping");
process.exit(1);

On this page