> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/multi-character-rooms.md).

# 在一个房间中托管多个角色

将一组 Convai 角色连接到一个实时房间，选择由哪个角色回答，实时更改角色列表，并允许第二个人加入。

在一个实时房间中容纳多个角色，并且无需重新连接即可与其中任意角色交谈。本页适用于包含多个说话者的场景，例如向导和评估员、多人面试或一组 NPC。

{% hint style="warning" %}
多角色房间目前处于 Beta 阶段。你的账户必须启用 `MULTI_CHARACTER_V0` 权限；该权限默认关闭。未启用时，使用角色列表进行连接会失败，并返回 `403 MULTI_CHARACTER_V0_DISABLED`.
{% endhint %}

### 角色列表房间的工作方式

房间中的每个角色都是独立的参与者，拥有自己的语音、对话历史和生命周期。房间是共享的；角色状态则不是。

创建房间时，传入一个有序的 `characters` 数组，而不是 `characterId`。每个条目都会成为角色列表中的一个成员：

* `characters[0]` 是初始的活跃成员，也是第一个作答的角色。
* 同一个 `characterId` 可以出现多次。每个条目都是独立副本，拥有自己的历史和语音。
* 每个成员都会获得一个 `membershipId`。通过 `membershipId`来指定成员，而不要使用 `characterId`，因为同一角色的两个副本会共享一个 `characterId`.

角色列表房间需要使用 realtime (WebRTC) 传输方式，并且 `endUserId`.

### 不能为空白

{% tabs %}
{% tab title="React" %}
{% code title="src/App.tsx" %}

```tsx
import { useConvaiClient } from '@convai/web-sdk/react';
import { ConvaiWidget } from '@convai/web-widget/react';

const GUIDE = 'YOUR_CHARACTER_ID';
const ASSESSOR = 'YOUR_SECOND_CHARACTER_ID';

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    endUserId: 'player-42',
    characters: [
      { characterId: GUIDE },     // characters[0] answers first
      { characterId: ASSESSOR },
      { characterId: GUIDE },     // an independent second copy of the guide
    ],
    maxNumParticipants: 2,
  });

  const { characters, activeMembershipId } = client.state;

  return (
    <div>
      <ul>
        {characters.map((c) => (
          <li key={c.membershipId}>
            {c.displayName ?? c.membershipId.slice(0, 8)} · {c.provisioningStatus}
            {c.membershipId === activeMembershipId && ' · active'}
            {c.failureCode && ` · failed: ${c.failureCode}`}
          </li>
        ))}
      </ul>
      <ConvaiWidget convaiClient={client} />
    </div>
  );
}
```

{% endcode %}
{% endtab %}

{% tab title="TypeScript" %}
{% code title="src/main.ts" %}

