> 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` 类， `createConvaiWidget`, `destroyConvaiWidget`， `VanillaWidget` 和 `VanillaWidgetOptions` 类型，以及所有核心类型。                                                                                                               |
| `@convai/web-sdk/vanilla/websocket` | 导入时注册 WebSocket 传输，并导出 `WebSocketSession`.                                                                                                                                                                                                               |
| `@convai/web-sdk/react`             | `useConvaiClient`, `ConvaiWidget`, `useCharacterInfo`, `useLocalCameraTrack`, `ConvaiClient`, `AudioRenderer` 和 `AudioContext` （LiveKit 的别名 `RoomAudioRenderer` 和 `RoomContext`），以及所有核心类型。                                                               |
| `@convai/web-sdk/lipsync-helpers`   | 通道顺序表、映射器、队列工厂和口型同步处理器。参见 [Blendshape 通道顺序参考](/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` 是两个不同的对象，但名称相同：第一个是你用 room 构造的类，第二个是一个 React 组件。

### ConvaiConfig

传递给 `new ConvaiClient(config)`, `connect(config)`，或 `useConvaiClient(config)`。仅需 `characterId` 和一个凭证。

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

#### blendshapeConfig

| 字段                       | 类型                                                  | 默认值                               | 描述                                                     |
| ------------------------ | --------------------------------------------------- | --------------------------------- | ------------------------------------------------------ |
| `格式`                     | `"arkit" \| "mha"`                                  | `"mha"`                           | `"mha"` 发送 251 个 MetaHuman 通道； `"arkit"` 发送 61 个值。     |
| `customMapper`           | `(input: number[] \| Float32Array) => Float32Array` | 无                                 | 在每一帧进入时应用到 `blendshapeQueue`.                          |
| `frames_buffer_duration` | `数值`                                                | `0.1`                             | Convai 在与音频一起释放这些表情前缓存的表情帧秒数。                          |
| `deliver_chunks_ahead`   | `布尔值`                                               | `true` 当 `enableLipsync` 为 `true` | 允许 Convai 在音频之前发送带索引的帧块。设置 `false` 以启用分时传递路径。          |
| `output_fps`             | `数值`                                                | `60`                              | 提前交付时间线的帧率。以下情况会被忽略： `deliver_chunks_ahead` 为 `false`. |

#### emotionConfig

| 字段                         | 类型                  | 默认值     | 描述                                   |
| -------------------------- | ------------------- | ------- | ------------------------------------ |
| `provider`                 | `"llm" \| "nrclex"` | `"llm"` | `"llm"` 从回复中推断情绪； `"nrclex"` 使用词级词典。 |
| `min_word_threshold`       | `数值`                | `3`     | `"nrclex"` 仅适用。检测所需的最小词数。            |
| `low_intensity_threshold`  | `数值`                | `0.33`  | `"nrclex"` 仅适用。低强度阈值，范围 0 到 1。       |
| `high_intensity_threshold` | `数值`                | `0.66`  | `"nrclex"` 仅适用。高强度阈值，范围 0 到 1。       |

#### actionConfig

| 字段                         | 类型                                             | 描述                                                             |
| -------------------------- | ---------------------------------------------- | -------------------------------------------------------------- |
| `actions`                  | `string[]`                                     | 角色可以执行的动作名称。                                                   |
| `characters`               | `Array<{ name: string; bio: string }>`         | 场景中的其他角色。                                                      |
| `objects`                  | `Array<{ name: string; description: string }>` | 场景中的对象。                                                        |
| `current_attention_object` | `字符串`                                          | 可选。角色关注的对象。必须匹配 `objects[].name`.                              |
| `tools`                    | `ClientToolDeclaration[]`                      | 可选。客户端执行的工具，每个都具有 `名称`, `描述`，以及 `inputSchema`。仅与动作协议版本 2 一起使用。 |

参见 [处理角色动作](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/actions.md).

#### capabilities

