# Vocabularies

Give a live session or a file the names and terms it must get right, and get them written exactly as you listed them.

Names of people, companies, streets, medicines and products are the words a transcript gets wrong most often, and often the ones that matter most. A vocabulary is a list of them, written as they should appear: `Vatis Tech`, `Ștefan cel Mare`, `Paracetamol Sinus`, `Strada 13 Septembrie`. The service listens for them while it transcribes, and writes them as listed.

> **Live sessions and files.** A vocabulary works in Romanian live sessions and in Romanian files sent for batch transcription ([Files](https://platform.vatis.tech/docs/realtime/vocabularies#files)). It costs nothing extra: a session or a file with a vocabulary is billed by its audio seconds, as any other.

## Two ways to give the list

|  | How | Suits |
|---|---|---|
| A saved vocabulary | `vocabulary_id=voc_...` in the query of the session, or in the form of the file. An Admin key saves the list once. | A long list, up to 10,000 entries, that many sessions and files share. |
| The request's own list | A `vocabulary` message, sent during the session; for a file, the `vocabulary` form field. | A short list known only when the call starts or the file is sent, or one that changes during the call. |

You can use both in one session or file: its own entries add to the saved ones. Both follow the same rules ([Writing entries](https://platform.vatis.tech/docs/realtime/vocabularies#writing-entries)).

## A saved vocabulary

Save the list once, then name it in each session or file by its id. A saved vocabulary belongs to the workspace: an Admin key creates, changes and deletes it, and every key of the workspace can list it, read it and use it, a Member key too. The console's [Vocabularies](https://platform.vatis.tech/vocabularies) page does the same without code: the workspace's owners and admins make and edit the lists there.

### Save the list

`POST /v1/vocabularies`

Body: a JSON object with a `name` and its `entries`. Answers `201` and the vocabulary ([Create a vocabulary](https://platform.vatis.tech/docs/endpoints/create-a-vocabulary)).

```bash
curl -sS https://api.eu.vatis.tech/v1/vocabularies \
  -H "Authorization: Bearer $VATIS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "streets-bucharest",
    "entries": ["Calea Victoriei", "Strada 13 Septembrie"]
  }'
```

```javascript
// Needs Node.js 22 or newer, no packages.
// Set VATIS_KEY to your API key, then run: node sample.mjs

const url = "https://api.eu.vatis.tech/v1/vocabularies";
const response = await fetch(url, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.VATIS_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "streets-bucharest",
    entries: ["Calea Victoriei", "Strada 13 Septembrie"],
  }),
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
// Needs Go 1.23 or newer, standard library only.
// Set VATIS_KEY to your API key, then run: go run main.go
package main

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

func main() {
	url := "https://api.eu.vatis.tech/v1/vocabularies"
	body := strings.NewReader(`{
		"name": "streets-bucharest",
		"entries": ["Calea Victoriei", "Strada 13 Septembrie"]
	}`)

	request, err := http.NewRequest("POST", url, body)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	request.Header.Set("Content-Type", "application/json")

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	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
# Needs Python 3.10 or newer and httpx (pip install httpx).
# Set VATIS_KEY to your API key, then run: python3 sample.py
import os

import httpx

url = "https://api.eu.vatis.tech/v1/vocabularies"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}
data = {
    "name": "streets-bucharest",
    "entries": ["Calea Victoriei", "Strada 13 Septembrie"],
}

response = httpx.post(url, headers=headers, json=data, timeout=60)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
// Needs Java 11 or newer, nothing to install.
// Set VATIS_KEY to your API key, then run: java Sample.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Sample {
    public static void main(String[] args) throws Exception {
        String url = "https://api.eu.vatis.tech/v1/vocabularies";
        String body = "{"
            + "\"name\": \"streets-bucharest\", "
            + "\"entries\": [\"Calea Victoriei\", \"Strada 13 Septembrie\"]"
            + "}";

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

```csharp
// Needs .NET 8 or newer, no packages. In a new folder:
// dotnet new console -o sample, then put this in sample/Program.cs
// Set VATIS_KEY to your API key, then run: dotnet run --project sample
using System.Net.Http.Headers;
using System.Text;

var url = "https://api.eu.vatis.tech/v1/vocabularies";

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);
var json = """
    {
      "name": "streets-bucharest",
      "entries": ["Calea Victoriei", "Strada 13 Septembrie"]
    }
    """;
var body = new StringContent(json, Encoding.UTF8, "application/json");

using var response = await http.PostAsync(url, body);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine(answer);
return 0;
```

**Expected result:** `201` and the vocabulary. Keep its `id`: sessions name it.

```json
{"id": "voc_3f9c1a2b7d4e", "name": "streets-bucharest", "entry_count": 2,
 "created_at": "2026-11-11T09:14:03Z", "updated_at": "2026-11-11T09:14:03Z",
 "entries": ["Calea Victoriei", "Strada 13 Septembrie"]}
```

### Name it in the session

Add `vocabulary_id` to the request parameters of the session. The rest of the program is the one of [The whole program](https://platform.vatis.tech/docs/realtime#the-whole-program).

```javascript
// Request parameters: the model and the saved vocabulary
const params = {
  model_id: "vatis_ro_v9_realtime",
  vocabulary_id: "voc_3f9c1a2b7d4e",
};
```

```go
// Request parameters: the model and the saved vocabulary
var params = url.Values{
	"model_id":      {"vatis_ro_v9_realtime"},
	"vocabulary_id": {"voc_3f9c1a2b7d4e"},
}
```

```python
# Request parameters: the model and the saved vocabulary
params = {
    "model_id": "vatis_ro_v9_realtime",
    "vocabulary_id": "voc_3f9c1a2b7d4e",
}
```

```java
// Request parameters: the model and the saved vocabulary
static final String[][] params = {
    {"model_id", "vatis_ro_v9_realtime"},
    {"vocabulary_id", "voc_3f9c1a2b7d4e"},
};
```

```csharp
// Request parameters: the model and the saved vocabulary
var parameters = new Dictionary<string, string>
{
    ["model_id"] = "vatis_ro_v9_realtime",
    ["vocabulary_id"] = "voc_3f9c1a2b7d4e",
};
```

**Expected result:** `session.started` says what was applied in its `config`: the id, the strength, and how many entries the saved vocabulary had when the session started (trimmed here).

```json
{"type": "session.started", "model_id": "vatis_ro_v9_realtime", ...,
 "config": {..., "vocabulary_id": "voc_3f9c1a2b7d4e", "vocabulary_strength": 1.0,
            "vocabulary_entries": 2}}
```

The vocabulary applies from the first word. An id that names no vocabulary of your workspace (a deleted one too) refuses the session: `invalid_parameter`, `param` `vocabulary_id`. A file names it in a form field: [Files](https://platform.vatis.tech/docs/realtime/vocabularies#files).

### Change it later

Add entries, remove some, replace them all, or rename it ([Update a vocabulary](https://platform.vatis.tech/docs/endpoints/update-a-vocabulary)). With both, what is removed goes first.

```bash
VOCABULARY_ID=voc_3f9c1a2b7d4e

curl -sS -X PATCH https://api.eu.vatis.tech/v1/vocabularies/$VOCABULARY_ID \
  -H "Authorization: Bearer $VATIS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"add_entries": ["Bulevardul Iuliu Maniu"]}'
```

```javascript
// Needs Node.js 22 or newer, no packages.
// Set VATIS_KEY to your API key, then run: node sample.mjs

const vocabularyId = "voc_3f9c1a2b7d4e";

const url = `https://api.eu.vatis.tech/v1/vocabularies/${vocabularyId}`;
const response = await fetch(url, {
  method: "PATCH",
  headers: {
    Authorization: `Bearer ${process.env.VATIS_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ add_entries: ["Bulevardul Iuliu Maniu"] }),
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
// Needs Go 1.23 or newer, standard library only.
// Set VATIS_KEY to your API key, then run: go run main.go
package main

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

func main() {
	vocabularyID := "voc_3f9c1a2b7d4e"
	url := "https://api.eu.vatis.tech/v1/vocabularies/" + vocabularyID
	body := strings.NewReader(`{"add_entries": ["Bulevardul Iuliu Maniu"]}`)

	request, err := http.NewRequest("PATCH", url, body)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	request.Header.Set("Content-Type", "application/json")

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	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
# Needs Python 3.10 or newer and httpx (pip install httpx).
# Set VATIS_KEY to your API key, then run: python3 sample.py
import os

import httpx

vocabulary_id = "voc_3f9c1a2b7d4e"
url = f"https://api.eu.vatis.tech/v1/vocabularies/{vocabulary_id}"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}
data = {"add_entries": ["Bulevardul Iuliu Maniu"]}

response = httpx.patch(url, headers=headers, json=data, timeout=60)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
// Needs Java 11 or newer, nothing to install.
// Set VATIS_KEY to your API key, then run: java Sample.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Sample {
    public static void main(String[] args) throws Exception {
        String vocabularyId = "voc_3f9c1a2b7d4e";
        String url = "https://api.eu.vatis.tech/v1/vocabularies/" +
            vocabularyId;
        String body = "{\"add_entries\": [\"Bulevardul Iuliu Maniu\"]}";

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .header("Content-Type", "application/json")
            .method("PATCH", HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

```csharp
// Needs .NET 8 or newer, no packages. In a new folder:
// dotnet new console -o sample, then put this in sample/Program.cs
// Set VATIS_KEY to your API key, then run: dotnet run --project sample
using System.Net.Http.Headers;
using System.Text;

var vocabularyId = "voc_3f9c1a2b7d4e";
var url = $"https://api.eu.vatis.tech/v1/vocabularies/{vocabularyId}";

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);
var json = """{"add_entries": ["Bulevardul Iuliu Maniu"]}""";
var body = new StringContent(json, Encoding.UTF8, "application/json");

using var response = await http.PatchAsync(url, body);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine(answer);
return 0;
```

- **New sessions and files only:** a session reads its saved vocabulary once, when it starts, and a file when its job is accepted. Open sessions and accepted jobs keep the entries they started with, through a change or a delete.
- **A long list is prepared once** and shared by the sessions that use it. The first session after a change may get its first text a moment later.
- [List vocabularies](https://platform.vatis.tech/docs/endpoints/list-vocabularies), [Get a vocabulary](https://platform.vatis.tech/docs/endpoints/get-a-vocabulary) and [Delete a vocabulary](https://platform.vatis.tech/docs/endpoints/delete-a-vocabulary) do the rest.

## The session's own list

Send the entries in a message, up to 250 of them:

```json
{"type": "vocabulary", "entries": ["Vatis Tech", "Ispas"]}
```

Send it when `session.started` comes, before the audio, and it applies from the first word. The session needs no parameter for it.

```javascript
// in ws.onmessage
if (message.type === "session.started") {
  console.log("connected");
  // the session's own entries, before the audio
  const entries = ["Vatis Tech", "Ispas"];
  ws.send(JSON.stringify({ type: "vocabulary", entries }));
  sendAudio();
} else if (message.type === "vocabulary.applied") {
  const { entries, total } = message;
  console.log(`vocabulary: ${entries} entries of its own, ${total} in all`);
}
```

```go
// in Message, the counts of vocabulary.applied
Entries int
Total   int

// the session's own entries, as a vocabulary message
vocabulary := `{"type": "vocabulary", "entries": ["Vatis Tech", "Ispas"]}`

// in the switch over the messages
case "session.started":
	fmt.Println("connected")
	// the session's own entries, before the audio
	check(ws.Write(ctx, websocket.MessageText, []byte(vocabulary)))
	go sendAudio(ctx, ws, audio)
case "vocabulary.applied":
	fmt.Printf("vocabulary: %d entries of its own, %d in all\n",
		message.Entries, message.Total)
```

```python
# in the loop over the messages
if message["type"] == "session.started":
    print("connected")
    # the session's own entries, before the audio
    entries = ["Vatis Tech", "Ispas"]
    vocabulary = {"type": "vocabulary", "entries": entries}
    await ws.send(json.dumps(vocabulary))
    asyncio.create_task(send_audio(ws))
elif message["type"] == "vocabulary.applied":
    own, total = message["entries"], message["total"]
    print(f"vocabulary: {own} entries of its own, {total} in all")
```

```java
// the session's own entries, as a vocabulary message
static final String VOCABULARY =
    "{\"type\": \"vocabulary\", \"entries\": [\"Vatis Tech\", \"Ispas\"]}";

// in print's switch
case "session.started":
    System.out.println("connected");
    // the session's own entries, before the audio, in one
    // thread: a Java WebSocket takes one send at a time
    new Thread(() -> {
        ws.sendText(VOCABULARY, true).join();
        sendAudio(ws);
    }).start();
    break;
case "vocabulary.applied":
    String own = number(raw, "entries");
    String total = number(raw, "total");
    System.out.println("vocabulary: " + own
        + " entries of its own, " + total + " in all");
    break;

// Reads a number field of the JSON.
static String number(String json, String name) {
    String value = "\"" + name + "\":\\s*(\\d+)";
    Matcher match = Pattern.compile(value).matcher(json);
    return match.find() ? match.group(1) : null;
}
```

```csharp
// the session's own entries, as a vocabulary message
var vocabulary = Encoding.UTF8.GetBytes(
    """{"type": "vocabulary", "entries": ["Vatis Tech", "Ispas"]}""");

// in the switch over the messages
case "session.started":
    Console.WriteLine("connected");
    // the session's own entries, before the audio
    await ws.SendAsync(new ArraySegment<byte>(vocabulary),
        WebSocketMessageType.Text, true, CancellationToken.None);
    _ = SendAudio();
    break;
case "vocabulary.applied":
    var own = message.GetProperty("entries");
    var total = message.GetProperty("total");
    Console.WriteLine(
        $"vocabulary: {own} entries of its own, {total} in all");
    break;
```

**Expected result:** once the entries are in effect, the server answers with how many entries the session has of its own, and how many in all, with the saved vocabulary's:

```json
{"type": "vocabulary.applied", "entries": 2, "total": 2}
```

An entry in both lists counts once in `total`. A message with a bad entry ends the session: [Errors](https://platform.vatis.tech/docs/realtime/vocabularies#errors).

## Change the list during a session

A voice bot knows what the caller may say next. When it asks for a street, it sends street names; when it asks for a medicine, medicine names. Send a new `vocabulary` message at any time:

- It **replaces** the session's own entries of the message before. An empty list removes them. The saved vocabulary stays.
- It applies to the audio the service transcribes next, within about two thirds of a second of audio. Audio already transcribed is not transcribed again, so a word said just before the message may miss the new list.
- Each message gets its own `vocabulary.applied`, in the order you sent them. With `multichannel=true` it applies to both channels.

```javascript
// Sets the session's own entries at any time: they replace the earlier
// ones, and an empty list removes them. The saved vocabulary stays.
function setVocabulary(entries) {
  ws.send(JSON.stringify({ type: "vocabulary", entries }));
}

// the bot just asked for a street
setVocabulary(["Calea Victoriei", "Strada 13 Septembrie", "Piața Unirii"]);

// the street is known: back to no entries of its own
setVocabulary([]);
```

```go
// setVocabulary sets the session's own entries at any time: they replace
// the earlier ones, and no entries removes them. The saved vocabulary stays.
func setVocabulary(ctx context.Context, ws *websocket.Conn, entries ...string) {
	message, err := json.Marshal(map[string]any{
		"type":    "vocabulary",
		"entries": append([]string{}, entries...), // [], never null
	})
	check(err)
	check(ws.Write(ctx, websocket.MessageText, message))
}

// the bot just asked for a street
streets := []string{"Calea Victoriei", "Strada 13 Septembrie", "Piața Unirii"}
setVocabulary(ctx, ws, streets...)

// the street is known: back to no entries of its own
setVocabulary(ctx, ws)
```

```python
async def set_vocabulary(ws, entries):
    """Sets the session's own entries at any time: they replace the earlier
    ones, and an empty list removes them. The saved vocabulary stays."""
    await ws.send(json.dumps({"type": "vocabulary", "entries": entries}))

# the bot just asked for a street
streets = ["Calea Victoriei", "Strada 13 Septembrie", "Piața Unirii"]
await set_vocabulary(ws, streets)

# the street is known: back to no entries of its own
await set_vocabulary(ws, [])
```

```java
// Sets the session's own entries at any time: they replace the earlier
// ones, and no entries removes them. The saved vocabulary stays.
// A Java WebSocket takes one send at a time: this method and sendAudio
// take turns on the same lock (a static synchronized method locks Live).
static synchronized void setVocabulary(WebSocket ws, String... entries) {
    // a valid entry holds no quote or backslash: nothing to escape
    StringJoiner list = new StringJoiner(", ", "[", "]");
    for (String entry : entries) {
        list.add("\"" + entry + "\"");
    }
    String message = "{\"type\": \"vocabulary\", \"entries\": " + list + "}";
    ws.sendText(message, true).join();
}

// in sendAudio, every send (the chunks and the end) takes the same lock
synchronized (Live.class) {
    ws.sendBinary(chunk, true).join();
}

// the bot just asked for a street
setVocabulary(ws, "Calea Victoriei", "Strada 13 Septembrie", "Piața Unirii");

// the street is known: back to no entries of its own
setVocabulary(ws);
```

```csharp
// before the loop over the messages: a ClientWebSocket takes one send at
// a time, so SetVocabulary and SendAudio take turns with this
var sending = new SemaphoreSlim(1);

// Sets the session's own entries at any time: they replace the earlier
// ones, and no entries removes them. The saved vocabulary stays.
async Task SetVocabulary(params string[] entries)
{
    var json = JsonSerializer.Serialize(new { type = "vocabulary", entries });
    await sending.WaitAsync();
    try
    {
        await ws.SendAsync(
            new ArraySegment<byte>(Encoding.UTF8.GetBytes(json)),
            WebSocketMessageType.Text,
            true,
            CancellationToken.None);
    }
    finally
    {
        sending.Release();
    }
}

// in SendAudio, every send (the chunks and the end) the same way
await sending.WaitAsync();
try
{
    await ws.SendAsync(
        chunk, WebSocketMessageType.Binary, true, CancellationToken.None);
}
finally
{
    sending.Release();
}

// the bot just asked for a street
await SetVocabulary("Calea Victoriei", "Strada 13 Septembrie", "Piața Unirii");

// the street is known: back to no entries of its own
await SetVocabulary();
```

**Expected result:** one answer for each message, in order. With a saved vocabulary, `total` includes its entries.

```json
{"type": "vocabulary.applied", "entries": 3, "total": 3}
{"type": "vocabulary.applied", "entries": 0, "total": 0}
```

## Files

`POST /v1/speech-to-text`

A file sent for batch transcription takes its vocabulary in three form fields, next to `model_id` and `file` ([Create a transcript](https://platform.vatis.tech/docs/endpoints/create-a-transcript)).

| Field | Values | Default | What it does |
|---|---|---|---|
| `vocabulary_id` | a vocabulary id, `voc_...` |  | A saved vocabulary of your workspace. |
| `vocabulary` | a JSON list of up to 250 entries, as a string |  | The file's own entries, added to the saved ones. |
| `vocabulary_strength` | 0 to 2 | `1` | How hard the service leans towards the entries ([Strength](https://platform.vatis.tech/docs/realtime/vocabularies#strength)). |

Send any of them, or none: a file without them is transcribed as always. `vocabulary` goes as text, as `metadata` does: `["Vatis Tech", "Ispas"]`. Romanian models only (`vatis_ro_v9`).

```bash
curl -sS https://api.eu.vatis.tech/v1/speech-to-text \
  -H "Authorization: Bearer $VATIS_KEY" \
  -F model_id=vatis_ro_v9 \
  -F vocabulary_id=voc_3f9c1a2b7d4e \
  -F 'vocabulary=["Vatis Tech", "Ispas"]' \
  -F vocabulary_strength=1.5 \
  -F file=@speech.wav
```

```javascript
// Needs Node.js 22 or newer, no packages.
// Set VATIS_KEY to your API key, then run: node sample.mjs
import { openAsBlob } from "node:fs";

const form = new FormData();
form.append("model_id", "vatis_ro_v9");
form.append("vocabulary_id", "voc_3f9c1a2b7d4e");
form.append("vocabulary", "[\"Vatis Tech\", \"Ispas\"]");
form.append("vocabulary_strength", "1.5");
form.append("file", await openAsBlob("speech.wav"), "speech.wav");

const url = "https://api.eu.vatis.tech/v1/speech-to-text";
const response = await fetch(url, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.VATIS_KEY}` },
  body: form,
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
// Needs Go 1.23 or newer, standard library only.
// Set VATIS_KEY to your API key, then run: go run main.go
package main

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	url := "https://api.eu.vatis.tech/v1/speech-to-text"

	var body bytes.Buffer
	form := multipart.NewWriter(&body)
	check(form.WriteField("model_id", "vatis_ro_v9"))
	check(form.WriteField("vocabulary_id", "voc_3f9c1a2b7d4e"))
	check(form.WriteField("vocabulary", "[\"Vatis Tech\", \"Ispas\"]"))
	check(form.WriteField("vocabulary_strength", "1.5"))
	audio, err := os.Open("speech.wav")
	check(err)
	defer audio.Close()
	part, err := form.CreateFormFile("file", "speech.wav")
	check(err)
	_, err = io.Copy(part, audio)
	check(err)
	check(form.Close())

	request, err := http.NewRequest("POST", url, &body)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	request.Header.Set("Content-Type", form.FormDataContentType())

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	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
# Needs Python 3.10 or newer and httpx (pip install httpx).
# Set VATIS_KEY to your API key, then run: python3 sample.py
import os

import httpx

url = "https://api.eu.vatis.tech/v1/speech-to-text"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}
data = {
    "model_id": "vatis_ro_v9",
    "vocabulary_id": "voc_3f9c1a2b7d4e",
    "vocabulary": "[\"Vatis Tech\", \"Ispas\"]",
    "vocabulary_strength": "1.5",
}

with open("speech.wav", "rb") as audio:
    files = {"file": audio}
    response = httpx.post(url, headers=headers, data=data, files=files,
                          timeout=600)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
// Needs Java 11 or newer, nothing to install.
// Set VATIS_KEY to your API key, then run: java Sample.java
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 static java.nio.charset.StandardCharsets.UTF_8;

public class Sample {
    static final String boundary = "vatis" + System.nanoTime();

    public static void main(String[] args) throws Exception {
        String url = "https://api.eu.vatis.tech/v1/speech-to-text";

        ByteArrayOutputStream form = new ByteArrayOutputStream();
        addPart(form, "name=\"model_id\"", "vatis_ro_v9".getBytes(UTF_8));
        addPart(form, "name=\"vocabulary_id\"",
            "voc_3f9c1a2b7d4e".getBytes(UTF_8));
        addPart(form, "name=\"vocabulary\"",
            "[\"Vatis Tech\", \"Ispas\"]".getBytes(UTF_8));
        addPart(form, "name=\"vocabulary_strength\"", "1.5".getBytes(UTF_8));
        addPart(form, "name=\"file\"; filename=\"speech.wav\"",
            Files.readAllBytes(Path.of("speech.wav")));
        String end = "--" + boundary + "--\r\n";
        form.write(end.getBytes(UTF_8));

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .POST(HttpRequest.BodyPublishers.ofByteArray(form.toByteArray()))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }

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

```csharp
// Needs .NET 8 or newer, no packages. In a new folder:
// dotnet new console -o sample, then put this in sample/Program.cs
// Set VATIS_KEY to your API key, then run: dotnet run --project sample
using System.Net.Http.Headers;

var url = "https://api.eu.vatis.tech/v1/speech-to-text";

using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

using var form = new MultipartFormDataContent();
form.Add(new StringContent("vatis_ro_v9"), "model_id");
form.Add(new StringContent("voc_3f9c1a2b7d4e"), "vocabulary_id");
form.Add(new StringContent("[\"Vatis Tech\", \"Ispas\"]"), "vocabulary");
form.Add(new StringContent("1.5"), "vocabulary_strength");
using var audio = File.OpenRead("speech.wav");
form.Add(new StreamContent(audio), "file", "speech.wav");

using var response = await http.PostAsync(url, form);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine(answer);
return 0;
```

**Expected result:** the transcript, with the entries written as listed wherever they were recognised, in its `words` and `text`, and a `vocabulary` key that says what was applied (trimmed here):

```json
{"id": "tr_3b41a7db9aba52c0", "status": "completed", ...,
 "vocabulary": {"id": "voc_3f9c1a2b7d4e", "strength": 1.5, "entries": 4},
 "text": "...", "words": [...]}
```

- **`vocabulary`** is there only when the request had a vocabulary: `id`, the saved vocabulary's, or `null` for the file's own entries alone; `strength`; `entries`, how many are in effect, the saved and the file's own together (one in both counts once). Never the entries themselves.
- **The saved vocabulary is read when the job is accepted.** A change or a delete after that does not reach the job.
- **Nothing of the list is kept** after the job ends: the transcript keeps only the counts.
- **Another model** takes no vocabulary: the field is refused ([Errors](https://platform.vatis.tech/docs/realtime/vocabularies#errors)).

## Strength

`vocabulary_strength`, in the query of the session or in the form of the file, sets how hard the service leans towards the entries, of both lists. It is a number from 0 to 2, set for the whole session or file.

| Strength | What it does |
|---|---|
| `0` | Does not lean at all: an entry is written as listed only when it was heard anyway. |
| `1` (default) | The tuned middle: finds many more of the listed words, and barely changes anything else. |
| `2` | Finds the most listed words, and also writes more of them where they were not said. |

- **Example address:** `wss://api.eu.vatis.tech/v1/speech-to-text/realtime?model_id=vatis_ro_v9_realtime&vocabulary_id=voc_3f9c1a2b7d4e&vocabulary_strength=1.5`
- Sent with `vocabulary_strength` only, a session has no saved vocabulary, and the strength applies to the lists its messages send.
- **In a file's form:** `-F vocabulary_strength=1.5`.

## Writing entries

An entry is a word or a phrase, written as it should appear in the transcript. The same rules hold for both lists, in a session and in a file.

- **1 to 100 characters:** letters (Romanian diacritics and the other letters of the Latin alphabet), digits `0` to `9`, spaces, and `-` `'` `.` inside or after a word: `Cluj-Napoca`, `O'Neill`, `Dr. Popescu`.
- **Every word starts with a letter or a digit.** Marks alone (`...`, `-`) are refused.
- **Nothing else:** no commas, quotes, tabs, other alphabets, or the curly apostrophes and long dashes that word processors put in. Type the plain `'` and `-`.
- **Written as it should appear:** capitals, diacritics and digits included. The service listens for the entry as it is said in Romanian: `Strada 13 Septembrie` as "strada treisprezece septembrie", and a letter Romanian does not use as the nearest one it does (`Müller` as "muller"). It writes the entry as you listed it.
- **Upper and lower case are the same entry:** of `vatis tech` and `Vatis Tech` one stays, at the place of the first, with the spelling given last.
- **Spaces:** the ones at the ends are trimmed, and a run of spaces between two words counts as one.

A list breaking a rule is refused whole, and the error names the place of the entry (`entries[3]`, a file's `vocabulary[3]`), never the entry itself. A valid entry never needs escaping in JSON: it has no quote or backslash.

## What you get back

- **`final`** messages carry the entries as listed, wherever they were recognised, with `punctuation`, `numbers` and `entities` applied around them as without a vocabulary. An entry that is also a common word (`Mare`, a surname) is written with its capital in every sentence.
- **`partial`** messages lean towards the entries too. Their text is the raw words being spoken, lowercase, as always.
- **`session.started`** shows in `config` what was applied, never the entries: `vocabulary_id` when you sent one, and `vocabulary_strength` and `vocabulary_entries` when the query has `vocabulary_id` or `vocabulary_strength`. `vocabulary_entries` is how many entries the saved vocabulary had when the session started (0 without one). The three keys are absent otherwise.
- **`vocabulary.applied`** answers each `vocabulary` message once its entries are in effect: `entries`, the session's own; `total`, with the saved vocabulary's.
- **A file's transcript** carries the entries as listed in its `words`, `text` and `segments`, with `punctuation` and `numbers` applied around them, and says what was applied in `vocabulary` ([Files](https://platform.vatis.tech/docs/realtime/vocabularies#files)).

## What to expect

We measured it in live sessions on public Romanian test audio, with a list of 425 names and terms said in it. Your results depend on your audio and your list, so try it on your own calls before you rely on it.

| Strength | Listed terms recognised, live sessions |
|---|---|
| no vocabulary | 57 % |
| `1` (default) | 69 % |
| `2` | 74 % |

- **Written as listed:** of the listed terms recognised, 99 % were written exactly as listed, against 89 % without a vocabulary.
- **A list that does not apply barely changes anything at strength 1.** With 500 entries never said in the audio, the word error rate went from 7.19 % to 7.20 %. At strength 2 it went to 7.32 %, with some listed words written where they were not said.
- **Phone calls gain about as much:** on the same audio passed through a telephone line (8 kHz, as `encoding=alaw` sessions get it), listed terms recognised went from 51 % to 63 % at strength 1 and to 69 % at 2. But entries never said were written two to three times as often as on wideband audio.
- **A long saved list** is prepared once and shared by its sessions. The first session after a change may get its first text a moment later.
- **Files gain a little more:** on the same test audio sent as files, listed terms recognised went from 55 % to 71 % at strength 1 and to 75 % at 2 (the same recordings over a telephone line: 52 %, 65 % and 70 %). With 500 entries never said, the word error rate went from 6.64 % to 6.65 % at strength 1. The figures in the table are for live sessions.

## Getting the best results

- **List the distinctive words the service gets wrong:** people, companies, streets, products, medicines, written as they should appear.
- **Do not list everyday words.** They are recognised already, and a listed word is written as listed everywhere.
- **Prefer distinctive names.** An entry that starts with a common word can pull the word after it: with `Comisia de la Veneția` listed, "comisia pentru buget" may be written "comisia de buget".
- **A name said far from its spelling may not be found.** The service listens for an entry as it would be read in Romanian.
- **On phone calls and in voice bots, list only what the caller may really say at that point.** The session's own list fits this: send the street names when the bot asks for the street ([Change the list during a session](https://platform.vatis.tech/docs/realtime/vocabularies#change-the-list-during-a-session)). On 8 kHz audio keep the strength at 1 or lower, and raise it only after checking on your own calls.
- **Start at strength 1.** Raise it towards 2 only when listed words are still missed, and check that they do not appear where they were not said.
- **Save the long lists** that many sessions and files share, and send the short ones that depend on the call or the file with it.

## Limits

| What | Limit |
|---|---|
| Entries in a session's own list | 250 a message |
| Entries in a file's own list | 250, in `vocabulary` |
| Entries in a saved vocabulary | 10,000 |
| Characters in an entry | 100 |
| Saved vocabularies | 100 a workspace |
| A saved vocabulary's name | 1 to 64 letters, digits, dots, dashes or underscores; no two of a workspace alike |
| The JSON body of Create or Update | 8 MB |
| `vocabulary_strength` | 0 to 2 |
| Price | nothing extra, for sessions and files alike |

Every limit of the API: [Limits and free credit](https://platform.vatis.tech/docs/limits).

## Errors

In a session, a refusal is an `error` message, then the server closes the connection ([Errors in a session](https://platform.vatis.tech/docs/realtime/errors-in-a-session)). Nothing of a refused message is applied.

```json
{"type": "error", "code": "invalid_parameter",
 "message": "vocabulary_id: no vocabulary with this id", "param": "vocabulary_id"}
```

| code (close code) | When | What to do |
|---|---|---|
| `invalid_parameter (1008)` | `param` `vocabulary_id`: no vocabulary of your workspace has that id, or it was deleted. | Check the id: [List vocabularies](https://platform.vatis.tech/docs/endpoints/list-vocabularies). |
| `invalid_parameter (1008)` | `param` `vocabulary_strength`: not a number from 0 to 2 ("vocabulary_strength: 0 to 2, got 2.5"). | Send a number from 0 to 2. |
| `invalid_parameter (1008)` | `param` `entries[3]`: that entry breaks the rules, and the message says which. `param` `entries`: not a list, or more than 250 entries. | Fix the entry at that place ([Writing entries](https://platform.vatis.tech/docs/realtime/vocabularies#writing-entries)). |
| `invalid_parameter (1008)` | `param` the field's name: a `vocabulary` message with another field than `type` and `entries`. | Send those two only. |
| `invalid_parameter (1008)` | The speech service cannot take a vocabulary yet: "vocabularies are not available on this server yet: its speech service is an older release" (`param` `vocabulary_id`, `vocabulary_strength` or `type`). A session is never transcribed without the vocabulary it asked for. | Try again later, or connect without the vocabulary. |
| `internal_error (1011)` | The saved vocabulary cannot be read for a moment, before `session.started`. | Connect again in a few seconds. |

A file's request is refused before its job starts, as any other request ([Request errors](https://platform.vatis.tech/docs/batch/request-errors)): `400` `invalid_parameter`, and `param` names the field. Nothing is transcribed.

```json
{"error": {"code": "invalid_parameter",
 "message": "'vocabulary[1]' must be 1 to 100 characters: ...",
 "param": "vocabulary[1]", "request_id": "req_bf2fed760ba5437ba0933a57"}}
```

| `param` | When | What to do |
|---|---|---|
| `vocabulary[3]` | That entry of the file's own list breaks the rules. | Fix the entry at that place ([Writing entries](https://platform.vatis.tech/docs/realtime/vocabularies#writing-entries)). |
| `vocabulary` | Not a JSON list of strings, or more than 250 entries. | Send a JSON list of at most 250. |
| `vocabulary_id` | No vocabulary of your workspace has that id, or it was deleted. | Check the id: [List vocabularies](https://platform.vatis.tech/docs/endpoints/list-vocabularies). |
| `vocabulary_strength` | Not a number from 0 to 2. | Send a number from 0 to 2. |
| the field sent | A model other than `vatis_ro_v9`, or a speech service that cannot take a vocabulary yet: "vocabularies are not available on this server yet: its speech service is an older release". A file is never transcribed without the vocabulary it asked for. | Use the Romanian model; on an older server, try again later or send the file without the vocabulary. |

The endpoints of saved vocabularies answer as the rest of the API ([Errors](https://platform.vatis.tech/docs/errors)):

| Status and code | When |
|---|---|
| `400` `invalid_parameter` | A field unknown or not valid, an entry breaking the rules (`param` `entries[3]`, `add_entries[3]`), more than 10,000 entries, or a query parameter. `param` names it. |
| `400` `missing_parameter` | No `name` when creating one. |
| `403` `admin_only` | A Member key creating, changing or deleting one. |
| `404` `not_found` | No vocabulary of your workspace has that id. |
| `409` `name_taken` | Another vocabulary of your workspace has that name. |
| `409` `vocabulary_limit` | A 101st vocabulary: delete one first. |
| `413` `request_too_large` | A JSON body over 8 MB. |

## Next steps

- [Create a vocabulary](https://platform.vatis.tech/docs/endpoints/create-a-vocabulary): every field and answer of the saved vocabularies' endpoints.
- [Messages](https://platform.vatis.tech/docs/realtime/messages): every message of a session, `vocabulary` and `vocabulary.applied` among them.
- [Query parameters](https://platform.vatis.tech/docs/realtime/query-parameters): every option of a session.
- [Create a transcript](https://platform.vatis.tech/docs/endpoints/create-a-transcript): every field of a file's request, the vocabulary's among them.
