# Quickstart

Go from an API key to your first transcript in five minutes: a file, then live audio.

## Before you begin

Create an account on [platform.vatis.tech](https://platform.vatis.tech/sign-up): a new workspace starts with free credit, no card needed ([The free credit](https://platform.vatis.tech/docs/limits#the-free-credit)). Verify your email, then open **API keys** and create a key. It starts with `vatis_sk_` and is shown only once: copy it.

Set it in your shell: every example reads it from `VATIS_KEY`. `read -rs` keeps it out of your shell's history: paste the key, then press Enter (it is not shown).

```bash
read -rs VATIS_KEY && export VATIS_KEY
```

## 1. Check your key

Ask the API which models your workspace can use. Python needs 3.10 or later and `pip install httpx`; the others need no packages: JavaScript Node.js 22 or later, Go 1.23 or later, Java 11 or later, C# .NET 8 or later.

```bash
curl -sS -H "Authorization: Bearer $VATIS_KEY" https://api.eu.vatis.tech/v1/models
```

```javascript
// The models your workspace can use: node quickstart_models.mjs
const url = "https://api.eu.vatis.tech/v1/models";
const headers = { Authorization: `Bearer ${process.env.VATIS_KEY}` };

const response = await fetch(url, { headers });
console.log(await response.text());
```

```go
// The models your workspace can use: go run quickstart_models.go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

const url = "https://api.eu.vatis.tech/v1/models"

func main() {
	request, err := http.NewRequest("GET", url, nil)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()
	answer, err := io.ReadAll(response.Body)
	check(err)
	fmt.Println(string(answer))
}

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

```python
"""The models your workspace can use: python3 quickstart_models.py"""
import os

import httpx

url = "https://api.eu.vatis.tech/v1/models"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}

response = httpx.get(url, headers=headers)
print(response.text)
```

```java
// The models your workspace can use: java QuickstartModels.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class QuickstartModels {
    static final String url = "https://api.eu.vatis.tech/v1/models";

    public static void main(String[] args) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}
```

```csharp
// The models your workspace can use. In a new folder:
// dotnet new console -o models, then put this in models/Program.cs
// and run: dotnet run --project models
using System.Net.Http.Headers;

var url = "https://api.eu.vatis.tech/v1/models";
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");

using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);
using var response = await http.GetAsync(url);
Console.WriteLine(await response.Content.ReadAsStringAsync());
```

**Expected result:** the models, on one line (here on several). `vatis_ro_v9` transcribes files, `vatis_ro_v9_realtime` live audio. Without a `batch` model, batch transcription is not open on your workspace yet: go on with step 3. Something else: [If something goes wrong](https://platform.vatis.tech/docs/quickstart#if-something-goes-wrong).

```json
{"models": [
  {"id": "vatis_ro_v9", "name": "Romanian v9", "mode": "batch", "languages": ["ro"], "licensed": null},
  {"id": "vatis_ro_v9_realtime", "name": "Romanian v9 real-time", "mode": "realtime", "languages": ["ro"], "licensed": null}
]}
```

## 2. Transcribe a file

Send a recording in Romanian, in any common audio or video format (`speech.wav` here). `diarize=true` tells the speakers apart. The answer comes at once, with the transcript queued; then ask for it by its id every 2 seconds until it is done.

```bash
# 1. Send the file: the answer comes at once, with the transcript queued
curl -sS -H "Authorization: Bearer $VATIS_KEY" https://api.eu.vatis.tech/v1/speech-to-text \
  -F model_id=vatis_ro_v9 -F diarize=true -F file=@speech.wav

# 2. Ask every 2 seconds while it is queued or processing (-o keeps the last answer in a file)
ID=tr_69348b9588d248d1   # the "id" of the first answer
while sleep 2; do
  curl -sS -H "Authorization: Bearer $VATIS_KEY" -o transcript.json https://api.eu.vatis.tech/v1/transcripts/$ID
  grep -qE '"status": ?"(queued|processing)"' transcript.json || break
done
cat transcript.json
```

```javascript
// A file to text with speakers, once it is done: node quickstart_batch.mjs speech.wav
import { openAsBlob } from "node:fs";
import { basename } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";

const base = "https://api.eu.vatis.tech";
const headers = { Authorization: `Bearer ${process.env.VATIS_KEY}` };

