# 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](https://platform.vatis.tech/docs/realtime/reconnect-after-a-restart#when-to-connect-again)).
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 with | Connect again |
|---|---|
| `service_restart` close 1012 | yes |
| `transcriber_error` close 1011, 1012 | yes: 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 1011 | yes |
| `capacity` close 1013 | a 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 |
| `unauthorized` `invalid_parameter` `audio_chunk_too_large` `idle_timeout` | no: a new session gets the same answer |
| `session_time_limit` close 1008 | yes, 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.

```javascript
// 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);
```

```go
// A live session carried over early ends: go run . speech.wav
// Needs Go 1.23 or newer and a WebSocket package. In a new folder:
// go mod init resume && go get github.com/coder/websocket, save this as main.go
// The audio: a 16 kHz 16-bit mono WAV.
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/coder/websocket"
)

const wsURL = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime"
const bytesPerS = 16000 * 2

var headers = http.Header{
	"Authorization": {"Bearer " + os.Getenv("VATIS_KEY")},
}
var params = url.Values{"model_id": {"vatis_ro_v9_realtime"}}

// errors a new session would get again: stop
var stop = map[string]bool{
	"unauthorized":          true,
	"invalid_parameter":     true,
	"audio_chunk_too_large": true,
	"idle_timeout":          true,
}

// Message holds what this code reads of the session's messages.
type Message struct {
	Type      string
	SegmentID int `json:"segment_id"`
	Text      string
	Start     float64
	End       float64
	Code      string
	Message   string
	ResumeS   *float64 `json:"resume_s"`
}

var audio []byte

func main() {
	wav, err := os.ReadFile(os.Args[1])
	check(err)
	audio = wav[bytes.Index(wav, []byte("data"))+8:]

	startS, lastID, tries := 0.0, 0, 0
	for tries < 15 { // about a minute without a session: stop
		completeS, id, started, code := session(startS, lastID)
		if code == websocket.StatusNormalClosure {
			return // the whole recording is transcribed
		}
		startS, lastID = completeS, id
		if started {
			tries = 1
		} else {
			tries++
		}
		fmt.Printf("connecting again from %.2f s\n", startS)
		time.Sleep(min(250*time.Millisecond<<(tries-1), 5*time.Second))
	}
	fmt.Fprintln(os.Stderr, "no session for a minute: stopping")
	os.Exit(1)
}

// session runs one session, from second startS of the audio on. It returns where the
// transcript is complete, the last segment id, whether the session started, and its close
// code (-1: none, the connection failed or dropped).
func session(startS float64, lastID int) (float64, int, bool, websocket.StatusCode) {
	baseID, completeS, started := lastID, startS, false
	var failure *Message // the error message, if one came
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	options := &websocket.DialOptions{HTTPHeader: headers}
	ws, _, err := websocket.Dial(ctx, wsURL+"?"+params.Encode(), options)
	if err != nil {
		return completeS, lastID, false, -1 // not connected
	}
	defer ws.CloseNow()

	var code websocket.StatusCode
	for {
		_, raw, err := ws.Read(ctx)
		if err != nil {
			code = websocket.CloseStatus(err) // -1: the connection dropped
			break
		}
		var message Message
		check(json.Unmarshal(raw, &message))
		switch message.Type {
		case "session.started":
			started = true
			go sendAudio(ctx, ws, startS)
		case "final":
			// this session's times and ids start again at 0: move them
			lastID = baseID + message.SegmentID
			completeS = startS + message.End
			fmt.Printf("[%7.2f] %s\n", startS+message.Start, message.Text)
		case "error":
			failure = &message
		}
	}
	if failure != nil && stop[failure.Code] {
		fmt.Fprintf(os.Stderr, "error %s: %s\n", failure.Code, failure.Message)
		os.Exit(1)
	}
	if failure != nil && failure.ResumeS != nil {
		completeS = startS + *failure.ResumeS // the server's resume point
	}
	return completeS, lastID, started, code
}

// sendAudio sends the audio from second startS on, at real-time pace, then end.
func sendAudio(ctx context.Context, ws *websocket.Conn, startS float64) {
	const chunk = bytesPerS / 10 // 100 ms
	for i := int(startS*bytesPerS) / 2 * 2; i < len(audio); i += chunk {
		piece := audio[i:min(i+chunk, len(audio))]
		if ws.Write(ctx, websocket.MessageBinary, piece) != nil {
			return // the session ended early
		}
		time.Sleep(100 * time.Millisecond)
	}
	ws.Write(ctx, websocket.MessageText, []byte(`{"type": "end"}`))
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
"""A live session carried over early ends: python3 realtime_resume.py speech.wav
Needs Python 3.10 or newer and websockets (pip install --upgrade websockets). The audio: a 16 kHz 16-bit mono WAV."""
import asyncio
import json
import os
import sys
import wave
from urllib.parse import urlencode

from websockets.asyncio.client import connect
from websockets.exceptions import ConnectionClosed, InvalidHandshake

url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}
params = {"model_id": "vatis_ro_v9_realtime"}
# errors a new session would get again: stop
STOP = {"unauthorized", "invalid_parameter", "audio_chunk_too_large", "idle_timeout"}
BYTES_PER_S = 16000 * 2

with wave.open(sys.argv[1]) as wav:
    audio = wav.readframes(wav.getnframes())

async def session(start_s, last_id):
    """One session, from second start_s of the audio on: where the transcript is complete, the last segment id,
    whether the session started, and its close code."""
    complete_s, base_id, error, started = start_s, last_id, None, False
    async with connect(f"{url}?{urlencode(params)}", additional_headers=headers) as ws:

        async def send_audio():
            chunk = BYTES_PER_S // 10  # 100 ms
            try:
                for i in range(int(start_s * BYTES_PER_S) // 2 * 2, len(audio), chunk):
                    await ws.send(audio[i:i + chunk])
                    await asyncio.sleep(0.1)
                await ws.send(json.dumps({"type": "end"}))
            except ConnectionClosed:
                pass  # the session ended early

        sender = None
        try:
            async for raw in ws:
                message = json.loads(raw)
                if message["type"] == "session.started":
                    started, sender = True, asyncio.create_task(send_audio())
                elif message["type"] == "final":
                    # this session's times and ids start again at 0: move them
                    last_id = base_id + message["segment_id"]
                    complete_s = start_s + message["end"]
                    print(f"[{start_s + message['start']:7.2f}] {message['text']}")
                elif message["type"] == "error":
                    error = message
        except ConnectionClosed:
            pass  # closed with another code than 1000: an error, or a dropped connection
        finally:
            if sender:
                sender.cancel()
    if error and error["code"] in STOP:
        sys.exit(f"error {error['code']}: {error['message']}")
    if error and "resume_s" in error:
        complete_s = start_s + error["resume_s"]  # the server's resume point
    return complete_s, last_id, started, ws.close_code

async def main():
    start_s, last_id, tries = 0.0, 0, 0
    while tries < 15:  # about a minute without a session: stop
        started, code = False, None
        try:
            start_s, last_id, started, code = await session(start_s, last_id)
        except (OSError, InvalidHandshake):
            pass  # not connected
        if code == 1000:
            return  # the whole recording is transcribed
        tries = 1 if started else tries + 1
        print(f"connecting again from {start_s:.2f} s")
        await asyncio.sleep(min(0.25 * 2 ** (tries - 1), 5.0))
    sys.exit("no session for a minute: stopping")

asyncio.run(main())
```