```typescript
import { ConvaiClient, ConvaiRoomError } from '@convai/web-sdk/core';

const GUIDE = 'YOUR_CHARACTER_ID';
const ASSESSOR = 'YOUR_SECOND_CHARACTER_ID';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  endUserId: 'player-42',
  characters: [
    { characterId: GUIDE },
    { characterId: ASSESSOR, characterSessionId: 'resume-this-history' },
  ],
  sharedSessionKey: 'match-7-party-a',
  maxNumParticipants: 2,
});

try {
  await client.connect();
  console.log(client.roomSession?.roomSessionId);
  console.log(client.characters.map((c) => c.membershipId));
} catch (error) {
  if (error instanceof ConvaiRoomError) {
    // 记录 requestTraceId：支持人员可用它查找请求。
    console.error(error.status, error.code, error.requestTraceId);
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

* `characters` 和 `characterId` 不能同时使用。两者都传入时，会在发送任何请求之前抛出异常。
* 角色列表项必须使用纯 UUID。以下版本选择器： `characterId` 可接受的，例如 `<uuid>-draft` 或 `<uuid>-1.2`，在角色列表中都会被拒绝。
* `characterSessionId` 用于恢复该成员此前的历史记录。它在角色列表中必须唯一。
* `client.characterId` 和 `client.characterSessionId` 分别对应 `characters[0]`.
* `sharedSessionKey` 将请求归入同一个房间：匹配的创建请求会复用现有房间。

### 区分成员

`client.characters` （以及 `client.state.characters` ，在 React 中）按顺序列出角色列表。单角色会话中该列表为空，因此可以通过检查其长度来区分这两种情况。每个条目都是一个 `ConvaiCharacterInstance` ，包含其 `membershipId`, `characterId`, `displayName` （运行时发送该字段时）及其状态。

成员产生的所有内容都通过 `membershipId`进行归属，因此同一个角色的两个实例不会合并：

* 转录消息包含 `membershipId` 和 `characterId`.
* `characterAudioTrack` 用于标识每条音轨所属的成员。
* `characterReady` 会传入已就绪的成员。

#### 就绪不等于派发

`provisioningStatus` 仅描述派发状态： `dispatch_queued`, `dispatch_accepted` 或 `dispatch_failed`. `dispatch_accepted` 并不意味着已就绪。只有成员收到自己的就绪信号后才可使用，该信号会将 `isReady` 设为 `true` 并触发 `characterReady`.

```ts
client.on('characterReady', (member) => {
  console.log('ready', member?.membershipId);
});

client.on('characterStatus', ({ membershipId, status, failureCode }) => {
  if (status === 'failed') console.warn(membershipId, failureCode);
});
```

`characterStatus` 会报告运行时添加的成员，以及后台调度失败的成员。不要仅凭 `ready` 状态就启用交互；应等待 `characterReady`.

#### 播放每个成员的音频

内置组件会渲染一份共享转录文本，并为每条消息标注发送者，同时播放每个成员的音频。若要为每个角色单独设置面板，请自行绑定音频，使用 `characterAudioTrack`。在群组房间中，该事件始终会标明所属成员；无法归属到成员的音轨会被丢弃。

```ts
client.on('characterAudioTrack', ({ membershipId, track }) => {
  const el = document.querySelector<HTMLAudioElement>(`audio[data-member="${membershipId}"]`);
  if (el) el.srcObject = new MediaStream([track]);
});
```

#### 将某个成员静音

向 `membershipId` 传入 `setCharacterMuted` 以将某个成员静音，同时保持其他成员声音正常。不传此参数调用会将房间中的所有角色静音。请参阅 [将角色的语音静音](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/mute-the-characters-voice.md).

```ts
const [, second] = client.characters;
client.setCharacterMuted(true, { membershipId: second.membershipId });
client.isCharacterMuted(second.membershipId);   // true
```

### 切换回答者

只有当前激活的成员会接收用户轮次。调用 `setInteractionTarget` 并传入 `membershipId` 即可在将下一条消息发送给其他成员前切换目标。

```ts
const assessor = client.characters.find((c) => c.characterId === ASSESSOR)!;

await client.setInteractionTarget(assessor.membershipId);
client.sendUserTextMessage('Now grade my answer.');
```

通过 `activeCharacterChange` 事件而不是你自己的调用来渲染当前激活的成员，因为房间中的其他参与者也可以切换目标。

```ts
client.on('activeCharacterChange', ({ previous, active, routeEpoch }) => {
  console.log('now talking to', active, 'at epoch', routeEpoch);
});
```

* `setInteractionTarget(null)` 会关闭所有通道。再次设置目标前，没有任何成员会听到用户的声音。
* 如果目标尚未就绪，系统会在发送命令前拒绝该请求。
* 如果另一位参与者先切换了，通话会根据服务器当前状态重试一次。

### 实时添加和移除成员

`updateCharacterRoster` 用于更改已连接房间的成员列表。 `remove` 接收的是成员 ID，而不是角色 ID。

```ts
await client.updateCharacterRoster({
  add: [{ characterId: NARRATOR }],
  remove: [someMembershipId],
});
```

* 移除当前活动成员时，需要有一位已准备就绪且仍留在房间中的成员作为替代者。如果不传入 `replacementTarget`.
* 新成员必须各自发送就绪信号后，才能向其发送消息。请监听 `characterReady`.
* 房间不能为空。
* 如果另一位参与者先更改了成员列表，此调用会因冲突而被拒绝，需要你自行协调。调用不会重试。
* `rosterChange` 事件会在更改后触发，并包含新增和移除的成员以及更改后的成员列表。

{% hint style="info" %}
确认消息丢失并不意味着操作失败。如果服务器的确认消息丢失，promise 会以结果未知为由拒绝。发送可能冲突的命令之前，请读取 `client.roomSession` 以查看实际发生的情况。
{% endhint %}

### 让其他人加入

第二个人可以通过 `roomSessionId` 或 `sharedSessionKey`加入第一个人创建的房间。加入时不会发送成员列表：成员列表由服务器管理，加入操作不会添加、移除或修复任何角色。

```typescript
const second = new ConvaiClient({ apiKey: 'YOUR_API_KEY' });