// The answer's JSON, or the error on one line and exit
async function answer(response) {
  const body = await response.json();
  if (!response.ok) {
    console.error(`${response.status} ${body.error.code}: ${body.error.message}`);
    process.exit(1);
  }
  return body;
}

// 1. Send the file: the answer comes at once, with the transcript queued
const form = new FormData();
form.append("model_id", "vatis_ro_v9");
form.append("diarize", "true");
form.append("file", await openAsBlob(process.argv[2]), basename(process.argv[2]));
let transcript = await answer(await fetch(`${base}/v1/speech-to-text`, { method: "POST", headers, body: form }));
// kept for 7 days: use this id to read, export or delete it
console.log(`queued ${transcript.id}`);

// 2. Ask every 2 seconds until it is completed or failed
while (transcript.status === "queued" || transcript.status === "processing") {
  await sleep(2000);
  transcript = await answer(await fetch(`${base}/v1/transcripts/${transcript.id}`, { headers }));
}
if (transcript.status === "failed") {
  console.error(`failed: ${transcript.error.code}: ${transcript.error.message}`);
  process.exit(1);
}
for (const segment of transcript.segments) console.log(`${segment.speaker}: ${segment.text}`);
```

```go
// A file to text with speakers, once it is done: go run quickstart_batch.go speech.wav
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

const base = "https://api.eu.vatis.tech"

// Transcript holds what this code reads of the answers.
type Transcript struct {
	ID       string
	Status   string
	Segments []struct{ Speaker, Text string }
	Error    struct{ Code, Message string }
}

// answer sends the request with the key: the answer's JSON,
// or the error on one line and exit.
func answer(request *http.Request) Transcript {
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()
	var body Transcript
	check(json.NewDecoder(response.Body).Decode(&body))
	if response.StatusCode >= 400 {
		e := body.Error
		check(fmt.Errorf("%d %s: %s", response.StatusCode, e.Code, e.Message))
	}
	return body
}

func main() {
	// 1. Send the file: the answer comes at once, with the transcript queued
	var body bytes.Buffer
	form := multipart.NewWriter(&body)
	check(form.WriteField("model_id", "vatis_ro_v9"))
	check(form.WriteField("diarize", "true"))
	audio, err := os.Open(os.Args[1])
	check(err)
	defer audio.Close()
	part, err := form.CreateFormFile("file", filepath.Base(os.Args[1]))
	check(err)
	_, err = io.Copy(part, audio)
	check(err)
	check(form.Close())
	request, err := http.NewRequest("POST", base+"/v1/speech-to-text", &body)
	check(err)
	request.Header.Set("Content-Type", form.FormDataContentType())
	transcript := answer(request)
	// kept for 7 days: use this id to read, export or delete it
	fmt.Println("queued", transcript.ID)

	// 2. Ask every 2 seconds until it is completed or failed
	for transcript.Status == "queued" || transcript.Status == "processing" {
		time.Sleep(2 * time.Second)
		request, err = http.NewRequest("GET", base+"/v1/transcripts/"+transcript.ID, nil)
		check(err)
		transcript = answer(request)
	}
	if transcript.Status == "failed" {
		e := transcript.Error
		check(fmt.Errorf("failed: %s: %s", e.Code, e.Message))
	}
	for _, segment := range transcript.Segments {
		fmt.Printf("%s: %s\n", segment.Speaker, segment.Text)
	}
}

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

```python
"""A file to text with speakers, once it is done: python3 quickstart_batch.py speech.wav"""
import os
import sys
import time

import httpx

client = httpx.Client(base_url="https://api.eu.vatis.tech", timeout=600,
                      headers={"Authorization": f"Bearer {os.environ['VATIS_KEY']}"})

def answer(response):
    """The answer's JSON, or the error on one line and exit."""
    body = response.json()
    if response.is_error:
        sys.exit(f"{response.status_code} {body['error']['code']}: {body['error']['message']}")
    return body

# 1. Send the file: the answer comes at once, with the transcript queued
data = {"model_id": "vatis_ro_v9", "diarize": "true"}
with open(sys.argv[1], "rb") as audio:
    transcript = answer(client.post("/v1/speech-to-text", data=data, files={"file": audio}))
# kept for 7 days: use this id to read, export or delete it
print(f"queued {transcript['id']}")

# 2. Ask every 2 seconds until it is completed or failed
while transcript["status"] in ("queued", "processing"):
    time.sleep(2)
    transcript = answer(client.get(f"/v1/transcripts/{transcript['id']}"))
if transcript["status"] == "failed":
    sys.exit(f"failed: {transcript['error']['code']}: {transcript['error']['message']}")
for segment in transcript["segments"]:
    print(f"{segment['speaker']}: {segment['text']}")
```

