FourHzLive
FourHzLive Beta
The model understands speech and generates spoken responses, with full-duplex audio and interruptions.
WebSocket
API: https://api.fourhz.ai
wss://api.fourhz.ai/v1/speech/realtime
Servers use the X-API-Key header. Browsers obtain a scoped speech.realtime temporary token through Portal, then immediately send the first frame below. Never expose long-lived keys in browser code or URLs.
{"type":"session.authenticate","access_token":"TEMPORARY_TOKEN"}Then start the session and wait for session.ready before sending audio:
{"type":"session.start","mode":"qa","prompt_language":"zh"}
{"type":"session.ready","model":"fourhz-live","mode":"qa","input_sample_rate":16000,"output_sample_rate":48000,"frame_ms":80}prompt_language: zh / en. Sessions use QA mode. Voice changes are available only when session.ready advertises voice in session_update. Send session.update with voice_sample (base64 mono 16 kHz PCM16LE, 1.5–6 seconds) or voice="default", and wait for session.updated before reporting success. Unknown options are rejected.
Audio transport
Browsers supporting both Opus encoding and decoding may request audio_codec="opus" in session.start. Wait for session.ready.audio_codec before sending audio: pcm or an omitted field means PCM. Each Opus binary frame contains one raw packet, not Ogg: uplink is mono 16 kHz, 20 ms, approximately 24 kbps with DTX disabled; downlink decodes to mono 48 kHz. Opus is lossy audio coding, not WebSocket deflate compression. The PCM formats of voice_sample references and session.greeting JSON audio remain unchanged.
Audio and events
| Direction | Format |
|---|---|
| Input | Binary PCM16 little-endian, mono, 16 kHz. Send continuously at realtime speed. The playground sends 40 ms packets (640 samples / 1,280 bytes). The server’s frame_ms: 80 describes its model step, not a required client packet size. Silence must also be sent while listening or muted. Maximum frame: 32,000 bytes; burst allowance: 2 seconds. |
| Output | PCM transport: binary PCM16 little-endian, mono, 48 kHz. Opus transport: decode raw Opus packets to mono 48 kHz. Queue and play sequentially. |
| JSON | reply.started, reply.text (delta), reply.done (text), user.text (optional captions), yield, error. |
On yield, immediately discard queued playback. Continue capturing during playback with echo cancellation; do not pause transmission using local VAD. To end, send session.end and stop microphone transmission; wait for session.ended, Termination or normal close before releasing playback and the connection. A session_update_* error rejects the settings change and must not disconnect an otherwise live call.
Usage and limits
Billed by connected duration starting at session.ready, including silence and waiting. Maximum 2 minutes, enforced by APIHub; temporary tokens may shorten this. The playground uses the existing guest account credit without registration. There is no cumulative 120-second voice allowance; each session is still limited to 120 seconds, and further calls require sufficient remaining credit. API use requires an account with available credit. Capacity exhaustion or an unconfigured service returns 503; there is no model fallback.
Examples
Issue a short-lived token on your server. Use its access_token in the first WebSocket frame; cURL is only used for this HTTP exchange.
curl https://api.fourhz.ai/auth/v1/ephemeral-tokens \
-H "X-API-Key: $FOURHZ_API_KEY" -H 'Content-Type: application/json' \
-d '{"resource":"speech.realtime","max_session_seconds":120}'Python 3.11+, websockets. input.wav: PCM16, mono, 16 kHz. Writes 48 kHz PCM16 response audio to reply.pcm. Feed silence after the input so the model can finish its response.
import asyncio, os, wave
import websockets
async def main():
async with websockets.connect(
"wss://api.fourhz.ai/v1/speech/realtime",
additional_headers={"X-API-Key": os.environ["FOURHZ_API_KEY"]},
) as ws:
await ws.send('{"type":"session.start","mode":"qa","prompt_language":"zh"}')
print(await ws.recv()) # session.ready; stop here on an error
async def capture_reply():
with open("reply.pcm", "wb") as out:
async for frame in ws:
if isinstance(frame, bytes): out.write(frame)
else: print(frame) # yield: flush queued playback in a live player
receive = asyncio.create_task(capture_reply())
try:
with wave.open("input.wav", "rb") as audio:
assert (audio.getframerate(), audio.getnchannels(), audio.getsampwidth()) == (16000, 1, 2)
for _ in range(750): # 30 seconds at 40 ms per packet
await ws.send(audio.readframes(640) or bytes(1280))
await asyncio.sleep(0.04)
finally:
await ws.send('{"type":"session.end"}')
try:
await asyncio.wait_for(receive, timeout=5)
finally:
await ws.close()
asyncio.run(main())Transport skeleton for a browser: obtain access_token from your authenticated server, send microphone PCM16 continuously after session.ready, and play received PCM16 at 48 kHz. Never embed your permanent key here.
const ws = new WebSocket('wss://api.fourhz.ai/v1/speech/realtime');
ws.binaryType = 'arraybuffer';
ws.onopen = () => {
ws.send(JSON.stringify({type:'session.authenticate', access_token}));
ws.send(JSON.stringify({type:'session.start', mode:'qa', prompt_language:'zh'}));
};
ws.onmessage = ({data}) => {
if (data instanceof ArrayBuffer) { playPCM16(data, 48000); return; }
const event = JSON.parse(data);
if (event.type === 'session.ready') startMicrophonePCM16(16000, audio => ws.send(audio));
if (event.type === 'yield') clearPlaybackQueue();
if (event.type === 'reply.text') showCaption(event.delta);
if (event.type === 'Termination') { stopMicrophone(); clearPlaybackQueue(); ws.close(); return; }
if (event.type === 'error' && !event.code?.startsWith('session_update_')) { stopMicrophone(); clearPlaybackQueue(); ws.close(); }
};
ws.onclose = () => { stopMicrophone(); clearPlaybackQueue(); };Scenes · Beta
Read GET /v1/speech/workspaces for the account’s native catalog. Set demo_workspace to a returned name, or omit it for a plain call. Boolean delegation allows the model to hand work to the account’s isolated server agent; ordinary questions are answered by the voice model. This workspace is not the user’s local desktop.
{"type":"session.start","mode":"qa","prompt_language":"en","demo_workspace":"robot-yard","delegation":true}Set delegation=true for Robot Yard, Blank project, Sorting visualizer, Voice Cloning and To-do list. The playground keeps delegation enabled for these five scenes. Star catcher has been withdrawn.
The server selects tools and instructions from the trusted catalog. Robot Yard uses page tools; sites support navigation, reading and search; build scenes let the agent edit files and refresh the preview. Execute each tool_call once in the current scene and return its JSON result. Do not send obsolete scenario/actions or arbitrary instructions/session_tools. Page voice controls and service calls require fourhz_scene_protocol: 1. Older catalogs may list previews or stores before voice routing is ready; reload the catalog and retry.
{"type":"input.text","role":"tool","text":"{\"ok\":true}"}Read GET /v1/speech/workspaces/service-calls, choose a store in the intended language and send its id as service_store, mutually exclusive with demo_workspace. The playground offers ordering stores. Results simulate the original training scenarios; no real order is placed.
{"type":"session.start","mode":"qa","prompt_language":"en","service_store":"order-en000","delegation":false}Clear queued playback on yield. Text input uses input.text with role=user, respond=true and a maximum of 16000 UTF-8 bytes. Send task.cancel only when session.ready advertises task_cancel=true, using a task_id already received in this session’s task.update. Wait for the terminal task update before reporting cancellation. To hang up, send session.end, stop microphone transmission and wait for session.ended or normal close before cleanup.
Normal termination
Like ASR WebSockets, normal completion returns Termination followed by close code 1000. The reason duration_limit_reached indicates the session duration limit was reached. Waiting for the close acknowledgement adds no billable time. audio_duration_seconds measures received audio; session_duration_seconds measures the connection after readiness.
{"type":"Termination","audio_duration_seconds":119.92,"session_duration_seconds":120,"reason":"duration_limit_reached","message":"Session duration limit reached."}