await second.joinRoom({
  roomSessionId: 'the-room-session-id',   // or: sharedSessionKey: 'match-7-party-a'
  endUserId: 'player-99',
});

console.log(second.characters.length);   // the existing roster
```

* 只传入一个定位参数。 `roomSessionId` 优先使用。
* `endUserId` 为必填项。
* 容量按不同的 `endUserId` 计数，默认值为 1。创建房间时设置 `maxNumParticipants` ，否则加入操作会因以下错误而失败： `409 Human room capacity reached`。同一用户重新连接不会占用额外名额。

### 限制

* **仅支持实时传输。** 成员列表房间不支持 WebSocket 或 SSE 传输。请参阅 [选择传输方式](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/choose-a-transport.md).
* **不支持操作协议 v2 或客户端工具。** `capabilities.actionProtocolVersion: 2` （或 `modelOutputVersion: 2`）需要单角色房间，因此 `actionConfig.tools` 也不可用。版本 1 可以使用。SDK 会在发送请求前拒绝这种组合。
* **`resetSession()` 会抛出异常** ，因为在多角色房间中，每个成员的会话都由服务器管理。
* **如果复用 `sharedSessionKey`** 时使用了不同的有序角色名单、创建者或容量，请求将失败并返回 `ROSTER_FINGERPRINT_MISMATCH`。即使角色相同，只要顺序不同也会被视为不同的名单，因为这会改变初始成员。
* **房间创建重试。** 当相同的请求仍在创建房间时，SDK 会采用有上限的退避策略进行重试。传入 `rosterProvisioningRetry: false` 可自行处理 `ROSTER_PROVISIONING_IN_PROGRESS` 。

### 错误

在多角色房间中， `connect()` 和 `joinRoom()` 会抛出 `ConvaiRoomError` ，当房间无法创建或加入时。该错误包含 `status`, `code`, `requestTraceId`, `detail` 和 `isRetryable`。请提供 `requestTraceId` ，以便联系支持人员时使用。

| 代码                                      | 状态  | 含义                                        |
| --------------------------------------- | --- | ----------------------------------------- |
| `MULTI_CHARACTER_V0_DISABLED`           | 403 | 您的账户未启用多角色房间。                             |
| `MULTI_CHARACTER_ROSTER_LIMIT_EXCEEDED` | 403 | 角色名单超出了您的账户允许的数量。                         |
| `CHARACTER_NOT_FOUND_OR_INACCESSIBLE`   | 404 | 角色名单中包含您无法使用的角色。                          |
| `ROSTER_FINGERPRINT_MISMATCH`           | 409 | 复用 `sharedSessionKey` 时使用了不同的角色名单、创建者或容量。 |
| `ROSTER_PROVISIONING_IN_PROGRESS`       | 409 | 房间仍在创建中。系统会自动重试。                          |
| `Human room capacity reached`           | 409 | 房间中的人数已达到 `maxNumParticipants` 。          |

### API 参考

| 属性 / 方法                              | 类型                                                                          | 说明                                                                                                                              |
| ------------------------------------ | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `characters` （配置项）                   | `ConvaiCharacterSpec[]`                                                     | 有序角色列表，传入此项而不是 `characterId`。每个条目都是 `{ characterId, characterSessionId? }`.                                                     |
| `sharedSessionKey` （配置项）             | `string`                                                                    | 将多个请求归入同一个房间；也可作为加入房间的定位符。                                                                                                      |
| `connectAttemptId` （配置项）             | `string`                                                                    | 单次逻辑连接的幂等键。仅在重试完全相同的请求时复用。                                                                                                      |
| `maxNumParticipants` （配置项）           | `number`                                                                    | 房间内不同用户的最大数量。角色不计入其中。默认值为 1。                                                                                                    |
| `rosterProvisioningRetry` （配置项）      | `{ attempts?, initialDelayMs? } \| false`                                   | 在房间配置期间重试。默认尝试四次，初始延迟为 500 毫秒。                                                                                                  |
| `characters`                         | `ConvaiCharacterInstance[]`                                                 | 按顺序排列的角色列表。在单角色会话中为空。也位于 `state`.                                                                                               |
| `activeMembershipId`                 | `string \| null`                                                            | 当前接收用户轮次的成员。也位于 `state`.                                                                                                        |
| `roomSession`                        | `ConvaiRoomSession \| null`                                                 | 由服务器管理的房间快照： `roomSessionId`, `activeMembershipId`, `routeEpoch`, `rosterEpoch`, `partialDispatch`, `characters`。在单角色会话中为 null。 |
| `setInteractionTarget(membershipId)` | `(membershipId: string \| null) => Promise<ActiveCharacterChange>`          | 将后续用户轮次路由到另一位成员。 `null` 会关闭所有闸门。                                                                                                |
| `updateCharacterRoster(options)`     | `(options: UpdateCharacterRosterOptions) => Promise<CharacterRosterChange>` | 添加成员（`add`），按成员 ID 移除成员（`remove`），并可选择指定一个 `replacementTarget`.                                                                 |
| `joinRoom(options)`                  | `(options: JoinRoomOptions) => Promise<void>`                               | 通过以下方式加入现有房间： `roomSessionId` 或 `sharedSessionKey`，并且必须提供 `endUserId`.                                                          |
| `appendMessage(message)`             | `(message: AppendMessageOptions) => ChatMessage`                            | 在本地插入一条转录内容，而不发送它。传入 `membershipId` 可将其归属到某个成员。                                                                                 |
| `setCharacterMuted(muted, options?)` | `(muted: boolean, options?: { membershipId?: string }) => void`             | 静音所有角色，或指定成员。                                                                                                                   |
| `isCharacterMuted(membershipId?)`    | `(membershipId?: string) => boolean`                                        | 房间级设置，或某个成员的生效设置。                                                                                                               |
| `characterReady` （事件）                | `(instance: ConvaiCharacterInstance \| undefined) => void`                  | 成员已发送就绪信号。                                                                                                                      |
| `characterStatus` （事件）               | `(status: CharacterStatusEvent) => void`                                    | 成员处于 `starting`, `ready` 或 `failed`，失败时还会包含 `failureCode` 。                                                                     |
| `activeCharacterChange` （事件）         | `(change: ActiveCharacterChange) => void`                                   | 活动成员已更改： `previous`, `active`, `routeEpoch`.                                                                                    |
| `rosterChange` （事件）                  | `(change: CharacterRosterChange) => void`                                   | 成员名单已更改： `added`, `removed`, `characters`, `activeMembershipId`.                                                                |
| `characterAudioTrack` （事件）           | `(event: CharacterAudioTrackEvent) => void`                                 | 具有以下内容的音轨： `membershipId` 和 `characterId` 这两个属性用于标识其所属对象。                                                                       |

如需查看完整的事件列表，请参阅 [事件参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/multi-character-rooms.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
