WebSocket

API: https://api.fourhz.cn

wss://api.fourhz.cn/v1/speech/realtime

服务端使用 X-API-Key 请求头。浏览器通过 Portal 获取 resource=speech.realtime 的临时凭证,并立即发送以下首帧;长期密钥不要放在浏览器或 URL 中。

{"type":"session.authenticate","access_token":"TEMPORARY_TOKEN"}

随后发送会话配置,等待 session.ready 再发送音频:

{"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. 会话使用问答模式。声音热更仅在 session.ready 的 session_update 数组包含 voice 时可用;发送 session.update 的 voice_sample(单声道 16 kHz PCM16LE 的 base64,1.5–6 秒)或 voice="default",等待 session.updated 确认后才视为切换成功。未知配置会被拒绝。

音频传输

支持 Opus 编码和解码的浏览器可在 session.start 请求 audio_codec="opus";必须等待 session.ready.audio_codec 确认实际传输格式,返回 pcm 或未返回该字段时继续发送 PCM。就绪前不发送音频。Opus 二进制帧每条为一个 raw Opus packet(非 Ogg),上行 16 kHz 单声道、20 毫秒、目标 24 kbps、关闭 DTX;下行解码为 48 kHz 单声道。Opus 为有损音频编码,不是 WebSocket deflate 压缩。声音克隆 voice_sample 和 session.greeting 的 JSON 音频仍使用各自约定的 PCM,不随通话编码改变。

音频与事件

DirectionFormat
InputBinary 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.
OutputPCM transport: binary PCM16 little-endian, mono, 48 kHz. Opus transport: decode raw Opus packets to mono 48 kHz. Queue and play sequentially.
JSONreply.started, reply.text (delta), reply.done (text), user.text (optional captions), yield, error.

收到 yield 后立即丢弃待播音频。播放期间持续采集输入,并开启回声消除;不要用本地 VAD 暂停传输。结束时发送 session.end 并停止上行麦克风,等待 session.ended、Termination 或正常关闭后再释放播放和连接。session_update_* 错误仅表示设置更新失败,不应中断仍在进行的通话。

用量与限制

从 session.ready 起按连接时长计费,静音和等待也包含在内。每次最多 2 分钟,由 APIHub 执行,临时凭证可进一步缩短。在线体验无需注册,使用账户已有赠送金额;不按累计通话 120 秒封顶,每次会话仍最多 120 秒,余额足够时可继续通话。使用 API 需要账号与可用余额。并发已满或未配置服务时返回 503,不会切换到其他模型。

Try FourHzLive

Examples

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.cn/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())

Scenes · Beta

先读取 GET /v1/speech/workspaces 获取当前账号的原生场景目录。demo_workspace 使用返回的 name;不传表示普通通话。delegation 为布尔值:允许模型把任务交给该账号隔离的服务器 Agent,普通问答仍由语音模型直接回答。工作区不是用户本机桌面。

{"type":"session.start","mode":"qa","prompt_language":"en","demo_workspace":"robot-yard","delegation":true}

Robot Yard、Blank project、Sorting visualizer、Voice Cloning、To-do list 五项需设 delegation=true;在线体验固定开启且不可关闭。Star catcher 已下架。

服务器按可信目录选择工具和说明。机器人用原页面工具;网站用打开、读取和搜索页面工具;构建场景由 Agent 修改文件后刷新预览。收到 tool_call 后,仅在当前场景执行一次并返回 JSON 工具结果。不要发送旧的 scenario/actions 或任意 instructions/session_tools。页面语音控制与服务电话要求目录声明 fourhz_scene_protocol: 1;旧目录即使列出页面或门店,也不表示语音路由可用,重新加载目录后再试。

{"type":"input.text","role":"tool","text":"{\"ok\":true}"}

服务电话目录为 GET /v1/speech/workspaces/service-calls。选择对应语言的 stores 条目,将其 id 作为 service_store,与 demo_workspace 互斥。体验界面展示点餐门店,订单是原训练场景的模拟结果,不会真实下单。

{"type":"session.start","mode":"qa","prompt_language":"en","service_store":"order-en000","delegation":false}

收到 yield 时清空待播放语音。通话内文字使用 input.text、role=user、respond=true,最多 16000 个 UTF-8 字节。仅当 session.ready 声明 task_cancel=true,才可用本会话 task.update 已返回的 task_id 发送 task.cancel;等待真实终止更新,不提前显示取消成功。手动挂断发送 session.end,停止上行麦克风,等待 session.ended 或正常关闭后释放资源。

正常结束

与 ASR WebSocket 一致,正常结束返回 Termination,然后以 1000 正常关闭。达到本次时长上限时,reason 为 duration_limit_reached;关闭确认等待不额外计费。audio_duration_seconds 是已接收音频时长,session_duration_seconds 是就绪后的连接时长。

{"type":"Termination","audio_duration_seconds":119.92,"session_duration_seconds":120,"reason":"duration_limit_reached","message":"Session duration limit reached."}