> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# 实时 API

> 创建短期实时浏览器会话，并获取 BeatAPI 实时 SDK 使用的 `client_secret`。

`POST https://api.beatapi.io/v1/realtime/sessions`

创建短期实时浏览器会话，并获取 BeatAPI 实时 SDK 使用的 `client_secret`。

## 鉴权

`Authorization`   `string`   **必填**

在 `Authorization` 请求头中以 Bearer 令牌发送服务端 API 密钥，可在[控制台](https://beatapi.io/dashboard)创建。

```
Authorization: Bearer <BEATAPI_API_KEY>
```

永久 API 密钥只能保存在可信服务端，不能写入浏览器、移动端、公开脚本、日志或截图。请求体必须使用 `Content-Type: application/json`。此接口必须为每个逻辑创建请求设置唯一的 `Idempotency-Key`，长度为 1–255 个字符；只有完全相同的请求体才能安全复用原键。

## 请求体

字段名、类型和枚举值保留英文原样，用途和限制用中文说明。

`max_duration_seconds`   `enum<integer>`   **必填**

该实时会话允许的最长持续时间，单位为秒，也是预留费用的档位。

**取值与默认值:** 可选值 `15`、`60`、`300`

---

`allowed_origins`   `string[]`   **必填**

允许使用短期会话密钥的完整浏览器来源列表。生产环境应使用 HTTPS。

**取值与默认值:** 1–10 项

---

`metadata`   `object`   **选填**

用于业务关联的自定义字符串元数据。

## 响应

成功请求返回 HTTP `201`，响应体如下。

```json
{
  "data": {
    "id": "rts_8K2qA",
    "object": "realtime.session",
    "status": "ready",
    "client_secret": "brt_live_example_short_lived_secret",
    "expires_at": "2026-08-12T10:01:00.000Z",
    "max_duration_seconds": 60,
    "allowed_origins": [
      "https://app.example.com"
    ],
    "credits": {
      "reserved": 1.2,
      "settled": 0,
      "refunded": 0
    },
    "request_id": "req_abc123",
    "created_at": "2026-08-12T10:00:00.000Z",
    "connected_at": null,
    "closed_at": null
  }
}
```

## 在浏览器中连接

安装实时 SDK。

```bash
npm install @beatapi/realtime
```

```ts
import { createRealtimeClient } from '@beatapi/realtime';

const camera = await navigator.mediaDevices.getUserMedia({ video: true });
const output = document.querySelector<HTMLVideoElement>('#output')!;
const client = createRealtimeClient({ clientSecret: session.client_secret });
const connection = await client.connect({
  input: camera,
  output,
  initial: { prompt: '保留动作，同时应用指定风格。' },
});
```

只能把短期 `client_secret` 交给 `allowed_origins` 中完全匹配的来源。体验结束后，请断开浏览器连接、停止本地媒体轨道，并关闭服务端会话。

* `GET /v1/realtime/sessions/{session_id}`：查询实时会话。
* `DELETE /v1/realtime/sessions/{session_id}`：关闭实时会话。

## 下一步

将返回的 `client_secret` 交给 `@beatapi/realtime`。永久 API 密钥必须保存在可信服务端，浏览器体验结束后请关闭会话。

## 错误

| 状态码   | 含义与处理方式                                                                                                                                                                                                                                                                  |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `400` | JSON 格式错误，或字段、取值、参数组合不被接受（`bad_request`，错误信息会点名字段）；输入未通过内容审核时为 `content_policy_violation`。修正后再请求，原样重试仍会失败。                                                                                                                                                               |
| `401` | 未提供 API 密钥（`missing_api_key`），或密钥错误、已过期、已停用或额度已用尽（`invalid_api_key`，错误信息会说明是哪一种）。不要原样重试。                                                                                                                                                                                 |
| `402` | 余额不足（`insufficient_credits`）：账户余额为零或低于本次请求的价格。充值后再请求。                                                                                                                                                                                                                    |
| `409` | 幂等键在 24 小时内已用于其他请求体或路径，或使用该键的首个请求仍在处理中（`idempotency_conflict`）。只对完全相同的请求复用原键。                                                                                                                                                                                            |
| `429` | 请求过于频繁（`rate_limit_exceeded`，含免费模型限额）。按 `Retry-After`（也在 `error.retry_after_seconds`）等待后重试。                                                                                                                                                                              |
| `503` | 请求未能完成（`processing_unavailable`、`processing_timeout`、`processing_failed` 或 `result_transfer_failed`），未扣费，可退避重试；503 不带 `Retry-After` 和 `retry_after_seconds`。BeatAPI 不返回 502 或 504。实时接口在本部署未启用时为 `realtime_disabled`（不可重试），容量暂时不足时为 `realtime_capacity_unavailable`（可重试）。 |