| 字段                      | 类型                  | 当省略时              |
| ----------------------- | ------------------- | ----------------- |
| `actionProtocolVersion` | `1 \| 2`            | 动作协议版本 1。         |
| `modelOutputVersion`    | `1 \| 2`            | 旧版输出消息。           |
| `botLlmTextMode`        | `"legacy" \| "raw"` | 在 `bot-llm-text`. |

上过滤的文本。当请求版本 2 或 `"raw"` 选择时， `connect()` 如果 Convai 未确认它则会抛出异常；如果 Convai 在未请求的情况下选择它，也会抛出异常。

#### visionInputConfig

| 字段                             | 类型                                             | 作为以下内容发送：                                                                 |
| ------------------------------ | ---------------------------------------------- | ------------------------------------------------------------------------- |
| `已启用`                          | `布尔值`                                          | `已启用`。默认为 `true` 当 `enableVideo` 为 `true`；设置 `false` 以在没有视觉上下文的情况下保留视频通道。 |
| `sampleIntervalSecs`           | `数值`                                           | `sample_interval_secs`                                                    |
| `framesPerTurn`                | `数值`                                           | `frames_per_turn`                                                         |
| `bufferFrames`                 | `数值`                                           | `buffer_frames`                                                           |
| `samplingWindows`              | `Array<{ count: number; intervalMs: number }>` | `sampling_windows`                                                        |
| `stalenessSeconds`             | `数值`                                           | `staleness_seconds`                                                       |
| `maxResolution`                | `数值 \| null`                                   | `max_resolution`                                                          |
| `replacePreviousVisionContext` | `布尔值`                                          | `replace_previous_vision_context`                                         |

#### respondModes

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

| 字段              | 类型               |
| --------------- | ---------------- |
| `文本`            | `"must_respond"` |
| `音频`            | `"must_respond"` |
| `视觉`            | `RespondMode`    |
| `contextUpdate` | `RespondMode`    |
| `触发器`           | `RespondMode`    |
| `sceneMetadata` | `RespondMode`    |

### ConvaiClientState

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

| 字段                 | 类型                                                                         | 描述                                                                                                   |
| ------------------ | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `isConnected`      | `布尔值`                                                                      | 已连接到 Convai。                                                                                         |
| `isConnecting`     | `布尔值`                                                                      | 正在进行连接尝试。                                                                                            |
| `isListening`      | `布尔值`                                                                      | 用户正在说话。                                                                                              |
| `isThinking`       | `布尔值`                                                                      | 角色正在生成回复。                                                                                            |
| `isSpeaking`       | `布尔值`                                                                      | 角色正在说话。                                                                                              |
| `agentState`       | `'disconnected' \| 'connected' \| 'listening' \| 'thinking' \| 'speaking'` | 组合活动。 `'disconnected'` 未连接时；否则 `'speaking'`，然后 `'listening'`，然后 `'thinking'`，然后 `'connected'`，按该优先级。 |
| `emotion`          | `{ emotion: string; scale?: number } \| null`                              | 收到的最后一个情绪。                                                                                           |
| `endUserId`        | `字符串 \| null`                                                              | 连接时由 Convai 返回的终端用户 ID。                                                                              |
| `endUserMetadata`  | `Record<string, unknown> \| null`                                          | 连接时由 Convai 返回的终端用户元数据。                                                                              |
| `metrics`          | `ConvaiMetrics[]`                                                          | 本会话接收到的指标事件，每个都包含 `id`, `data`，以及 `timestamp`.                                                       |
| `disconnectReason` | `DisconnectReason \| null`                                                 | 最后一次断开连接的原因，或 `null`.                                                                                |

### ChatMessage

| 字段              | 类型    | 描述                         |
| --------------- | ----- | -------------------------- |
| `id`            | `字符串` | 消息 ID。                     |
| `type`          | 见下文   | 消息类型。                      |
| `content`       | `字符串` | 消息文本。                      |
| `timestamp`     | `字符串` | ISO 8601 创建时间。             |
| `isStreaming`   | `布尔值` | 可选。 `true` 当消息仍在追加时。       |
| `logicalTurnId` | `字符串` | 可选。模型输出版本 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'` 适用于任何其他代码。

