Source: https://speech.unidatum.com/docs/  
All pages as markdown: https://speech.unidatum.com/llms.txt

# Use it, integrate it

The wire format is Deepgram's, so any Deepgram client needs only a different base URL and key. Everything below is pasted from tested examples in the repository (`docs/examples/`); `speech.example` and `YOUR_KEY` are placeholders for your own service address and key.

**There is no hosted API: you host it.** Unidatum Speech is software you run on your own servers or cloud, and each client has a key that you set. Download the [release packages](https://speech.unidatum.com/download/), which are free to use for any purpose under the [Unidatum Speech Free Use Licence](https://speech.unidatum.com/licence/). For maintenance, support or consulting, [contact Unidatum](https://www.unidatum.ie/en/contact).

- Connection
- Quick start with curl
- Live clients
- Text to speech
- API reference
- Errors and fallback
- PowerConduit drop-in
- For coding agents
- Install and run
- Checklist

## Connection details

Base URL

`UNIDATUM_SPEECH_URL`, for example `https://speech.example` (use `wss://` for WebSockets; the service itself speaks plain HTTP on a private address, so TLS comes from whatever sits in front)

Key

`UNIDATUM_SPEECH_KEY`, or the first line of a mode-600 file such as `~/.config/yourapp/unidatum-speech-key`

Auth header

`Authorization: Token <key>` (also `Bearer`). Browsers cannot set headers: use the WebSocket subprotocols `["token", "<key>"]`

Live audio

raw `linear16`, 16 kHz mono is native. 8 to 96 kHz and 1 or 2 channels are accepted when declared. About 100 ms per binary frame, at real-time pace, no WAV header

Files

`POST /v1/listen` with the bytes of a wav, flac, ogg or mp3 file. `{"url": ...}` is refused: the service never fetches URLs

TTS output

16-bit mono PCM, 24 kHz by default (8 to 48 kHz), raw or in a WAV container

Rules: never put the key in source, a flag, a log, a URL or a commit; never print it. The service listens on a private address only; if you cannot reach it, do not open it to the internet. Do not load-test a production instance; start a throwaway instance on another port.

```bash
# a quick check from a shell (health needs no key; /v1/projects checks the key)
export UNIDATUM_SPEECH_URL=https://speech.example
export UNIDATUM_SPEECH_KEY=YOUR_KEY          # from your secret store, never typed into a repo
curl -fsS "$UNIDATUM_SPEECH_URL/health"
# {"ok":true,"sessions":0,"capacity":8,"final_queue":0,"tts_workers":1,"tts_queue":0,"retention_hours":24,"final_model":"parakeet-v3"}
curl -fsS -H "Authorization: Token $UNIDATUM_SPEECH_KEY" "$UNIDATUM_SPEECH_URL/v1/projects"
# 200 with a project list; 401 means the key is wrong

# the repository's smoke test: health, key, the sample WAV through POST /v1/listen, SMOKE OK
docs/examples/smoke.sh
```

## Quick start with curl

### Recorded audio to text

```bash
curl -fsS -X POST "$UNIDATUM_SPEECH_URL/v1/listen?language=en&smart_format=true" \
  -H "Authorization: Token $UNIDATUM_SPEECH_KEY" \
  -H 'Content-Type: audio/wav' --data-binary @clip.wav
# Deepgram's pre-recorded shape; the text is at
#   .results.channels[0].alternatives[0].transcript
# with .words[] (word, start, end, confidence, punctuated_word)
```

### Text to speech

```bash
curl -fsS -X POST "$UNIDATUM_SPEECH_URL/v1/speak?model=aura-2-thalia-en&encoding=linear16&sample_rate=24000&container=wav" \
  -H "Authorization: Token $UNIDATUM_SPEECH_KEY" -H 'Content-Type: application/json' \
  -d '{"text":"Hello from Unidatum Speech."}' -o hello.wav
# container=none gives raw PCM; GET /v1/voices lists voices and the aura-2-* aliases
```

## Live speech to text: tested clients

The query the examples and PowerConduit use: `language=en&encoding=linear16&sample_rate=16000&channels=1&interim_results=true&vad_events=true&endpointing=350&smart_format=true`. Each client sends a 16 kHz mono WAV's samples in 100 ms frames at real-time pace, joins finals until `speech_final` or `UtteranceEnd`, and ends with `CloseStream`.

```python
#!/usr/bin/env python3
"""Live speech to text over WebSocket /v1/listen. Usage: listen.py clip.wav   (16 kHz, mono, 16-bit WAV)
Needs: pip install websockets. Env: UNIDATUM_SPEECH_URL (https://speech.example), UNIDATUM_SPEECH_KEY."""
import asyncio, json, os, sys, wave
import websockets

BASE = os.environ["UNIDATUM_SPEECH_URL"].rstrip("/").replace("http", "ws", 1)   # http->ws, https->wss
KEY = os.environ["UNIDATUM_SPEECH_KEY"]                                          # never hardcode
QUERY = "language=en&encoding=linear16&sample_rate=16000&channels=1&interim_results=true&vad_events=true&endpointing=350&smart_format=true"

async def main(path):
    w = wave.open(path); assert (w.getframerate(), w.getnchannels(), w.getsampwidth()) == (16000, 1, 2), "need 16 kHz mono 16-bit"
    pcm = w.readframes(w.getnframes())
    async with websockets.connect(f"{BASE}/v1/listen?{QUERY}", additional_headers={"Authorization": f"Token {KEY}"}) as ws:
        async def send():
            for i in range(0, len(pcm), 3200):                      # 100 ms per frame, sent in real time
                await ws.send(pcm[i:i + 3200]); await asyncio.sleep(0.1)
            await asyncio.sleep(1.0)                                # trailing silence so the last utterance endpoints
            await ws.send(json.dumps({"type": "CloseStream"}))      # pending finals, then Metadata
        sender = asyncio.create_task(send())
        turn = []
        async for raw in ws:
            m = json.loads(raw)
            if m["type"] == "Results":
                alt = m["channel"]["alternatives"][0]
                if not m["is_final"]:
                    print("partial:", alt["transcript"])
                elif alt["transcript"].strip():
                    turn.append(alt["transcript"])                  # finals of one turn are joined
                    if m["speech_final"]:
                        print("TURN:", " ".join(turn)); turn = []
            elif m["type"] == "UtteranceEnd" and turn:
                print("TURN:", " ".join(turn)); turn = []
            elif m["type"] == "SpeechStarted":
                print("[speech started]")
            elif m["type"] == "Error":
                sys.exit(f"service error: {m}")
            elif m["type"] == "Metadata":
                break
        if turn: print("TURN:", " ".join(turn))
        await sender

asyncio.run(main(sys.argv[1]))
```

The official Deepgram Python SDK also works, pointed at the service with the key as its API key (`service/tests/sdk_stream.py` in the repository).

```js
// Live speech to text, Node 22+ (global WebSocket) or a browser. Usage: node listen.mjs clip.wav  (16 kHz mono 16-bit WAV)
// Env: UNIDATUM_SPEECH_URL (https://speech.example), UNIDATUM_SPEECH_KEY. Browsers cannot set headers, so the key goes in the subprotocol.
import { readFileSync } from "node:fs";
const base = process.env.UNIDATUM_SPEECH_URL.replace(/\/$/, "").replace(/^http/, "ws");
const key = process.env.UNIDATUM_SPEECH_KEY;
const q = "language=en&encoding=linear16&sample_rate=16000&channels=1&interim_results=true&vad_events=true&endpointing=350&smart_format=true";
const wav = readFileSync(process.argv[2]);
const pcm = wav.subarray(44);                                   // a plain PCM WAV has a 44-byte header
const ws = new WebSocket(`${base}/v1/listen?${q}`, ["token", key]);
ws.binaryType = "arraybuffer";
let turn = [];
ws.onopen = async () => {
  for (let i = 0; i < pcm.length; i += 3200) { ws.send(pcm.subarray(i, i + 3200)); await new Promise(r => setTimeout(r, 100)); }
  await new Promise(r => setTimeout(r, 1000));
  ws.send(JSON.stringify({ type: "CloseStream" }));
};
ws.onmessage = (ev) => {
  const m = JSON.parse(ev.data);
  if (m.type === "Results") {
    const alt = m.channel.alternatives[0];
    if (!m.is_final) console.log("partial:", alt.transcript);
    else if (alt.transcript.trim()) { turn.push(alt.transcript); if (m.speech_final) { console.log("TURN:", turn.join(" ")); turn = []; } }
  } else if (m.type === "UtteranceEnd" && turn.length) { console.log("TURN:", turn.join(" ")); turn = []; }
  else if (m.type === "Error") { console.error("service error", m); process.exit(1); }
  else if (m.type === "Metadata") { if (turn.length) console.log("TURN:", turn.join(" ")); ws.close(); }
};
ws.onerror = (e) => { console.error("websocket error", e.message ?? e); process.exit(1); };
```

In a browser, do not ship the key in the bundle: let a backend of yours hold the key and open the stream, as PowerConduit's apps do through vccd.

Three ways from Go: the repository's own client package `clients/go` (live streaming with reconnect, recorded audio, TTS, health, typed errors; one dependency, `github.com/coder/websocket`; copy the directory or use a `replace` in `go.mod`, there is no public module proxy), the official Deepgram Go SDK pointed at the service (tested with v3.12.0), or the plain client below. `docs/GO.md` in the repository walks through all three.

```go
import us "github.com/OptimalMatch/unidatum-speech/clients/go"

c, err := us.FromEnv()                                   // UNIDATUM_SPEECH_URL, UNIDATUM_SPEECH_KEY (or _KEY_FILE)
h, err := c.Health(ctx)                                  // GET /health (no key needed): h.OK, h.Sessions, h.Capacity
err = c.CheckKey(ctx)                                    // GET /v1/projects: nil = key accepted; *us.APIError otherwise
t, err := c.Transcribe(ctx, wavBytes, "audio/wav", "en") // recorded audio: t.Text, t.Words
s, err := c.Listen(ctx, us.ListenOptions{...})           // live: *us.Stream
res, err := c.Speak(ctx, us.SpeakOptions{Text: "..."})   // TTS, streamed: res.Audio is an io.ReadCloser
```

The smallest possible client, with only `coder/websocket`:

```go
// Live speech to text over WebSocket /v1/listen. Usage: go run . clip.wav   (16 kHz, mono, 16-bit WAV, 44-byte header)
// Env: UNIDATUM_SPEECH_URL (https://speech.example), UNIDATUM_SPEECH_KEY. Module: github.com/coder/websocket.
package main

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

	"github.com/coder/websocket"
)

type msg struct {
	Type        string `json:"type"`
	IsFinal     bool   `json:"is_final"`
	SpeechFinal bool   `json:"speech_final"`
	Channel     struct {
		Alternatives []struct {
			Transcript string  `json:"transcript"`
			Confidence float64 `json:"confidence"`
		} `json:"alternatives"`
	} `json:"channel"`
	ErrMsg string `json:"err_msg"`
}

func main() {
	base := strings.Replace(strings.TrimRight(os.Getenv("UNIDATUM_SPEECH_URL"), "/"), "http", "ws", 1)
	key := os.Getenv("UNIDATUM_SPEECH_KEY") // never hardcode
	wav, err := os.ReadFile(os.Args[1])
	if err != nil || len(wav) < 44 {
		panic("cannot read WAV")
	}
	pcm := wav[44:]
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()
	q := "language=en&encoding=linear16&sample_rate=16000&channels=1&interim_results=true&vad_events=true&endpointing=350&smart_format=true"
	c, resp, err := websocket.Dial(ctx, base+"/v1/listen?"+q, &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Token " + key}}})
	if err != nil {
		if resp != nil {
			panic(fmt.Sprintf("refused: HTTP %d (401 key, 503 capacity)", resp.StatusCode))
		}
		panic(err)
	}
	defer c.CloseNow()
	go func() {
		for i := 0; i < len(pcm); i += 3200 { // 100 ms frames in real time
			end := min(i+3200, len(pcm))
			c.Write(ctx, websocket.MessageBinary, pcm[i:end])
			time.Sleep(100 * time.Millisecond)
		}
		time.Sleep(time.Second)
		c.Write(ctx, websocket.MessageText, []byte(`{"type":"CloseStream"}`))
	}()
	var turn []string
	for {
		_, data, err := c.Read(ctx)
		if err != nil {
			return
		}
		var m msg
		if json.Unmarshal(data, &m) != nil {
			continue
		}
		switch m.Type {
		case "Results":
			if len(m.Channel.Alternatives) == 0 {
				continue
			}
			t := m.Channel.Alternatives[0].Transcript
			if !m.IsFinal {
				fmt.Println("partial:", t)
			} else if strings.TrimSpace(t) != "" {
				turn = append(turn, t)
				if m.SpeechFinal {
					fmt.Println("TURN:", strings.Join(turn, " "))
					turn = nil
				}
			}
		case "UtteranceEnd":
			if len(turn) > 0 {
				fmt.Println("TURN:", strings.Join(turn, " "))
				turn = nil
			}
		case "Error":
			panic("service error: " + m.ErrMsg)
		case "Metadata":
			if len(turn) > 0 {
				fmt.Println("TURN:", strings.Join(turn, " "))
			}
			return
		}
	}
}
```

```kotlin
// Android / Kotlin with OkHttp (not run in the repository; same protocol). Prefer a backend that holds the key, as PowerConduit does.
val req = Request.Builder()
    .url("${base.replaceFirst("http", "ws")}/v1/listen?language=en&encoding=linear16&sample_rate=16000&channels=1&interim_results=true&endpointing=350&smart_format=true")
    .header("Authorization", "Token $key")          // key from your secure config, never in source
    .build()
val ws = OkHttpClient().newWebSocket(req, object : WebSocketListener() {
    override fun onMessage(ws: WebSocket, text: String) { /* parse JSON as in the other clients */ }
    override fun onFailure(ws: WebSocket, t: Throwable, r: Response?) { /* r?.code: 401 key, 503 capacity -> fall back */ }
})
// from AudioRecord (16 kHz, mono, ENCODING_PCM_16BIT), every ~100 ms:
ws.send(ByteString.of(*pcmChunk))
// when done:
ws.send("""{"type":"CloseStream"}""")
```

## Text to speech in code

```python
#!/usr/bin/env python3
"""Text to speech. Usage: speak.py "Hello there." out.wav
POST /v1/speak (Deepgram shape) and the WebSocket form. Env: UNIDATUM_SPEECH_URL, UNIDATUM_SPEECH_KEY. pip install websockets"""
import asyncio, json, os, sys, urllib.request, wave
import websockets

URL = os.environ["UNIDATUM_SPEECH_URL"].rstrip("/"); KEY = os.environ["UNIDATUM_SPEECH_KEY"]
text, out = sys.argv[1], sys.argv[2]

# 1) HTTP: the answer is a WAV (container=wav) that streams sentence by sentence
req = urllib.request.Request(f"{URL}/v1/speak?model=aura-2-thalia-en&encoding=linear16&sample_rate=24000&container=wav",
    data=json.dumps({"text": text}).encode(), headers={"Authorization": f"Token {KEY}", "Content-Type": "application/json"})
open(out, "wb").write(urllib.request.urlopen(req, timeout=60).read())
print("http wav:", out)

# 2) WebSocket: raw 16-bit mono PCM chunks, Flushed marks the end of what was sent
async def ws_speak():
    u = URL.replace("http", "ws", 1) + "/v1/speak?model=aura-2-thalia-en&encoding=linear16&sample_rate=24000&container=none"
    async with websockets.connect(u, additional_headers={"Authorization": f"Token {KEY}"}) as ws:
        await ws.send(json.dumps({"type": "Speak", "text": text})); await ws.send(json.dumps({"type": "Flush"}))
        pcm = b""
        async for m in ws:
            if isinstance(m, bytes): pcm += m
            elif json.loads(m)["type"] == "Flushed": break
        await ws.send(json.dumps({"type": "Close"}))
        return pcm
pcm = asyncio.run(ws_speak())
with wave.open(out.replace(".wav", "-ws.wav"), "wb") as w:
    w.setnchannels(1); w.setsampwidth(2); w.setframerate(24000); w.writeframes(pcm)
print("websocket pcm bytes:", len(pcm))
```

### The three routes

- `POST /v1/speak?model=aura-2-thalia-en&encoding=linear16&sample_rate=24000&container=wav|none`, body `{"text": "..."}`. Deepgram's shape, so existing Deepgram TTS code works. `aura-2-*` names map to Kokoro voices.
- `POST /speak`, body `{"text","voice","speed"}`: PowerConduit's Kokoro sidecar style, raw PCM, header `X-Sample-Rate`, trailer `X-Took-Ms`.
- `WS /v1/speak` (same query): send `{"type":"Speak","text":"..."}` then `{"type":"Flush"}`; binary PCM frames come back, then `Flushed`. `{"type":"Clear"}` drops pending audio (`Cleared`) for interruptions; `{"type":"Close"}` ends.

Limits: 5,000 characters per request; a full queue answers HTTP 503 with `Retry-After`; one speaker per free core (RTF 0.3 to 0.8), so buffer about a second before playing. The first audio arrives after about one sentence (0.4 to 1.2 s).

**Optional cloud voices.** A Fish Audio provider exists behind `provider=fish`, off by default. It sends the text to Fish Audio's servers and needs a Fish Audio account and key; everything else stays local. `docs/FISH-AUDIO.md` says what it sends, what it costs and what was not tested. Phase 2's prosody options (`emotion`, `fx`, `normalize`) are on a branch and off by default; see the [roadmap](https://speech.unidatum.com/roadmap/).

**Interruptions.** For a voice assistant, `Clear` is how a barge-in stops the speech; the recipe for a client that pauses on sound, confirms with the service's words and resumes after a false alarm is `docs/INTERRUPTIONS.md`, summarised on the [home page](https://speech.unidatum.com/#barge-demo).

## API reference

Auth on every route except `/health` and `/metrics`: `Authorization: Token <key>` or `Bearer <key>`; for browsers `Sec-WebSocket-Protocol: token, <key>`. With no keys configured every request is refused.

| Route | What |
| --- | --- |
| `GET /health` | No auth. `ok`, `sessions`, `capacity`, `final_queue`, `tts_workers`, `tts_queue`, `retention_hours`, `final_model`. 503 while workers load models (about a minute) or if one died. |
| `GET /metrics` | No auth. Prometheus text, including `final_fallbacks_total`. |
| `GET /v1/projects` | Key check: 200 with a project list, 401 otherwise. PowerConduit calls it with a 3 s timeout before each stream. |
| `GET /v1/listen` (WebSocket) | Live audio in, `Results`, `SpeechStarted`, `UtteranceEnd`, `Metadata`, `Error` out. 503 before the upgrade when all sessions are in use. |
| `POST /v1/listen` | A wav, flac, ogg or mp3 body; Deepgram's pre-recorded response shape with words and times. |
| `POST /v1/speak`, `WS /v1/speak`, `POST /speak` | Text to speech, see above. |
| `GET /v1/voices` | Kokoro voices and the `aura-2-*` aliases. |
| `GET /v1/transcripts` | The finals kept for the retention period (text, times, language, request id, a hash prefix of the key id). No audio is ever stored. |

### Query parameters of `/v1/listen`

| Parameter | Notes |
| --- | --- |
| `model` | Accepted and ignored (`nova-3` is fine); routing is by language. |
| `language` | `en` (default from config): Parakeet final, partials. Another code: Whisper final, no partials, keyterms used. `multi`: Whisper with detection. |
| `encoding`, `sample_rate`, `channels` | `linear16` only; 8000 to 96000 Hz (resampled to 16 kHz); 1 or 2 channels (averaged). Anything else is refused with an error. |
| `interim_results` | `true` for partials (lower-case, unpunctuated, English only). |
| `endpointing` | Pause in ms that ends an utterance; default 300; use about 350 (300 to 400 is the measured range). `false`: only `Finalize` or `CloseStream` ends it (a 30 s cap still applies). |
| `utterance_end_ms` | Send `UtteranceEnd` after this much silence (PowerConduit uses 1500). |
| `vad_events` | `true` for `SpeechStarted`. |
| `punctuate`, `smart_format` | Punctuated, capitalised finals; with both off, plain lower-case words. |
| `keyterm`, `keywords` | Up to 50; used by the Whisper route only (as a prompt, 550 characters). Parakeet ignores them. |

### Messages

**Control (text frames you send):** `{"type":"KeepAlive"}` every 5 s when you have no audio (the service waits at most 30 s for anything); `{"type":"Finalize"}` forces the pending final (returned with `from_finalize: true`); `{"type":"CloseStream"}`: pending finals, then `Metadata`, then close. `Configure` is accepted and ignored.

**A `Results` message** carries `type`, `channel_index`, `start`, `duration`, `is_final`, `speech_final`, `from_finalize`, `channel.alternatives[0].{transcript, confidence, words}` (each word: `word`, `start`, `end`, `confidence`, `punctuated_word`) and `metadata.{request_id, model_info, model_uuid}`. Partial confidence is 1.0; final confidence is the mean word probability (Whisper) or 1.0 (Parakeet). Word times on partials are emission times, on finals acoustic times.

**The five fields PowerConduit reads, all present on every `Results`:** `type`, `is_final`, `speech_final`, `channel.alternatives[0].transcript`, `channel.alternatives[0].confidence`. A turn ends on `speech_final: true` or on `UtteranceEnd`; join the finals received since the last turn end; ignore empty transcripts; do not act on partials for commands. `SpeechStarted` and `UtteranceEnd` carry `"channel": [0, 1]`, a list, as Deepgram's do.

## Errors, fallback, reconnect, backpressure

| Situation | What you see | What to do |
| --- | --- | --- |
| Wrong or missing key | HTTP 401 on the handshake, `{"err_code":"INVALID_AUTH"}` | Do not retry; report a configuration error without printing the key. |
| All sessions busy | HTTP 503 `{"err_code":"CAPACITY"}` before the upgrade | Back off 1 to 2 s, retry once or twice, then fall back. |
| Service down or unreachable | Connection refused or timeout | Fall back. |
| Unsupported encoding or bad parameter | HTTP 400 or an `Error` message | Fix the request. |
| Final pass overloaded | Finals arrive as unpunctuated lower-case text (the fast text after 8 s) | Reduce load; nothing to handle in code. |
| Connection drops mid-stream | Socket closed without `Metadata` | Open a new stream; there is no resume. Keep the last seconds of audio in a ring buffer and resend them if the sentence matters. |

- **Fallback to Deepgram** is a different base URL and key. Before each new stream call `GET /v1/projects` with a short timeout; if it fails, hear with Deepgram (`wss://api.deepgram.com`), tell the user, and try the service again at the next stream. Deepgram wants `endpointing=800` and takes keyterms in English; the service wants about 350 and ignores keyterms in English.
- **Reconnect** with a small backoff (0.5 s, 1 s, 2 s, max 5 s) and a new key check; never in a tight loop.
- **Backpressure:** send at real-time pace. Do not burst a whole file faster than about 2x real time on a shared host: the final workers are the bottleneck and a flood delays everyone's finals. If your sender falls behind, drop the oldest audio. On TTS, honour `Retry-After`.
- **Health:** a load balancer or your own fallback logic can use `sessions >= capacity` from `/health`.

## Drop-in for PowerConduit

PowerConduit's service, vccd, takes the address from a flag, else the environment, else a file in `~/.config/voicecommandcontrol/`, and the key from the environment or a mode-600 file (never a flag). Choose the engine in Settings, Speech recognition: Deepgram, **Unidatum**, Whisper server, Whisper phone; or by voice with the assistant's `hearing` control (`unidatum`, `deepgram`, `whisper`, `phone`). The choice is per device and a new install never defaults to Unidatum.

| What | Flag | Environment | File |
| --- | --- | --- | --- |
| Service address | `-unidatum-speech https://speech.example` | `UNIDATUM_SPEECH_URL` | `unidatum-speech-url` |
| Its key | none, never a flag | `UNIDATUM_SPEECH_KEY` | `unidatum-speech-key` (mode 600) |
| Pause that ends a turn | `-unidatum-endpointing 350ms` |  |  |

- **Endpointing** is 350 ms for this engine; Deepgram's 800 ms would add to the second decoding pass.
- **Fallback:** before a stream vccd calls `GET /v1/projects` (3 s). If it fails, the key is refused, there is no address or the stream will not open, vccd hears with Deepgram and shows a notice; the setting is kept and retried at every new stream.
- **Turn-taking:** vccd ends a turn on held finals after 2 s with no news, and a held final goes after 10 s whatever is heard; it watches partials for the wake word too.
- **Roll back:** remove the address and restart vccd.

```bash
# ~/.config/voicecommandcontrol/env on the machine that runs vccd
VCCD_ARGS=-unidatum-speech https://speech.example

# the key in its own file, readable by you only
umask 077
printf '%s\n' "$UNIDATUM_SPEECH_KEY" > ~/.config/voicecommandcontrol/unidatum-speech-key

systemctl --user restart vccd
# then pick "Unidatum" under Settings > Speech recognition, or say: set hearing to unidatum
```

Deepgram stays available: PowerConduit falls back to it when this service is unreachable. Without a Deepgram key there is nothing to fall back to.

## For coding agents (Claude Code and others)

An agent can install the service for you, start it, check it and wire a project to it. Tell it: *"Install Unidatum Speech from speech.unidatum.com and verify it works."* The procedure it follows is the [agents page](https://speech.unidatum.com/agents/) (also [as markdown](https://speech.unidatum.com/agents.md), with the whole site in [llms.txt](https://speech.unidatum.com/llms.txt) and [llms-full.txt](https://speech.unidatum.com/llms-full.txt)). The installer has a supported automation route, `--agent`: it solves a short proof of work instead of the download page's check, then does everything a person's install does (checksum verified, no sudo, the key written to a private file and never printed). It is limited to 40 installs an hour for the site and 10 per country, and says when to retry.

The skill is one file. It carries the install steps, the verification, and the integration details (connection, audio format, the query to use, event parsing, errors and fallback, a tested Python client). It contains no keys. Agents get the base URL from `UNIDATUM_SPEECH_URL` and the key from `UNIDATUM_SPEECH_KEY` or a mode-600 file, and are told never to hardcode, print, log or commit a key, never to put it in a URL, and not to make up keys or hosts.

A prompt that works for a project: *"Add speech to text to this app using Unidatum Speech. Use the unidatum-speech skill, use endpointing 350, join finals until speech_final, fall back to Deepgram on 401, 503 or connection failure, and add a smoke test that runs when the key is set."*

```bash
# install the service (no sudo, 3 to 6 minutes; --dry-run shows the plan first)
curl -fsSL https://speech.unidatum.com/install.sh | sh -s -- --agent

# install the skill for every project you work on (one file)
curl -fsSL https://speech.unidatum.com/skill/SKILL.md --create-dirs -o ~/.claude/skills/unidatum-speech/SKILL.md

# what the skill gives the agent
#  - install, start, stop, verify, uninstall
#  - connection details, audio format, the query to use, event parsing
#  - a tested Python client; Node and Go guides in the repository
#  - errors, fallback to Deepgram, reconnect and backpressure rules
```

## Install and run the service

### Linux (systemd user unit)

```bash
# unpack the release, then: downloads about 1 GB of models, checks their hashes, starts nothing
packaging/install.sh --profile <your-profile>          # a profile from config/, its cpu lists edited for your machine
echo "UNIDATUM_SPEECH_KEYS=$(openssl rand -hex 24)" >> ~/.config/unidatum-speech/env   # private file, never commit it
systemctl --user daemon-reload && systemctl --user enable --now unidatum-speech
curl -s localhost:18790/health

# validate a profile without starting (refuses more than half the cores, efficiency cores, overlaps)
unidatum-speech -check -config ~/.config/unidatum-speech/config.toml
```

### macOS, Apple silicon (launchd, no root)

```bash
# cross-compile on a build host, copy service/ to the Mac with the binary at packaging/unidatum-speech
GOOS=darwin GOARCH=arm64 go build ./cmd/unidatum-speech
START=1 packaging/install-macos.sh --profile mac-mini-m4      # or mac-mini-m1
packaging/stop-macos.sh                                        # stop and remove

# build and test from source
cd service && go build ./cmd/unidatum-speech && go test ./...
```

**Configuration** is one TOML profile per host: `listen` (bind a private address, never a public interface), `[auth]` keys from `UNIDATUM_SPEECH_KEYS` in the environment file, `[cpu]` with `max_cpus`, `max_fraction = 0.5` and `exclude_efficiency_cores`, the `[fast]`, `[final]` and `[tts]` cpu lists, worker counts, model directories, `max_sessions` and `timeout`, `[retention]` (`transcripts = "24h"`; `"0s"` stores nothing) and `[defaults]` (`language`, `endpointing_ms`). Sizing: about 0.2 to 0.6 CPU-seconds per audio second for speech to text and RTF 0.3 to 0.6 per thread for TTS. Several hosts go behind a round-robin proxy that reads `/health`.

## Drop-in checklist, and common mistakes

- Base URL from `UNIDATUM_SPEECH_URL` (or config), key from `UNIDATUM_SPEECH_KEY` or a mode-600 file; nothing hardcoded or logged.
- Live audio is 16 kHz mono linear16 in about 100 ms binary frames at real-time pace; `CloseStream` at the end; `KeepAlive` when idle.
- `endpointing=350`, `interim_results=true`, `smart_format=true`; `vad_events=true` if you show "speaking".
- Join finals until `speech_final` or `UtteranceEnd`; ignore empty transcripts; do not act on partials for commands.
- Keyterms only if the language is not English (or `multi`).
- Handles 401, 503 and connection failure; falls back to Deepgram or tells the user; retries the service at the next stream.
- A smoke test in your repo that runs against the sample WAV, skipped when the key is not set. The key is not in the repo, the CI log, the crash report or the UI.

- Sending a WAV with its header as live audio, or the wrong sample rate without saying `sample_rate=`: garbage or no text.
- Keeping `endpointing=800` from Deepgram: turns end half a second later than needed.
- Treating partials as final, or discarding finals that arrive without `speech_final` (they are parts of the turn; join them).
- Expecting keyterms to fix an English misrecognition, punctuation in partials, partials for non-English speech, a first partial before about 0.95 s, or a final as fast as Deepgram's.
- Opening many streams from one client "to be safe": a host has 6 to 8 sessions in total.
- Waiting for `Metadata` forever: it comes only after `CloseStream`.
- Opening the service port to the internet or a LAN beyond the private network.