```java
// A live session carried over early ends: java RealtimeResume.java speech.wav
// Needs Java 11 or newer, nothing to install. The audio: a 16 kHz 16-bit mono WAV.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RealtimeResume {
    static final String url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
    static final String params = "model_id=vatis_ro_v9_realtime";
    // errors a new session would get again: stop
    static final Set<String> STOP = Set.of("unauthorized", "invalid_parameter",
        "audio_chunk_too_large", "idle_timeout");
    static final int BYTES_PER_S = 16000 * 2;
    static final HttpClient http = HttpClient.newHttpClient();
    static byte[] audio;

    public static void main(String[] args) throws Exception {
        byte[] wav = Files.readAllBytes(Path.of(args[0]));
        String header = new String(wav, StandardCharsets.ISO_8859_1);
        audio = Arrays.copyOfRange(wav, header.indexOf("data") + 8, wav.length);

        double startS = 0;
        int lastId = 0, tries = 0;
        while (tries < 15) { // about a minute without a session: stop
            Session result = session(startS, lastId);
            if (result.code == WebSocket.NORMAL_CLOSURE) {
                return; // the whole recording is transcribed
            }
            startS = result.completeS;
            lastId = result.lastId;
            tries = result.started ? 1 : tries + 1;
            System.out.printf(Locale.ROOT, "connecting again from %.2f s%n", startS);
            Thread.sleep(Math.min(250L << (tries - 1), 5000));
        }
        System.err.println("no session for a minute: stopping");
        System.exit(1);
    }

    // One session, from second startS of the audio on. Returns it once it is closed: where
    // the transcript is complete, the last segment id, whether it started, its close code.
    static Session session(double startS, int lastId) {
        Session session = new Session(startS, lastId);
        try {
            http.newWebSocketBuilder()
                .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
                .buildAsync(URI.create(url + "?" + params), session)
                .join();
            session.code = session.closed.join();
        } catch (CompletionException e) {
            session.code = 1006; // not connected
        }
        String error = session.error; // the error message, if one came
        if (error != null && STOP.contains(field(error, "code"))) {
            String reason = field(error, "message");
            System.err.println("error " + field(error, "code") + ": " + reason);
            System.exit(1);
        }
        Double resumeS = error == null ? null : number(error, "resume_s");
        if (resumeS != null) {
            session.completeS = startS + resumeS; // the server's resume point
        }
        return session;
    }

    // Sends the audio from second startS on, at real-time pace, then end.
    static void sendAudio(WebSocket ws, double startS) {
        int chunk = BYTES_PER_S / 10; // 100 ms
        try {
            for (int i = (int) (startS * BYTES_PER_S) / 2 * 2; i < audio.length; i += chunk) {
                int length = Math.min(chunk, audio.length - i);
                ws.sendBinary(ByteBuffer.wrap(audio, i, length), true).join();
                Thread.sleep(100);
            }
            ws.sendText("{\"type\": \"end\"}", true).join();
        } catch (Exception e) {
            // the session ended early
        }
    }

    static class Session implements WebSocket.Listener {
        final double startS;
        final int baseId;
        double completeS;
        int lastId;
        boolean started;
        int code;
        String error;
        final CompletableFuture<Integer> closed = new CompletableFuture<>();
        // a long message comes in parts
        final StringBuilder received = new StringBuilder();

        Session(double startS, int lastId) {
            this.startS = startS;
            this.completeS = startS;
            this.baseId = lastId;
            this.lastId = lastId;
        }

        void print(WebSocket ws, String raw) {
            switch (field(raw, "type")) {
            case "session.started":
                started = true;
                new Thread(() -> sendAudio(ws, startS)).start();
                break;
            case "final":
                // this session's times and ids start again at 0: move them
                lastId = baseId + number(raw, "segment_id").intValue();
                completeS = startS + number(raw, "end");
                double at = startS + number(raw, "start");
                System.out.printf(Locale.ROOT, "[%7.2f] %s%n", at, field(raw, "text"));
                break;
            case "error":
                error = raw;
                break;
            default:
            }
        }

        @Override
        public CompletionStage<?> onText(WebSocket ws, CharSequence part, boolean last) {
            received.append(part);
            if (last) {
                print(ws, received.toString());
                received.setLength(0);
            }
            ws.request(1);
            return null;
        }

        @Override
        public CompletionStage<?> onClose(WebSocket ws, int status, String reason) {
            closed.complete(status);
            return null;
        }

        @Override
        public void onError(WebSocket ws, Throwable failure) {
            closed.complete(1006); // the connection dropped
        }
    }

    // Reads a text field of the JSON: Java has no JSON parser built in,
    // a real program would use a library.
    static String field(String json, String name) {
        String value = "\"" + name + "\":\\s*\"((?:[^\"\\\\]++|\\\\.)*+)\"";
        Matcher match = Pattern.compile(value).matcher(json);
        if (!match.find()) {
            return null;
        }
        Pattern escaped = Pattern.compile("\\\\(u....|.)");
        return escaped.matcher(match.group(1)).replaceAll((escape) -> {
            String code = escape.group(1);
            if (code.equals("n")) {
                return "\n";
            }
            if (code.length() > 1) {
                int number = Integer.parseInt(code.substring(1), 16);
                code = String.valueOf((char) number);
            }
            return Matcher.quoteReplacement(code);
        });
    }

    // Reads a number field of the JSON (null: not there).
    static Double number(String json, String name) {
        String value = "\"" + name + "\":\\s*(-?[0-9.eE+-]+)";
        Matcher match = Pattern.compile(value).matcher(json);
        return match.find() ? Double.valueOf(match.group(1)) : null;
    }
}
```