| Code | Key                   | `getDisconnectReasonMessage`  |
| ---- | --------------------- | ----------------------------- |
| `0`  | `UNKNOWN_REASON`      | `网络不可用或原因未知`                  |
| `1`  | `CLIENT_INITIATED`    | `用户已断开连接`                     |
| `2`  | `DUPLICATE_IDENTITY`  | `另一个具有相同身份的客户端已加入`            |
| `3`  | `SERVER_SHUTDOWN`     | `服务器正在关闭`                     |
| `4`  | `PARTICIPANT_REMOVED` | `通过 RemoveParticipant API 移除` |
| `5`  | `ROOM_DELETED`        | `通过 DeleteRoom API 结束房间`      |
| `6`  | `STATE_MISMATCH`      | `状态不匹配`                       |
| `7`  | `JOIN_FAILURE`        | `加入失败`                        |
| `8`  | `MIGRATION`           | `参与者已移动到其他房间`                 |
| `9`  | `SIGNAL_CLOSE`        | `信令连接已关闭`                     |

### ServerResponse

由以下项携带： `serverResponse` 事件，用于确认客户端发送的消息。

| 字段           | 类型                                                  | 描述                                                                                  |
| ------------ | --------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `event_type` | `字符串`                                               | 正在确认的消息类型，例如 `context-update`.                                                      |
| `status`     | `'success' \| 'error' \| 'processing' \| 'pending'` | 处理状态。                                                                               |
| `message`    | `字符串 \| null`                                       | 人类可读的结果。                                                                            |
| `extras`     | `ServerResponseExtras \| null`                      | 特定于事件的数据，例如 `token_count`, `max_tokens`，以及 `remaining_tokens` 适用于 `context-update`. |

### 其他导出类型

| 领域        | 类型                                                                                                                                                                                                                                                    |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Client    | `IConvaiClient`, `AudioControls`, `VideoControls`, `ScreenShareControls`，以及 `ConvaiClientType` 来自 `@convai/web-sdk/core`                                                                                                                              |
| Messaging | `ContextUpdateOptions`, `SendUserTextMessageOptions`, `UpdateSceneMetadataOptions`, `UploadFileOptions`, `DynamicInfo`, `InteractionCreated`, `ServerResponseExtras`                                                                                  |
| 操作和模型输出   | `ConvaiAction`, `ConvaiToolCall`, `ActionResponseEvent`, `ActionResult`, `ClientToolDeclaration`, `ModelOutputMessage`, `ModelOutputItem`, `ModelOutputProtocolError`, `ProtocolCapabilitiesConfig`, `JsonValue`, `JsonObject`                        |
| Vision    | `VisionInputConfig`, `VisionStatusOptions`, `VisionTriggerOptions`, `VisionSourceState`, `VisionSourceHandle`, `PublishCanvasOptions`, `PublishVideoTrackOptions`, `RespondMode`, `RespondModality`, `RespondModesConfig`, `RespondModeUpdateOptions` |
| Memory    | `Memory`, `MemoryAddResponse`, `MemoryListResponse`, `MemoryDeleteResponse`, `MemoryDeleteAllResponse`                                                                                                                                                |
| 口型同步      | `TurnStats` 和 `BlendshapeChunkMetadata` 来自 `@convai/web-sdk/core`; `BlendshapeMapper`, `BlendshapeFormat`, `BlendshapeMappingConfig`, `BlendshapeNameMapping`，以及 `OptimizedBlendshapeOutput` 来自 `@convai/web-sdk/lipsync-helpers`                     |
| Transport | `IWebSocketSession`, `WebSocketSessionFactory`, `PublishedChatConnectOptions`                                                                                                                                                                         |

### 相关参考

{% content-ref url="/pages/f1fc7386520b3ebeeafa719a8d9efb554e1d7024" %}
[ConvaiClient 参考](/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 事件参考](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/4478f4a3cec9e37c9839b186fe7a71671f76fa3e" %}
[Blendshape 声道顺序参考](/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.