```java
// A file to text with speakers, once it is done: java QuickstartBatch.java speech.wav
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.nio.charset.StandardCharsets.UTF_8;

public class QuickstartBatch {
    static final String base = "https://api.eu.vatis.tech";
    static final String boundary = "vatis" + System.nanoTime();
    static final HttpClient client = HttpClient.newHttpClient();

    // Sends the request with the key: the answer's JSON,
    // or the error on one line and exit
    static String answer(HttpRequest.Builder request) throws Exception {
        request.header("Authorization", "Bearer " + System.getenv("VATIS_KEY"));
        HttpResponse<String> response =
            client.send(request.build(), HttpResponse.BodyHandlers.ofString());
        String body = response.body();
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + " " + field(body, "code") + ": "
                + field(body, "message"));
            System.exit(1);
        }
        return body;
    }

    public static void main(String[] args) throws Exception {
        // 1. Send the file: the answer comes at once, with the transcript queued
        Path audio = Path.of(args[0]);
        ByteArrayOutputStream form = new ByteArrayOutputStream();
        addPart(form, "name=\"model_id\"", "vatis_ro_v9".getBytes(UTF_8));
        addPart(form, "name=\"diarize\"", "true".getBytes(UTF_8));
        addPart(form, "name=\"file\"; filename=\"" + audio.getFileName() + "\"",
            Files.readAllBytes(audio));
        form.write(("--" + boundary + "--\r\n").getBytes(UTF_8));
        URI start = URI.create(base + "/v1/speech-to-text");
        String transcript = answer(HttpRequest.newBuilder(start)
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .POST(HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())));
        String id = field(transcript, "id");
        // kept for 7 days: use this id to read, export or delete it
        System.out.println("queued " + id);

        // 2. Ask every 2 seconds until it is completed or failed
        String status = field(transcript, "status");
        while (status.equals("queued") || status.equals("processing")) {
            Thread.sleep(2000);
            URI poll = URI.create(base + "/v1/transcripts/" + id);
            transcript = answer(HttpRequest.newBuilder(poll));
            status = field(transcript, "status");
        }
        if (status.equals("failed")) {
            System.err.println("failed: " + field(transcript, "code") + ": "
                + field(transcript, "message"));
            System.exit(1);
        }
        for (String segment : segments(transcript)) {
            System.out.println(field(segment, "speaker") + ": " + field(segment, "text"));
        }
    }

    // Adds one part to the form: Java has no multipart body built in.
    static void addPart(ByteArrayOutputStream form, String disposition,
            byte[] value) throws Exception {
        String head = "--" + boundary + "\r\n"
            + "Content-Disposition: form-data; " + disposition + "\r\n\r\n";
        form.write(head.getBytes(UTF_8));
        form.write(value);
        form.write("\r\n".getBytes(UTF_8));
    }

    // 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);
        });
    }

    // The transcript's segments, each as its JSON text: a segment holds no
    // object or list, so a match that skips over strings finds its end.
    static List<String> segments(String json) {
        String object = "\\{(?:[^{}\"]++|\"(?:[^\"\\\\]++|\\\\.)*+\")*+\\}";
        Matcher match = Pattern.compile("\\s*,?\\s*(" + object + ")").matcher(json);
        List<String> found = new ArrayList<>();
        int key = json.indexOf("\"segments\":");
        int at = json.indexOf('[', key) + 1;
        while (key >= 0 && match.region(at, json.length()).lookingAt()) {
            found.add(match.group(1));
            at = match.end();
        }
        return found;
    }
}
```