```csharp
// A live session carried over early ends: dotnet run --project resume -- speech.wav
// Needs .NET 8 or newer, no packages. In the audio's folder: dotnet new console -o resume,
// then put this in resume/Program.cs. The audio: a 16 kHz 16-bit mono WAV.
using System.Globalization;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;

var url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
var query = "model_id=vatis_ro_v9_realtime";
// errors a new session would get again: stop
var stop = new HashSet<string>
{
    "unauthorized", "invalid_parameter", "audio_chunk_too_large", "idle_timeout",
};
const int bytesPerS = 16000 * 2;
// times print as 12.50 in every language setting, not 12,50
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;

var wav = File.ReadAllBytes(args[0]);
var audio = wav[(wav.AsSpan().IndexOf("data"u8) + 8)..];

double startS = 0;
int lastId = 0, tries = 0;
while (tries < 15) // about a minute without a session: stop
{
    var result = await Session(startS, lastId);
    if (result.Code == WebSocketCloseStatus.NormalClosure)
    {
        return 0; // the whole recording is transcribed
    }
    (startS, lastId) = (result.CompleteS, result.LastId);
    tries = result.Started ? 1 : tries + 1;
    Console.WriteLine($"connecting again from {startS:F2} s");
    await Task.Delay(Math.Min(250 << (tries - 1), 5000));
}
Console.Error.WriteLine("no session for a minute: stopping");
return 1;

// One session, from second startS of the audio on: where the transcript is complete, the
// last segment id, whether the session started, and its close code (null: none).
async Task<Result> Session(double startS, int lastId)
{
    var baseId = lastId;
    var completeS = startS;
    var started = false;
    string? code = null, reason = null; // the error message, if one came
    double? resumeS = null;
    using var ws = new ClientWebSocket();
    ws.Options.SetRequestHeader("Authorization", $"Bearer {apiKey}");
    try
    {
        await ws.ConnectAsync(new Uri($"{url}?{query}"), CancellationToken.None);
    }
    catch (WebSocketException)
    {
        return new Result(completeS, lastId, false, null); // not connected
    }

    using var ended = new CancellationTokenSource();
    async Task SendAudio()
    {
        const int chunk = bytesPerS / 10; // 100 ms
        try
        {
            for (var i = (int)(startS * bytesPerS) / 2 * 2; i < audio.Length; i += chunk)
            {
                var size = Math.Min(chunk, audio.Length - i);
                var piece = new ArraySegment<byte>(audio, i, size);
                await ws.SendAsync(piece, WebSocketMessageType.Binary, true, ended.Token);
                await Task.Delay(100, ended.Token);
            }
            var end = new ArraySegment<byte>(Encoding.UTF8.GetBytes("""{"type": "end"}"""));
            await ws.SendAsync(end, WebSocketMessageType.Text, true, ended.Token);
        }
        catch (Exception)
        {
            // the session ended early
        }
    }

    var buffer = new byte[65536];
    var segment = new ArraySegment<byte>(buffer);
    using var received = new MemoryStream(); // a long message comes in parts
    Task? sender = null;
    try
    {
        while (true)
        {
            var part = await ws.ReceiveAsync(segment, CancellationToken.None);
            if (part.MessageType == WebSocketMessageType.Close)
            {
                break;
            }

            received.Write(buffer, 0, part.Count);
            if (!part.EndOfMessage)
            {
                continue;
            }
            var message = JsonDocument.Parse(received.ToArray()).RootElement;
            received.SetLength(0);

            switch (message.GetProperty("type").GetString())
            {
                case "session.started":
                    started = true;
                    sender = SendAudio();
                    break;
                case "final":
                    // this session's times and ids start again at 0: move them
                    lastId = baseId + message.GetProperty("segment_id").GetInt32();
                    completeS = startS + message.GetProperty("end").GetDouble();
                    var at = startS + message.GetProperty("start").GetDouble();
                    Console.WriteLine($"[{at,7:F2}] {message.GetProperty("text")}");
                    break;
                case "error":
                    code = message.GetProperty("code").GetString();
                    reason = message.GetProperty("message").GetString();
                    if (message.TryGetProperty("resume_s", out var resume))
                    {
                        resumeS = resume.GetDouble();
                    }
                    break;
            }
        }
    }
    catch (WebSocketException)
    {
        // the connection dropped
    }
    finally
    {
        ended.Cancel();
        if (sender != null)
        {
            await sender;
        }
    }

    if (code != null && stop.Contains(code))
    {
        Console.Error.WriteLine($"error {code}: {reason}");
        Environment.Exit(1);
    }
    if (resumeS != null)
    {
        completeS = startS + resumeS.Value; // the server's resume point
    }
    return new Result(completeS, lastId, started, ws.CloseStatus);
}

record Result(double CompleteS, int LastId, bool Started, WebSocketCloseStatus? Code);
```
