4Hz / fourhz-focus
Speaker Diarization · Realtime · RTT
Distinguish speakers and label each contribution.
Service endpoints
Service URL: https://api.fourhz.ai
| Method / Protocol | Path | Content-Type / Frames | Auth |
|---|---|---|---|
| WebSocket | /v1/asr/realtime | JSON control + PCM16LE binary | Authorization: <API Key> / ?token=… |
Two variants
Diarization only
speaker_labels=true returns anonymous roles without enrollment.
Diarization + speaker identification
Keep speaker_labels=true and supply fourhz_identify_candidates. Create candidates using enrollment. An unknown result or best_candidate is not a confirmed identity.
Speaker enrollmentAuthentication
Use the raw API key without Bearer. Put it in the HTTP Authorization header; keep long-lived keys on the server.
Authorization: $FOURHZ_API_KEY
When a temporary credential is required, exchange the API key for a single-use token on the server and put the returned token in the token parameter of the WebSocket URL below. Mint a fresh token for each connection.
Request parameters
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
speech_model | string | Yes | fourhz-focus | Select the speech recognition model for this endpoint. |
speaker_labels | boolean | Yes | true | Set true to separate speakers and return anonymous speaker labels. |
WebSocket send parameters
After receiving Begin, send an UpdateConfiguration JSON text message to update background speech rejection on the active connection.
| Field | Type | Required | Description |
|---|---|---|---|
type | string | Yes | UpdateConfiguration |
reject_background_speech | boolean | Yes | Background speech rejection. Set to true to filter low-confidence transcripts and help keep background speech out of the results. Set to false to disable this filter. |
{"type":"UpdateConfiguration","reject_background_speech":true}Response fields
Speaker naming and revisions
Handle FourHzSpeakerNaming and FourHzSpeakerRevision, updating existing Turns by turn_order. Termination.fourhz_speaker_names is authoritative; unknown is not a successful match.
| Field | Type | Meaning and availability |
|---|---|---|
type | string | Begin, Turn, Termination, Error, and documented extension events. |
id | string | Session ID in Begin for troubleshooting. |
expires_at | integer | Session expiration Unix time in Begin, distinct from token expiry. |
turn_order | integer | Stable utterance ID; gaps are allowed. Replace older snapshots of the same ID. |
transcript | string | Complete current utterance snapshot, not an append-only delta. |
end_of_turn | boolean | true means the utterance is finalized. |
turn_is_formatted | boolean | Whether the text is formatted. |
audio_duration_seconds | number | Received audio duration in seconds, in Termination. |
session_duration_seconds | number | Session duration in seconds, distinct from audio duration. |
error | string | Error-event message; results may be incomplete. |
speaker_label / utterances[].speaker | string | Anonymous role A/B/… or UNKNOWN, not a real-person identity. |
utterances[].start / end | integer | PRE/SYNC utterance start/end in milliseconds. |
utterances[].text | string | Text of this speaker’s utterance. |
fourhz_speaker_name | string? | Name returned after a server match; absence is not a successful identification. |
fourhz_speaker_names[] | array? | Final speaker matches in Termination; only matched confirms identity. |
turns[] | array | Speaker revision entries; update existing Turns by turn_order. |
Request examples
Code samples
curl "https://api.fourhz.ai/v1/token?expires_in_seconds=60" \
-H "Authorization: $FOURHZ_API_KEY"
# Use the returned token in this WebSocket URL (for example with wscat):
TOKEN=$(jq -r .token token.json)
wscat -c "wss://api.fourhz.ai/v1/asr/realtime?speech_model=fourhz-focus&speaker_labels=true&token=$TOKEN"# pip install websocket-client
# audio.pcm: 16 kHz, mono, signed 16-bit little-endian (no WAV header)
import json, os, threading, time
import websocket
ws = websocket.create_connection("wss://api.fourhz.ai/v1/asr/realtime?speech_model=fourhz-focus&speaker_labels=true", header=["Authorization: " + os.environ["FOURHZ_API_KEY"]], timeout=15)
ws.settimeout(None)
ready = threading.Event()
done = threading.Event()
errors = []
def receive():
try:
while not done.is_set():
event = json.loads(ws.recv())
print(event)
if event.get("type") == "Begin":
ready.set()
if event.get("type") in ("error", "Error"):
errors.append(event)
done.set()
ready.set()
if event.get("type") == "Termination":
done.set()
except Exception as error:
if not done.is_set():
errors.append(str(error))
done.set()
ready.set()
thread = threading.Thread(target=receive, daemon=True)
thread.start()
try:
if not ready.wait(15) or errors:
raise RuntimeError("Connection not ready", errors)
with open("audio.pcm", "rb") as audio:
while chunk := audio.read(16000):
if done.is_set():
break
ws.send_binary(chunk)
time.sleep(len(chunk) / 32000)
if not done.is_set():
ws.send(json.dumps({"type":"Terminate"}))
if not done.wait(70):
raise TimeoutError("No final completion event")
if errors:
raise RuntimeError(errors)
finally:
done.set()
ws.close()
thread.join(timeout=2)// Node.js 22+: npm install ws
// Server-side example. audio.pcm: 16 kHz mono PCM16LE, no WAV header.
import WebSocket from 'ws';
import {readFile} from 'node:fs/promises';
const pcm = await readFile('audio.pcm');
const ws = new WebSocket("wss://api.fourhz.ai/v1/asr/realtime?speech_model=fourhz-focus&speaker_labels=true", {headers: {"Authorization": process.env.FOURHZ_API_KEY}});
let started = false, finished = false;
const timer = setTimeout(() => {console.error('No final completion event'); ws.terminate();}, pcm.length / 32 + 85000);
ws.on('error', error => {console.error(error); clearTimeout(timer);});
ws.on('close', () => {clearTimeout(timer); if (!finished) console.error('Incomplete session');});
ws.on('message', async data => {
const event = JSON.parse(data.toString());
console.log(event);
if (event.type === "Termination") {finished = true; clearTimeout(timer); ws.close(); return;}
if (event.type === 'Error' || event.type === 'error') {console.error(event); ws.close(); return;}
if (event.type === "Begin" && !started) {
started = true;
for (let offset = 0; offset < pcm.length && ws.readyState === WebSocket.OPEN; offset += 16000) {
if (ws.bufferedAmount > 64000) {console.error('Send backlog'); ws.terminate(); return;}
ws.send(pcm.subarray(offset, offset + 16000));
await new Promise(resolve => setTimeout(resolve, 500));
}
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({type: "Terminate"}));
}
});Sending and receiving
1. Send audio
Send 16 kHz mono PCM16LE as binary audio. A 500 ms frame (16000 bytes) is recommended; do not combine many frames into one oversized message.
# audio.pcm: 16 kHz, mono PCM16LE, without a WAV header
with open("audio.pcm", "rb") as audio:
while chunk := audio.read(16000): # 500 ms per frame
ws.send_binary(chunk)2. Receive events
The server sends Begin, Turn, and Termination in order. Begin confirms the session, Turn carries transcript snapshots, and Termination means the server has finished and the connection can close.
| Event | What it means | Client action |
|---|---|---|
Begin | Returns the session id, model, and expiry. | Record id and start sending audio. |
Turn | Returns the current utterance snapshot. | Replace the same turn_order; do not append snapshots. |
Termination | Returns final session information and received audio duration. | Close the WebSocket only after receiving it. |
{"type":"Begin","id":"session-id","model":"fourhz-focus"}
{"type":"Turn","turn_order":0,"end_of_turn":true,"transcript":"Hello world.","speaker_label":"A","fourhz_speaker_name":"Alice"}
{"type":"Termination","audio_duration_seconds":4.2,"fourhz_speaker_names":[{"speaker_label":"A","status":"matched","enrollment_id":"enr_a","name":"Alice"}]}3. How Turn text updates
The same turn_order may receive partial and then final snapshots. Partial is temporary; persist the final snapshot.
| Field | Partial Turn (speaking) | Final Turn (settled) |
|---|---|---|
transcript | Snapshot of the utterance so far (no punctuation) | Punctuated, ITN-normalised final text |
utterance | Always an empty string | Mirrors transcript (redundant compatibility field) |
end_of_turn | false | true — the utterance is done; the next one has a different turn_order |
turn_is_formatted | false | true — this transcript is the punctuated, normalised final text |
4. Session limits
The termination event is documented in “Receive events”. The table below only lists session and input limits for troubleshooting timeouts, idle input, and control-message issues.
| Begin pre-Begin buffer | 512 KiB (≈16 s at 16 kHz PCM16LE); exceeding it → 400 and close |
| Session duration | Server-configured ceiling; a token caps the session to its value at issue time. On timeout you get Error (Session time limit reached.) and close |
| Audio-frame idle timeout | The session ends normally after 60 seconds without application input, with session_idle and close code 1000. Reconnect to continue. |
| Terminate flush window | After Terminate the server waits up to 60 s for the upstream to flush; beyond that the session ends with Error (Streaming ASR temporarily unavailable.) |
| Control messages | UpdateConfiguration updates settings. Terminate ends the session; repeated Terminate messages have no effect, and subsequent audio is ignored. |
| Billing | Billed per received audio second (asr_realtime); audio already received is settled even if the client disconnects mid-session |
Error codes
Every HTTP error body contains error_code (machine-readable) and message (human-readable). Legacy fields such as detail, code/msg or an upstream error object are kept and status codes are unchanged. Clients should read error_code and message first.
Before the WebSocket is established, 4xx/5xx values are HTTP status codes. After connection, Error, 1000 and 1011 are WebSocket events/close codes, not HTTP responses. HTTP error bodies usually contain error_code and message.
| Type | Status/code | Trigger |
|---|---|---|
| HTTP | 400 (before upgrade) | Missing or invalid query parameters (invalid_request), or a conflicting combination (invalid_config). |
| HTTP | 401 | Missing or invalid API key, or an expired/used single-use token. |
| HTTP | 402 | Insufficient balance. |
| HTTP | 404 | The enrollment does not exist or is not owned by the current API key. |
| HTTP | 409 | The Idempotency-Key is reused by another job. |
| HTTP | 422 | No backend can serve diarization or role naming (unsupported_capability), or the selected model does not support it. |
| HTTP | 429 | Rate limited; wait for the response Retry-After before retrying. |
| WebSocket | session_timeout / 1000 | The session reached its maximum lifetime and ends normally. |
| WebSocket | session_idle / 1000 | No application input for 60 seconds; the session ends normally, not as a service failure. |
| WebSocket | 503 / 1011 (in session) | The upstream is temporarily unavailable: dial failure, flush timeout, or engine exit. |
Idle session end: session_idle
Applies to all realtime ASR models, including Spectrum and Focus.
{
"type": "Error",
"error_code": "session_idle",
"error": "Session ended after 60 seconds without application input. Reconnect to continue."
}Send Terminate when recording ends. After an idle end, reconnect when recording resumes. Silent audio frames are input; WebSocket ping/pong does not reset application inactivity.