```csharp
// A file to text with speakers, once it is done. In the audio's folder:
// dotnet new console -o batch, then put this in batch/Program.cs
// and run: dotnet run --project batch -- speech.wav
using System.Net.Http.Headers;
using System.Text.Json;

using var http = new HttpClient
{
    BaseAddress = new Uri("https://api.eu.vatis.tech"),
    Timeout = TimeSpan.FromMinutes(10),
};
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

// 1. Send the file: the answer comes at once, with the transcript queued
using var form = new MultipartFormDataContent();
form.Add(new StringContent("vatis_ro_v9"), "model_id");
form.Add(new StringContent("true"), "diarize");
using var audio = File.OpenRead(args[0]);
form.Add(new StreamContent(audio), "file", Path.GetFileName(args[0]));
var transcript = await Answer(await http.PostAsync("/v1/speech-to-text", form));
var id = transcript.GetProperty("id").GetString();
// kept for 7 days: use this id to read, export or delete it
Console.WriteLine($"queued {id}");

// 2. Ask every 2 seconds until it is completed or failed
while (transcript.GetProperty("status").GetString() is "queued" or "processing")
{
    await Task.Delay(2000);
    transcript = await Answer(await http.GetAsync($"/v1/transcripts/{id}"));
}
if (transcript.GetProperty("status").GetString() == "failed")
{
    var error = transcript.GetProperty("error");
    var code = error.GetProperty("code");
    Console.Error.WriteLine($"failed: {code}: {error.GetProperty("message")}");
    return 1;
}
foreach (var segment in transcript.GetProperty("segments").EnumerateArray())
{
    var speaker = segment.GetProperty("speaker");
    Console.WriteLine($"{speaker}: {segment.GetProperty("text")}");
}
return 0;

// The answer's JSON, or the error on one line and exit
static async Task<JsonElement> Answer(HttpResponseMessage response)
{
    var text = await response.Content.ReadAsStringAsync();
    var body = JsonDocument.Parse(text).RootElement;
    if (!response.IsSuccessStatusCode)
    {
        var error = body.GetProperty("error");
        var code = error.GetProperty("code");
        var message = error.GetProperty("message");
        Console.Error.WriteLine($"{(int)response.StatusCode} {code}: {message}");
        Environment.Exit(1);
    }
    return body;
}
```

**Expected result:** at once, `202` and the transcript `queued`, with its id; a few seconds later for a few minutes of audio, the transcript, `completed`. curl prints it as JSON on one line (here on several, trimmed); the programs print its id, then one line for each utterance.

```json
{
  "id": "tr_69348b9588d248d1",
  "status": "completed",
  "text": "Bună ziua, vă rog să luați loc. Mulțumesc.",
  "segments": [
    {"speaker": "speaker_0", "start": 0.12, "end": 2.31, "text": "Bună ziua, vă rog să luați loc."},
    {"speaker": "speaker_1", "start": 2.9, "end": 3.62, "text": "Mulțumesc."}
  ],
  ...
}
```

