# 同声传译 WebSocket

使用 Protobuf 二进制帧进行同声传译。

## 接口与鉴权

`GET https://api.tu-zi.com/v1/realtime?model={model}`

传输方式: websocket

使用模型调用 API Key。示例凭证为占位符，请从环境变量读取真实密钥。

```http
Authorization: Bearer YOUR_API_KEY
```

## 查询参数

| 字段 | 类型 | 必填 | 说明与约束 |
| --- | --- | --- | --- |
| model | string | 是 | 精确模型名，通过 URL 查询参数传入。 |

## 请求体参数

| 字段 | 类型 | 必填 | 说明与约束 |
| --- | --- | --- | --- |
| request_meta.session_id | string | 是 | 会话 UUID。 |
| event | integer | 是 | 按 AST 协议发送会话事件；100 为开始。 |
| source_audio | object | 是 | 输入音频格式配置，16 kHz、单声道、16-bit PCM。 |
| request | object | 是 | 模式 s2t/s2s 和源、目标语言。 |

## 最小请求示例

```json
{
  "request_meta": {
    "session_id": "YOUR_SESSION_UUID"
  },
  "event": 100,
  "source_audio": {
    "format": "wav",
    "rate": 16000,
    "bits": 16,
    "channel": 1
  },
  "request": {
    "mode": "s2t",
    "source_language": "zh",
    "target_language": "en"
  }
}
```

## 运行前准备

将 https://api.tu-zi.com 替换为本站地址（不要重复追加 /v1），YOUR_MODEL 替换为模型广场中的完整模型名。Python 示例需要先安装 requests；JavaScript 示例使用 Node.js 20+ 并保存为 .mjs 文件。WebSocket 示例按代码注释安装专用依赖。

先在本站令牌页面创建模型调用密钥，并设置 API_KEY 环境变量；cURL 中的 YOUR_API_KEY 需要替换。上传示例中的 input.png/input.wav 是本地文件，必须提前准备。

首次运行使用最小请求；成功后对照下方响应字段读取结果。异步接口返回任务 ID 后仍需查询，任务提交成功不代表生成已完成。

## 代码示例

### curl

```bash
# Requires a Protobuf WebSocket client. Download the official AST demo and replace its URL and headers with the values below.
```

### python

```python
# pip install "websockets>=14" "protobuf>=6.31.1"
# Copy python_protogen/ from the official AST Python demo beside this script.
import asyncio, os, uuid, wave
from websockets.asyncio.client import connect
from python_protogen.products.understanding.ast.ast_service_pb2 import TranslateRequest, TranslateResponse

async def main():
    async with connect("wss://api.tu-zi.com/v1/realtime?model=YOUR_MODEL", additional_headers={
        "Authorization": "Bearer " + os.environ["API_KEY"]
    }, max_size=2**21, open_timeout=15) as ws:
        sid = str(uuid.uuid4())
        req = TranslateRequest(event=100)
        req.request_meta.SessionID = sid
        req.source_audio.format = "wav"
        req.source_audio.rate, req.source_audio.bits, req.source_audio.channel = 16000, 16, 1
        req.request.mode, req.request.source_language, req.request.target_language = "s2t", "zh", "en"
        await ws.send(req.SerializeToString())
        async def send_audio():
            with wave.open("input.wav", "rb") as audio:
                assert (audio.getframerate(), audio.getnchannels(), audio.getsampwidth()) == (16000, 1, 2)
                while chunk := audio.readframes(1280):
                    req = TranslateRequest(event=200)
                    req.source_audio.binary_data = chunk
                    await ws.send(req.SerializeToString())
                    await asyncio.sleep(0.08)
            await ws.send(TranslateRequest(event=102).SerializeToString())
        sender = None
        try:
            async for frame in ws:
                event = TranslateResponse.FromString(frame)
                if event.event == 150: sender = asyncio.create_task(send_audio())
                if event.text: print(event.event, event.text)
                if event.event == 154: print(event.response_meta.Billing)
                if event.event in (152, 153): break
        finally:
            if sender:
                sender.cancel()
                await asyncio.gather(sender, return_exceptions=True)

asyncio.run(main())
```

### javascript

```javascript
// Use the official Go/Python AST Protobuf demo or protobufjs.
// URL: wss://api.tu-zi.com/v1/realtime?model=YOUR_MODEL
// Authorization: Bearer YOUR_API_KEY
// Send TranslateRequest as binary; wait for event 150 before audio, finish with event 102.
// See the complete Python example.
```

## 响应字段

| 字段 | 类型 | 说明与约束 |
| --- | --- | --- |
| event | integer | AST 响应事件类型。 |
| text | string | 字幕内容（按事件提供）。 |
| data | binary | 音频数据（按事件提供）。 |

## 流式响应

示例 JSON 表示 Protobuf 消息内容，不能直接把 JSON 文本发送到 WebSocket。需要官方 AST .proto 生成的客户端；参考模型快速上手的 Python 完整示例。

## 错误处理与重试

检查 HTTP 状态与该协议的错误对象；不要将不同协议的错误字段混用。401/403 检查凭证与权限，429 退避等待，5xx 检查网关或上游状态。错误正文可能含 error/message/code 等字段，以实际协议为准。

查询可采用有上限的指数退避；创建任务、生成内容、创建或删除密钥等操作不要盲目重试，以免重复计费或重复执行。

## 适用限制

本页是协议基础结构。模型可用参数、枚举、上限和异步行为以该模型“快速上手”为准；示例中的 YOUR_MODEL 必须替换。表中表单初始值不代表上游默认值。

## 文档依据

定义版本: 1

审核日期: 2026-11-02

来源: https://api.tu-zi.com/docs/api/reference-relay-seed-interpretation

关联协议说明: https://api.tu-zi.com/docs/api/audio-realtime

本文只包含接口文档和示例。真实密钥、账号数据及用户请求内容不包含在复制内容中。
