> 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/vanilla-typescript/best-practices-and-type-definitions.md).

# 配置和类型参考

Convai Web SDK 包入口点、每个连接配置字段及其默认值，以及主要导出类型的参考。

本页列出了 `@convai/web-sdk`的入口点、 `ConvaiConfig`的所有字段，以及客户端使用的状态、消息和确认类型。这些类型定义在 SDK 的核心模块中，并从以下模块重新导出： `@convai/web-sdk/core`, `@convai/web-sdk/vanilla`和 `@convai/web-sdk/react`.

### 入口点

该包在其 `exports` 字段中声明了以下导入路径。除此之外，没有其他公共入口点。

| 导入路径                                | 导出内容                                                                                                                                                                                                                                                  |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@convai/web-sdk`                   | 导出 `@convai/web-sdk/react` 和 `@convai/web-sdk/lipsync-helpers`.                                                                                                                                                                                       |
| `@convai/web-sdk/core`              | `ConvaiClient`, `MemoryManager`, `BlendshapeQueue`, `EventEmitter`, `AudioManager`, `VideoManager`, `ScreenShareManager`, `MessageHandler`、模型输出辅助函数 `parseModelOutputMessage`, `ModelOutputExtensionRegistry`, `isJsonValue`和 `isJsonObject`以及所有核心类型。 |
| `@convai/web-sdk/vanilla`           | `ConvaiClient`、SDK 的 `AudioRenderer` 类、 `CharacterVersionManager`、错误类以及所有核心类型。原生版组件（`createConvaiWidget`, `destroyConvaiWidget`）位于 `@convai/web-widget/vanilla`.                                                                                      |
| `@convai/web-sdk/vanilla/websocket` | 导入时注册 WebSocket 传输方式，并导出 `WebSocketSession`.                                                                                                                                                                                                          |
| `@convai/web-sdk/react`             | `useConvaiClient`, `ConvaiClient`以及所有核心类型。 `ConvaiWidget`, `useCharacterInfo`, `useLocalCameraTrack`, `AudioRenderer` 和 `AudioContext` （LiveKit 的 `RoomAudioRenderer` 和 `RoomContext`）位于 `@convai/web-widget/react`.                                  |
| `@convai/web-sdk/lipsync-helpers`   | 通道顺序表、映射器、队列工厂和口型同步处理器。请参阅 [Blendshape 通道顺序参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/mappings-reference.md).                                                                         |
| `@convai/web-sdk/embed`             | 用于加载已发布聊天的辅助函数： `fetchPublishedChatDescriptor`, `requestPublishedChatGrant`, `loadPublishedChatSession`及其类型。                                                                                                                                          |

`AudioRenderer` 来自 `@convai/web-sdk/vanilla` 和 `AudioRenderer` 来自 `@convai/web-widget/react` 是两个名称相同但对象不同的实体：第一个是使用房间实例化的类，第二个是 React 组件。

`livekit-client` 是一个对等依赖，版本为 `>=2.20.1 <3`。如果你的应用直接调用 LiveKit，请注意，从 2.20 版开始， `client.room.localParticipant.publishData()` 接收 `Uint8Array<ArrayBuffer>`类型。使用当前 TypeScript 的 `new TextEncoder().encode(...)` 生成的字节已经是该类型，前提是使用当前 TypeScript 的 `lib` 文件；可能由 `Uint8Array` 支持的 `SharedArrayBuffer`，或应用自行声明的结构化 LiveKit 类型，则需要进行仅涉及类型的更改，例如 `new Uint8Array(bytes)`.

### ConvaiConfig

传入 `new ConvaiClient(config)`, `connect(config)`，或 `useConvaiClient(config)`。仅 `characterId` 和一个凭据为必填项。

| 字段                      | 类型                                  | 默认值                                             | 说明                                                                                                                                                                                    |
| ----------------------- | ----------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `characterId`           | `string`                            | 必填                                              | 要连接的角色。                                                                                                                                                                               |
| `apiKey`                | `string`                            | 无                                               | Convai API 密钥。必须提供 `apiKey` 或 `authToken` 。                                                                                                                                           |
| `authToken`             | `string`                            | 无                                               | 短期有效的身份验证令牌。两者都设置时，将优先使用此令牌而非 `apiKey` 。请参阅 [使用身份验证令牌连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md).                         |
| `url`                   | `string`                            | `https://realtime-api.convai.com`               | 实时 API 的基础 URL。客户端会向 `{url}/connect`发送 POST 请求。有关自行部署，请参阅 [连接到自托管部署](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/self-hosted-deployments.md). |
| `characterInfoUrl`      | `string`                            | `https://api.convai.com`                        | 提供 `POST /character/get`的来源； `@convai/web-widget` 聊天组件会通过该接口获取角色名称和头像。在自托管部署中请设置此项，否则查询请求和 API 密钥会发送到 `api.convai.com`.                                                               |
| `characterApiUrl`       | `string`                            | `https://api2.convai.com`                       | 供 `client.characterVersions`.                                                                                                                                                         |
| `iceTransportPolicy`    | `"relay" \| "all"`                  | `"relay"`                                       | WebRTC ICE 策略。 `"relay"` 仅使用 TURN； `"all"` 还允许直接连接，适用于未配置 TURN 的 LiveKit 服务器。                                                                                                         |
| `transport`             | `"livekit" \| "websocket" \| "sse"` | `"livekit"`，或 `"sse"` 当 `interactionApiUrl` 已设置 | 通过 LiveKit 使用 WebRTC、WebSocket 传输或 SSE 传输。请参阅 [选择传输方式](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/choose-a-transport.md).                    |
| `interactionApiUrl`     | `string`                            | 无                                               | SSE 端点。设置此项后，当 `transport` 未指定时，将选择 SSE 传输。请参阅 [通过 SSE 传输进行聊天](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/sse-transport.md).                 |
| `endUserId`             | `string`                            | 无                                               | 最终用户的稳定 ID，例如 UUID 或电子邮件地址。启用长期记忆和按用户分析。不提供时，会话为匿名会话。                                                                                                                                 |
| `endUserMetadata`       | `Record<string, unknown>`           | 无                                               | 有关最终用户的元数据，以 `end_user_metadata`.                                                                                                                                                     |
| `characterSessionId`    | `string`                            | 无                                               | 要恢复的会话。 `'-1'` 会被视为未指定会话。连接后，客户端会存储 Convai 返回的会话 ID。                                                                                                                                  |
| `enableVideo`           | `boolean`                           | `false`                                         | `true` 建立视频连接，支持摄像头、屏幕共享和视觉功能。 `false` 建立音频连接。                                                                                                                                        |
| `startWithVideoOn`      | `boolean`                           | `false`                                         | 连接时开启摄像头。仅当 `enableVideo` 为 `true`.                                                                                                                                                   |
| `startWithAudioOn`      | `boolean`                           | `false` 在 WebRTC 中                              | 连接时开启麦克风。在 WebSocket 传输中，麦克风默认开启，只有明确设置为 `false`.                                                                                                                                     |
| `ttsEnabled`            | `boolean`                           | `true`                                          | 角色的回复是否以语音播报。                                                                                                                                                                         |
| `enableLipsync`         | `boolean`                           | `false`                                         | 请求用于面部动画的混合形状帧。                                                                                                                                                                       |
| `blendshapeConfig`      | `object`                            | 请参阅 [blendshapeConfig](#blendshapeconfig)       | 混合形状帧的格式和传递方式。                                                                                                                                                                        |
| `enableEmotion`         | `boolean`                           | `false`                                         | 请求角色在回复中提供情绪信息。                                                                                                                                                                       |
| `emotionConfig`         | `object`                            | `{ provider: "llm" }`                           | 情绪检测方式。仅当 `enableEmotion` 为 `true`时发送。请参阅 [情绪配置](#emotionconfig).                                                                                                                     |
| `stateOfMind`           | `string \| null`                    | 无                                               | 连接时发送的临时心理状态。该值会先去除首尾空白，再转换为小写； `"neutral"` 或空字符串可将其清除。                                                                                                                               |
| `actionConfig`          | `object`                            | 无                                               | 角色可以执行操作的动作、场景对象和角色。请参阅 [actionConfig](#actionconfig).                                                                                                                                |
| `capabilities`          | `ProtocolCapabilitiesConfig`        | 无                                               | 可选启用的协议版本。请参阅 [capabilities](#capabilities).                                                                                                                                          |
| `dynamicInfo`           | `string`                            | 无                                               | 初始动态上下文文本。                                                                                                                                                                            |
| `keepInContext`         | `boolean`                           | 无                                               | 与 `dynamicInfo`. `true` 一同发送时，会将动态信息作为连接的固定提示保留。                                                                                                                                      |
| `narrativeTemplateKeys` | `Record<string, string>`            | 无                                               | 叙事设计模板键值；当映射非空时，会在连接时发送。                                                                                                                                                              |
| `visionInputConfig`     | `VisionInputConfig`                 | 在 `enableVideo` 为 `true`                        | 视觉帧设置。请参阅 [visionInputConfig](#visioninputconfig).                                                                                                                                    |
| `respondModes`          | `RespondModesConfig`                | 无                                               | 各模态的响应模式默认值。请参阅 [respondModes](#respondmodes).                                                                                                                                        |
| `invocationMetadata`    | `object`                            | `source: "web_sdk"`, `clientVersion`：SDK 版本     | `source`, `clientVersion`以及 `extraMetadata` 会发送用于分析的数据。                                                                                                                               |
| `debug`                 | `boolean`                           | 无                                               | 设置后，会以 `debug` 的形式发送给 Convai。                                                                                                                                                         |
| `logRtviMessages`       | `boolean`                           | `true`                                          | 将解码后的实时消息记录到浏览器控制台。设置为 `false` 以将其静音。                                                                                                                                                 |

#### blendshapeConfig

| 字段                       | 类型                                                  | 默认值                               | 说明                                                 |
| ------------------------ | --------------------------------------------------- | --------------------------------- | -------------------------------------------------- |
| `format`                 | `"arkit" \| "mha"`                                  | `"mha"`                           | `"mha"` 发送 251 个 MetaHuman 通道； `"arkit"` 发送 61 个值。 |
| `customMapper`           | `(input: number[] \| Float32Array) => Float32Array` | 无                                 | 每帧进入 `blendshapeQueue`.                            |
| `frames_buffer_duration` | `number`                                            | `0.1`                             | Convai 在随音频释放形状数据之前缓冲的秒数。                          |
| `deliver_chunks_ahead`   | `boolean`                                           | `true` 当 `enableLipsync` 为 `true` | 允许 Convai 提前发送带索引的帧块。若要使用按节奏交付的方式，请设为 `false` 。    |
| `output_fps`             | `number`                                            | `60`                              | 提前交付时间线的帧率。当 `deliver_chunks_ahead` 为 `false`.     |

#### emotionConfig

| 字段                         | 类型                  | 默认值     | 说明                                   |
| -------------------------- | ------------------- | ------- | ------------------------------------ |
| `provider`                 | `"llm" \| "nrclex"` | `"llm"` | `"llm"` 根据响应推断情绪； `"nrclex"` 使用词级词典。 |
| `min_word_threshold`       | `number`            | `3`     | `"nrclex"` 仅适用于此选项。检测所需的最低词数。        |
| `low_intensity_threshold`  | `number`            | `0.33`  | `"nrclex"` 仅适用于此选项。低强度阈值，范围为 0 到 1。  |
| `high_intensity_threshold` | `number`            | `0.66`  | `"nrclex"` 仅适用于此选项。高强度阈值，范围为 0 到 1。  |

#### actionConfig

| 字段                         | 类型                                             | 说明                                                                        |
| -------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------- |
| `actions`                  | `string[]`                                     | 角色可以执行的动作名称。                                                              |
| `characters`               | `Array<{ name: string; bio: string }>`         | 场景中的其他角色。                                                                 |
| `objects`                  | `Array<{ name: string; description: string }>` | 场景中的物体。                                                                   |
| `current_attention_object` | `string`                                       | 可选。角色关注的物体。必须与某个 `objects[].name`.                                        |
| `tools`                    | `ClientToolDeclaration[]`                      | 可选。由客户端执行的工具，每个工具包含 `name`, `description`和 `inputSchema`。仅与操作协议版本 2 搭配使用。 |

请参阅 [处理角色操作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/actions.md).

#### 功能

| 字段                      | 类型                  | 省略时                        |
| ----------------------- | ------------------- | -------------------------- |
| `actionProtocolVersion` | `1 \| 2`            | 操作协议版本 1。                  |
| `modelOutputVersion`    | `1 \| 2`            | 旧版输出消息。                    |
| `botLlmTextMode`        | `"legacy" \| "raw"` | 经过筛选的文本，位于 `bot-llm-text`. |

请求选择版本 2 或 `"raw"` 时， `connect()` 如果 Convai 未确认该选择，或者 Convai 在未收到请求的情况下选择了该项，都会抛出异常。

#### 视觉输入配置

| 字段                             | 类型                                             | 发送为                                                                             |
| ------------------------------ | ---------------------------------------------- | ------------------------------------------------------------------------------- |
| `enabled`                      | `boolean`                                      | `enabled`。默认值为 `true` 当 `enableVideo` 为 `true`时，设为 `false` 可在保留视频通道的同时不包含视觉上下文。 |
| `sampleIntervalSecs`           | `number`                                       | `sample_interval_secs`                                                          |
| `framesPerTurn`                | `number`                                       | `frames_per_turn`                                                               |
| `bufferFrames`                 | `number`                                       | `buffer_frames`                                                                 |
| `samplingWindows`              | `Array<{ count: number; intervalMs: number }>` | `sampling_windows`                                                              |
| `stalenessSeconds`             | `number`                                       | `staleness_seconds`                                                             |
| `maxResolution`                | `number \| null`                               | `max_resolution`                                                                |
| `replacePreviousVisionContext` | `boolean`                                      | `replace_previous_vision_context`                                               |

#### respondModes

`RespondMode` 是 `"must_respond"`, `"auto"`，或 `"silent"`.

| 字段              | 类型               |
| --------------- | ---------------- |
| `text`          | `"must_respond"` |
| `audio`         | `"must_respond"` |
| `vision`        | `RespondMode`    |
| `contextUpdate` | `RespondMode`    |
| `trigger`       | `RespondMode`    |
| `sceneMetadata` | `RespondMode`    |

### ConvaiClientState

由以下内容返回： `client.state` 并由以下事件携带： `stateChange` 事件。

| 字段                 | 类型                                                                         | 说明                                                                                                           |
| ------------------ | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `isConnected`      | `boolean`                                                                  | 已连接到 Convai。                                                                                                 |
| `isConnecting`     | `boolean`                                                                  | 正在尝试建立连接。                                                                                                    |
| `isListening`      | `boolean`                                                                  | 用户正在说话。                                                                                                      |
| `isThinking`       | `boolean`                                                                  | 角色正在生成回复。                                                                                                    |
| `isSpeaking`       | `boolean`                                                                  | 角色正在说话。                                                                                                      |
| `agentState`       | `'disconnected' \| 'connected' \| 'listening' \| 'thinking' \| 'speaking'` | 综合活动状态。 `'disconnected'` 未连接时；否则为 `'speaking'`，然后是 `'listening'`，然后是 `'thinking'`，然后是 `'connected'`，按此优先级排序。 |
| `emotion`          | `{ emotion: string; scale?: number } \| null`                              | 最近收到的情绪。                                                                                                     |
| `endUserId`        | `string \| null`                                                           | 连接时 Convai 返回的最终用户 ID。                                                                                       |
| `endUserMetadata`  | `Record<string, unknown> \| null`                                          | 连接时 Convai 返回的最终用户元数据。                                                                                       |
| `metrics`          | `ConvaiMetrics[]`                                                          | 本会话收到的指标事件，每个事件包含 `id`, `data`和 `timestamp`.                                                                 |
| `disconnectReason` | `DisconnectReason \| null`                                                 | 上次断开连接的原因，或 `null`.                                                                                          |

### 聊天消息

| 字段              | 类型        | 说明                         |
| --------------- | --------- | -------------------------- |
| `id`            | `string`  | 消息 ID。                     |
| `type`          | 见下文       | 消息类型。                      |
| `content`       | `string`  | 消息文本。                      |
| `timestamp`     | `string`  | ISO 8601 创建时间。             |
| `isStreaming`   | `boolean` | 可选。 `true` 消息仍在持续追加时。      |
| `logicalTurnId` | `string`  | 可选。模型输出版本 2 中关联语音转写的轮次 ID。 |

| `type`               | 含义                                |
| -------------------- | --------------------------------- |
| `user`               | 用户发送的消息。                          |
| `user-llm-text`      | 使用 `sendUserTextMessage`.         |
| `user-transcription` | 转写后的用户语音。                         |
| `convai`             | 角色的回复。                            |
| `bot-llm-text`       | 角色的回复，生成时会以流式方式传输。                |
| `bot-output`         | 角色的回复，在朗读时汇总传输。                   |
| `bot-emotion`        | 角色的情绪。                            |
| `emotion`            | 一种情绪状态。                           |
| `action`             | 角色选择执行的动作，以文本表示。                  |
| `behavior-tree`      | 行为树响应。                            |
| `interrupt-bot`      | 中断角色的响应。                          |
| `idle-warning`       | 空闲超时警告。 `content` 以数字字符串形式包含剩余秒数。 |
| `llm-no-response`    | 角色有意未作出响应。 `content` 为空。          |

### DisconnectReason

`DisconnectReasonEnum` 包含数字代码。 `getDisconnectReasonMessage(reason)` 返回下方的消息， `'Connected'` 用于 `null`，而 `'Disconnected'` 用于任何其他代码。

| 代码  | 键                     | `getDisconnectReasonMessage`               |
| --- | --------------------- | ------------------------------------------ |
| `0` | `UNKNOWN_REASON`      | `Network unavailable or unknown cause`     |
| `1` | `CLIENT_INITIATED`    | `User disconnected`                        |
| `2` | `DUPLICATE_IDENTITY`  | `Another client with same identity joined` |
| `3` | `SERVER_SHUTDOWN`     | `Server is shutting down`                  |
| `4` | `PARTICIPANT_REMOVED` | `Removed by RemoveParticipant API`         |
| `5` | `ROOM_DELETED`        | `Room ended via DeleteRoom API`            |
| `6` | `STATE_MISMATCH`      | `State mismatch`                           |
| `7` | `JOIN_FAILURE`        | `Failed to join`                           |
| `8` | `MIGRATION`           | `Participant moved to different room`      |
| `9` | `SIGNAL_CLOSE`        | `Signal connection closed`                 |

### ServerResponse

由 `serverResponse` 事件承载，用于确认客户端发送的消息。

| 字段           | 类型                                                  | 说明                                                                                 |
| ------------ | --------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `event_type` | `string`                                            | 被确认的消息类型，例如 `context-update`.                                                      |
| `status`     | `'success' \| 'error' \| 'processing' \| 'pending'` | 处理状态。                                                                              |
| `message`    | `string \| null`                                    | 人类可读的结果。                                                                           |
| `extras`     | `ServerResponseExtras \| null`                      | 特定于事件的数据，例如 `token_count`, `max_tokens`和 `remaining_tokens` （适用于 `context-update`. |

### 其他导出的类型

| 区域      | 类型                                                                                                                                                                                                                                                    |
| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 客户端     | `IConvaiClient`, `AudioControls`, `VideoControls`, `ScreenShareControls`和 `ConvaiClientType` ，来自 `@convai/web-sdk/core`                                                                                                                               |
| 消息传递    | `ContextUpdateOptions`, `SendUserTextMessageOptions`, `UpdateSceneMetadataOptions`, `UploadFileOptions`, `DynamicInfo`, `InteractionCreated`, `ServerResponseExtras`                                                                                  |
| 操作与模型输出 | `ConvaiAction`, `ConvaiToolCall`, `ActionResponseEvent`, `ActionResult`, `ClientToolDeclaration`, `ModelOutputMessage`, `ModelOutputItem`, `ModelOutputProtocolError`, `ProtocolCapabilitiesConfig`, `JsonValue`, `JsonObject`                        |
| 视觉      | `VisionInputConfig`, `VisionStatusOptions`, `VisionTriggerOptions`, `VisionSourceState`, `VisionSourceHandle`, `PublishCanvasOptions`, `PublishVideoTrackOptions`, `RespondMode`, `RespondModality`, `RespondModesConfig`, `RespondModeUpdateOptions` |
| 内存      | `Memory`, `MemoryAddResponse`, `MemoryListResponse`, `MemoryDeleteResponse`, `MemoryDeleteAllResponse`                                                                                                                                                |
| 唇形同步    | `TurnStats` 和 `BlendshapeChunkMetadata` 来自 `@convai/web-sdk/core`; `BlendshapeMapper`, `BlendshapeFormat`, `BlendshapeMappingConfig`, `BlendshapeNameMapping`，以及 `OptimizedBlendshapeOutput` 来自 `@convai/web-sdk/lipsync-helpers`                     |
| 传输      | `IWebSocketSession`, `WebSocketSessionFactory`, `PublishedChatConnectOptions`                                                                                                                                                                         |

### 相关参考

{% content-ref url="/pages/f1fc7386520b3ebeeafa719a8d9efb554e1d7024" %}
[ConvaiClient 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/convaiclient-core-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/8c6e3631e7e7da5b3c9acf5a0019d7737dc79e19" %}
[Web SDK 事件参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/4478f4a3cec9e37c9839b186fe7a71671f76fa3e" %}
[Blendshape 声道顺序参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/mappings-reference.md)
{% endcontent-ref %}


---

# 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/vanilla-typescript/best-practices-and-type-definitions.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.