- `id`: the transcript is kept for 7 days after its job ends. Use the id to read, export or delete it ([Manage transcripts](https://platform.vatis.tech/docs/batch/manage-transcripts)). The uploaded audio is deleted 1 day after.
- `text`: the whole transcript, with punctuation, capitals and numbers as digits.
- `segments`: the transcript as utterances, what one speaker said in one go. Show these to people.

Every field: [The transcript object](https://platform.vatis.tech/docs/transcript-object). Instead of asking, your server can have the transcript posted to it ([Send now, collect later](https://platform.vatis.tech/docs/batch/send-now-collect-later)).

## 3. Transcribe live audio

Send audio over a WebSocket as it is recorded, and text comes back at once (curl cannot do this: skip it with curl). **Partial** text is the segment so far, replaced by the next. **Final** text is a finished segment: it never changes.

The program sends a WAV file at the pace of real time. The file must be 16 kHz, 16-bit, mono: the program does not check, and another format comes out as wrong text, so convert other recordings first (the command is in the program). Python also needs `pip install --upgrade websockets`, and Go a WebSocket package: in a new folder, `go mod init live && go get github.com/coder/websocket`. Java and C# need nothing more.

```javascript
// Needs Node.js 22 or newer, no packages.
// Set your API key, then run: export VATIS_KEY=your_api_key && node live.mjs
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}` };

// Request parameters
const params = {
  model_id: "vatis_ro_v9_realtime",
  diarize: "true",
};

// The audio: a 16 kHz 16-bit mono WAV. To convert a file:
// ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
const wav = readFileSync("speech.wav");
const audio = wav.subarray(wav.indexOf("data") + 8);
const chunkSize = 3200; // 100 ms of audio

// Open the session
const ws = new WebSocket(`${url}?${new URLSearchParams(params)}`, { headers });

// Send the audio at real-time pace
async function sendAudio() {
  for (let start = 0; start < audio.length; start += chunkSize) {
    ws.send(audio.subarray(start, start + chunkSize));
    await sleep(100);
  }
  ws.send(JSON.stringify({ type: "end" }));
  console.log("finished sending");
}

// Print the messages as they come
ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  if (message.type === "session.started") {
    console.log("connected");
    sendAudio();
  } else if (message.type === "partial") {
    console.log(`... ${message.text}`);
  } else if (message.type === "final") {
    console.log(`${message.speaker}: ${message.text}`);
  } else if (message.type === "session.ended") {
    console.log(`done: ${message.duration_s} s of audio`);
  } else if (message.type === "error") {
    console.log(`error ${message.code}: ${message.message}`);
  }
};

// A failed connection is an error; when the server closes, the program ends
ws.onerror = () => {
  console.error("connection failed");
  process.exit(1);
};
ws.onclose = (event) => {
  if (event.code !== 1000) { // 1000 is the normal end
    console.error(`connection failed: close code ${event.code}`);
    process.exit(1);
  }
  process.exit();
};
```

```go
// Needs Go 1.23 or newer and a WebSocket package. In a new folder:
// go mod init live && go get github.com/coder/websocket, save this as main.go
// Set your API key, then run: export VATIS_KEY=your_api_key && go run .

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 chunkSize = 3200 // 100 ms of audio

var headers = http.Header{
	"Authorization": {"Bearer " + os.Getenv("VATIS_KEY")},
}

// Request parameters
var params = url.Values{
	"model_id": {"vatis_ro_v9_realtime"},
	"diarize":  {"true"},
}

// Message holds what this code reads of the session's messages.
type Message struct {
	Type      string
	Text      string
	Speaker   string
	DurationS float64 `json:"duration_s"`
	Code      string
	Message   string
}

func main() {
	// The audio: a 16 kHz 16-bit mono WAV. To convert a file:
	// ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
	wav, err := os.ReadFile("speech.wav")
	check(err)
	audio := wav[bytes.Index(wav, []byte("data"))+8:]

	// Open the session
	ctx := context.Background()
	options := &websocket.DialOptions{HTTPHeader: headers}
	ws, _, err := websocket.Dial(ctx, wsURL+"?"+params.Encode(), options)
	check(err)

	// Print the messages until the server closes the connection
	for {
		_, raw, err := ws.Read(ctx)
		if websocket.CloseStatus(err) == websocket.StatusNormalClosure {
			return
		}
		check(err)

		var message Message
		check(json.Unmarshal(raw, &message))
		switch message.Type {
		case "session.started":
			fmt.Println("connected")
			go sendAudio(ctx, ws, audio)
		case "partial":
			fmt.Printf("... %s\n", message.Text)
		case "final":
			fmt.Printf("%s: %s\n", message.Speaker, message.Text)
		case "session.ended":
			fmt.Printf("done: %g s of audio\n", message.DurationS)
		case "error":
			fmt.Printf("error %s: %s\n", message.Code, message.Message)
		}
	}
}

// sendAudio sends the audio at real-time pace.
func sendAudio(ctx context.Context, ws *websocket.Conn, audio []byte) {
	for start := 0; start < len(audio); start += chunkSize {
		chunk := audio[start:min(start+chunkSize, len(audio))]
		check(ws.Write(ctx, websocket.MessageBinary, chunk))
		time.Sleep(100 * time.Millisecond)
	}
	check(ws.Write(ctx, websocket.MessageText, []byte(`{"type": "end"}`)))
	fmt.Println("finished sending")
}

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

```python
# Needs Python 3.10 or newer and websockets (pip install --upgrade websockets).
# Set your API key, then run: export VATIS_KEY=your_api_key && python3 live.py
import asyncio
import json
import os
import wave
from urllib.parse import urlencode

from websockets.asyncio.client import connect

url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}

# Request parameters
params = {
    "model_id": "vatis_ro_v9_realtime",
    "diarize": "true",
}

# The audio: a 16 kHz 16-bit mono WAV. To convert a file:
# ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
with wave.open("speech.wav") as wav:
    audio = wav.readframes(wav.getnframes())
chunk_size = 3200  # 100 ms of audio

async def send_audio(ws):
    for start in range(0, len(audio), chunk_size):
        await ws.send(audio[start:start + chunk_size])
        await asyncio.sleep(0.1)  # real-time pace
    await ws.send(json.dumps({"type": "end"}))
    print("finished sending")

async def main():
    address = f"{url}?{urlencode(params)}"
    async with connect(address, additional_headers=headers) as ws:
        # Print the messages until the server closes the connection
        async for raw in ws:
            message = json.loads(raw)
            if message["type"] == "session.started":
                print("connected")
                asyncio.create_task(send_audio(ws))
            elif message["type"] == "partial":
                print(f"... {message['text']}")
            elif message["type"] == "final":
                print(f"{message['speaker']}: {message['text']}")
            elif message["type"] == "session.ended":
                print(f"done: {message['duration_s']} s of audio")
            elif message["type"] == "error":
                print(f"error {message['code']}: {message['message']}")

asyncio.run(main())
```

```java
// Needs Java 11 or newer, nothing to install.
// Set your API key, then run: export VATIS_KEY=your_api_key && java Live.java
import java.net.URI;
import java.net.URLEncoder;
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.StringJoiner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Live {
    static final String url =
        "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
    static final int chunkSize = 3200; // 100 ms of audio
    static final CompletableFuture<Void> closed = new CompletableFuture<>();
    static byte[] audio;

    // Request parameters
    static final String[][] params = {
        {"model_id", "vatis_ro_v9_realtime"},
        {"diarize", "true"},
    };

    public static void main(String[] args) throws Exception {
        // The audio: a 16 kHz 16-bit mono WAV. To convert a file:
        // ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
        byte[] wav = Files.readAllBytes(Path.of("speech.wav"));
        String header = new String(wav, StandardCharsets.ISO_8859_1);
        audio = Arrays.copyOfRange(wav, header.indexOf("data") + 8, wav.length);

        // Open the session: Session prints the messages
        // until the server closes the connection
        StringJoiner query = new StringJoiner("&");
        for (String[] param : params) {
            String value = URLEncoder.encode(param[1], StandardCharsets.UTF_8);
            query.add(param[0] + "=" + value);
        }
        HttpClient.newHttpClient().newWebSocketBuilder()
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .buildAsync(URI.create(url + "?" + query), new Session())
            .join();
        closed.join();
    }

    // Sends the audio at real-time pace.
    static void sendAudio(WebSocket ws) {
        try {
            for (int start = 0; start < audio.length; start += chunkSize) {
                int length = Math.min(chunkSize, audio.length - start);
                ByteBuffer chunk = ByteBuffer.wrap(audio, start, length);
                ws.sendBinary(chunk, true).join();
                Thread.sleep(100);
            }
            ws.sendText("{\"type\": \"end\"}", true).join();
            System.out.println("finished sending");
        } catch (Exception e) {
            System.out.println(e); // the session ended early
        }
    }

    static class Session implements WebSocket.Listener {
        // a long message comes in parts
        final StringBuilder received = new StringBuilder();

        void print(WebSocket ws, String raw) {
            switch (field(raw, "type")) {
            case "session.started":
                System.out.println("connected");
                new Thread(() -> sendAudio(ws)).start();
                break;
            case "partial":
                System.out.println("... " + field(raw, "text"));
                break;
            case "final":
                String speaker = field(raw, "speaker");
                System.out.println(speaker + ": " + field(raw, "text"));
                break;
            case "session.ended":
                System.out.println("done");
                break;
            case "error":
                String code = field(raw, "code");
                String reason = field(raw, "message");
                System.out.println("error " + code + ": " + reason);
                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 code,
                String reason) {
            if (code == WebSocket.NORMAL_CLOSURE) {
                closed.complete(null);
            } else {
                String failed = "connection failed: close code " + code;
                closed.completeExceptionally(new RuntimeException(failed));
            }
            return null;
        }

        @Override
        public void onError(WebSocket ws, Throwable error) {
            closed.completeExceptionally(error);
        }
    }

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

```csharp
// Needs .NET 8 or newer, no packages. In the audio's folder:
// dotnet new console -o live, then put this in live/Program.cs
// Set your API key, then run:
// export VATIS_KEY=your_api_key && dotnet run --project live
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");

// Request parameters
var parameters = new Dictionary<string, string>
{
    ["model_id"] = "vatis_ro_v9_realtime",
    ["diarize"] = "true",
};

// The audio: a 16 kHz 16-bit mono WAV. To convert a file:
// ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
var wav = File.ReadAllBytes("speech.wav");
var audio = wav[(wav.AsSpan().IndexOf("data"u8) + 8)..];
const int chunkSize = 3200; // 100 ms of audio

// Open the session
var pairs = parameters.Select(
    (pair) => $"{pair.Key}={Uri.EscapeDataString(pair.Value)}");
var query = string.Join("&", pairs);
using var ws = new ClientWebSocket();
ws.Options.SetRequestHeader("Authorization", $"Bearer {apiKey}");
await ws.ConnectAsync(new Uri($"{url}?{query}"), CancellationToken.None);

// Print the messages until the server closes the connection
var buffer = new byte[65536];
var segment = new ArraySegment<byte>(buffer);
using var received = new MemoryStream(); // a long message comes in parts
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":
            Console.WriteLine("connected");
            _ = SendAudio();
            break;
        case "partial":
            Console.WriteLine($"... {message.GetProperty("text")}");
            break;
        case "final":
            var speaker = message.GetProperty("speaker");
            Console.WriteLine($"{speaker}: {message.GetProperty("text")}");
            break;
        case "session.ended":
            var seconds = message.GetProperty("duration_s");
            Console.WriteLine($"done: {seconds} s of audio");
            break;
        case "error":
            var code = message.GetProperty("code");
            var reason = message.GetProperty("message");
            Console.WriteLine($"error {code}: {reason}");
            break;
    }
}

