> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokenlab.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# 实时 WebSocket

> 通过 WebSocket 连接实时语音和多模态会话

## 概览

这个端点用于实时语音识别、语音合成、语音翻译或实时多模态模型等会话。普通 `GET` 请求会返回端点元信息；WebSocket 升级请求会代理到路由后的实时上游会话。

## 支持范围

这个端点是 TokenLab 的实时 WebSocket 代理。它支持普通 `GET /v1/realtime` 元信息检查，也支持在同一路径上发起 WebSocket 升级。它不提供 OpenAI Realtime 的 REST 辅助端点，例如 `POST /v1/realtime/client_secrets`、`POST /v1/realtime/translations/client_secrets`、Realtime Calls（`accept`、`hangup`、`refer`、`reject`），也不提供 legacy beta REST session / transcription-session 创建。

浏览器或移动端应用应把长期 API Key 保留在服务端。这个端点不会签发短期 Realtime client secret。

<Note>Agent 应先通过 `/v1/models` 发现支持 realtime 的模型，再打开 socket。</Note>

## 连接

<ParamField query="model" type="string" required>
  实时模型 ID。请选择模型说明中包含 realtime 支持的模型。
</ParamField>

<ParamField header="Authorization" type="string" required>
  Bearer API Key。WebSocket 客户端应在升级请求中发送 `Authorization: Bearer sk-your-api-key`。
</ParamField>

<RequestExample>
  ```javascript JavaScript theme={null}
  import WebSocket from 'ws';

  const socket = new WebSocket('wss://api.tokenlab.sh/v1/realtime?model=gpt-realtime', {
    headers: { Authorization: 'Bearer sk-your-api-key' }
  });

  socket.on('open', () => {
    socket.send(JSON.stringify({
      type: 'session.update',
      session: { modalities: ['text', 'audio'] }
    }));
  });

  socket.on('message', (data) => {
    console.log('realtime event', data.toString());
  });
  ```

  ```bash cURL theme={null}
  curl "https://api.tokenlab.sh/v1/realtime" \
    -H "Authorization: Bearer sk-your-api-key"
  ```
</RequestExample>

## 消息

TokenLab 会在客户端和路由后的实时提供方之间转发 WebSocket 消息。请保留所选模型的官方事件结构，并通过查询参数传入 `model`。

## 计费与关闭

实时会话使用同一 API Key 余额。TokenLab 会在 socket 打开时预扣小额估算费用，并在会话关闭时结算或退款。

会话完成后关闭客户端 socket。如果上游先关闭，TokenLab 会尽可能把关闭码转发给客户端。

## 响应示例

<ResponseExample>
  ```json Connected theme={null}
  {
    "type": "session.created",
    "session": {
      "id": "sess_abc123",
      "model": "gpt-realtime",
      "modalities": ["text", "audio"]
    }
  }
  ```
</ResponseExample>

## 重要字段

<ResponseField name="type" type="string">API 返回的事件或消息类型。</ResponseField>
<ResponseField name="session.id" type="string">实时提供方返回的标识符；可用于日志和支持排障，不是 REST session URL。</ResponseField>