// 1000 is the normal end, any other close code a failure
if (ws.CloseStatus != WebSocketCloseStatus.NormalClosure)
{
    var closed = (int?)ws.CloseStatus;
    Console.Error.WriteLine($"connection failed: close code {closed}");
    return 1;
}
return 0;

// Sends the audio at real-time pace
async Task SendAudio()
{
    for (var start = 0; start < audio.Length; start += chunkSize)
    {
        var size = Math.Min(chunkSize, audio.Length - start);
        var chunk = new ArraySegment<byte>(audio, start, size);
        await ws.SendAsync(
            chunk, WebSocketMessageType.Binary, true, CancellationToken.None);
        await Task.Delay(100);
    }
    var end = Encoding.UTF8.GetBytes("""{"type": "end"}""");
    await ws.SendAsync(
        new ArraySegment<byte>(end),
        WebSocketMessageType.Text,
        true,
        CancellationToken.None);
    Console.WriteLine("finished sending");
}
```

**Expected result:** the program runs as long as the recording lasts.

```
connected
... bună ziua vă rog
speaker_0: Bună ziua, vă rog să luați loc.
... mulțumesc
speaker_1: Mulțumesc.
finished sending
done: 3.8 s of audio
```

- A partial comes fast and raw: lowercase words without punctuation, numbers in words.
- A final comes when the speaker pauses, with punctuation, capitals and digits.
- The API keeps no transcript of a live session: keep the finals you receive.

Every option: [Real-time transcription](https://platform.vatis.tech/docs/realtime).

## If something goes wrong

| You see | What it means | What to do |
|---|---|---|
| `401` `unauthorized`, or `error unauthorized` | No key, or a wrong, revoked or expired one. | Set `VATIS_KEY` again, in this shell. Create a new key on the API keys page if it is lost. |
| `403`, or an `error` before `session.started` | The workspace is paused (its credit is used up), or its live sessions are all in use. | The message says which. Add credit, or end another session ([Limits and free credit](https://platform.vatis.tech/docs/limits)). |
| `400` `invalid_parameter` | A field is misspelled or has a wrong value: `param` names it. | Fix that field. |
| `curl: (6) Could not resolve host` | The address is mistyped, or the machine is offline. | Check the address: `https://api.eu.vatis.tech`. |

## Next steps

- [Batch transcription](https://platform.vatis.tech/docs/batch): long files without waiting, and every option.
- [Real-time transcription](https://platform.vatis.tech/docs/realtime): every option of a live session, and live text in a web page.
- [Errors](https://platform.vatis.tech/docs/errors): every code, and what to do about it.

> **Try it in the console first.** The console's [Real-time](https://platform.vatis.tech/realtime) page runs a live session from your microphone or a file, and shows the program for that session with its options.
