> 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/convai-pixel-streaming-embed/api-reference.md).

# Pixel Streaming Embed API 参考

React 组件、无框架客户端、它们的选项和方法、它们报告的事件以及它们显示的错误的参考文档。

`@convai/experience-embed` 导出一个 React 组件， `PixelStreamComponent`以及一个不依赖框架的类， `PixelStreamClient`。两者都会在 iframe 中渲染 Convai Pixel Streaming 体验，并接受相同的选项；本页注明的差异除外。

### 入口点

| 导入                                                | 格式               | 导出内容                                                                                                                                 |
| ------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `@convai/experience-embed`                        | ES 模块            | `PixelStreamComponent`, `getPixelStream`以及以下类型： `PixelStreamComponentProps`, `PixelStreamComponentHandles`, `EndUserId`和 `ChatStyle` |
| `@convai/experience-embed/core`                   | UMD， `require` 仅 | `PixelStreamClient`以及以下类型： `PixelStreamOptions`, `EndUserId`和 `ChatStyle`                                                            |
| `dist/core/convai-embed.umd.js` 由 `<script>` 标签加载 | UMD              | 全局对象 `PixelStreamCore`，其 `PixelStreamClient` 属性是该类                                                                                   |

UMD 文件是独立的。ES 模块会从你的应用中导入 `react` 。该软件包将 `react` 和 `react-dom` `^18.3.1` 声明为依赖项。

### PixelStreamComponent 属性

| 属性                       | 类型                                                    | 默认值               | 说明                                                                                                                                      |
| ------------------------ | ----------------------------------------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `expId`                  | `string`                                              | 必填                | 已发布体验的 ID。                                                                                                                              |
| `authToken`              | `string`                                              | 无                 | 由您的服务器签发的 Convai 身份验证令牌。设置后，它会授权会话，而非通过页面域名进行授权。更改此值会启动一个新会话。                                                                           |
| `endUserId`              | `string`                                              | 无                 | 您为使用此体验的用户设置的标识符。创建会话时会发送此标识符，并将其绑定到该会话。更改此值会启动一个新会话。空值或仅包含空白字符的值不会包含在会话请求中。                                                            |
| `endUserMetadata`        | `Record<string, any>`                                 | 无                 | 关于最终用户的其他信息，会随 `endUserId`一起发送到流页面。仅当 `endUserId` 已设置时才允许使用。                                                                            |
| `InitialScreen`          | `React.ReactNode`                                     | 一个 **点击以开始体验** 屏幕 | 在体验开始前显示。点击自定义屏幕不会启动体验；请调用 `initializeExperience()`.                                                                                    |
| `LoadingScreenComponent` | `React.ReactNode`                                     | 无                 | 显示在 iframe 上方，直到流页面报告已完成加载。                                                                                                             |
| `chatStyle`              | `ChatStyle`                                           | 无                 | 内置聊天窗口的外观。体验运行期间也会应用更改。                                                                                                                 |
| `serviceUrls`            | `{ sessionFetch?: string; pixelStreamBase?: string }` | Convai 的服务        | 自托管服务 URL。请参阅 [配置本地部署](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/on-premise-deployment.md). |
| `avatarStudio`           | `boolean`                                             | 无                 | 当 `true`时，请求 `vhh_character_creator` 会话模式。                                                                                              |
| `ref`                    | `React.Ref<PixelStreamComponentHandles>`              | 无                 | 接收下一节中列出的方法。                                                                                                                            |

该组件也会将 [回调](#callbacks) 中的所有回调作为属性接收。组件会填满其父元素，因此请为父元素设置宽度和高度。

### PixelStreamComponentHandles

组件的 `ref`上可用的方法。在流页面加载完成前调用方法不会发送任何内容：

| 方法                                        | 返回                 | 说明                                                            |
| ----------------------------------------- | ------------------ | ------------------------------------------------------------- |
| `initializeExperience()`                  | `void`             | 将初始屏幕替换为体验界面。                                                 |
| `sendMessageToCharacter(message: string)` | `void`             | 向角色发送文本消息。                                                    |
| `beginVoiceInteraction()`                 | `void`             | 向体验发送开始语音输入的信号。                                               |
| `endVoiceInteraction()`                   | `void`             | 向体验发送停止语音输入的信号。在免提体验中，角色会持续听取用户的声音；请使用 `muteMicrophone()` 代替。 |
| `muteMicrophone()`                        | `void`             | 在对话继续进行时将用户的麦克风静音。流重新连接后仍会保持静音状态。 `onMicStatus` 会在该操作生效时报告。   |
| `unmuteMicrophone()`                      | `void`             | 取消将用户的麦克风静音。                                                  |
| `enableCamera()`                          | `Promise<boolean>` | 打开用户的网络摄像头。当流页面报告摄像头状态时，Promise 会兑现： `true` 表示摄像头已开启。         |
| `disableCamera()`                         | `Promise<boolean>` | 关闭用户的网络摄像头。当流页面报告 `true` 表示摄像头已关闭时，Promise 会兑现。               |
| `enableCharacterAudio()`                  | `void`             | 取消将角色音频静音。                                                    |
| `disableCharacterAudio()`                 | `void`             | 将角色音频静音。                                                      |
| `setChatStyle(style: ChatStyle)`          | `void`             | 更改聊天外观。建议优先使用 `chatStyle` 属性。                                 |

当体验显示其内置聊天窗口，且你尚未调用 `muteMicrophone()` 或 `unmuteMicrophone()`时，麦克风默认处于静音状态。

### PixelStreamClient 选项

```ts
new PixelStreamClient(options: PixelStreamOptions)
```

构造函数会请求会话，并将内容渲染到 `container` 中，无需进一步调用。

| 选项                       | 类型                                                    | 默认值               | 说明                                                                                                                                      |
| ------------------------ | ----------------------------------------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `container`              | `HTMLElement`                                         | 必填                | 体验内容渲染到的元素。该元素现有的内容会被替换。                                                                                                                |
| `expId`                  | `string`                                              | 必填                | 已发布体验的 ID。                                                                                                                              |
| `authToken`              | `string`                                              | 无                 | 由你的服务器签发的 Convai 身份验证令牌。设置后，该令牌将用于授权会话，而不是使用页面域名进行授权。                                                                                   |
| `endUserId`              | `string`                                              | 无                 | 你为使用该体验的用户设置的标识符；创建会话时，此标识符会与会话绑定。                                                                                                      |
| `endUserMetadata`        | `Record<string, any>`                                 | 无                 | 有关最终用户的其他详细信息。仅当 `endUserId` 已设置时才允许提供。                                                                                                 |
| `InitialScreen`          | `HTMLElement`                                         | 一个 **点击以开始体验** 屏幕 | 在体验开始前显示。点击自定义屏幕不会启动体验；请调用 `initializeExperience()`.                                                                                    |
| `LoadingScreenComponent` | `HTMLElement`                                         | 无                 | 显示在 iframe 上方，直到流页面报告已完成加载。                                                                                                             |
| `chatStyle`              | `ChatStyle`                                           | 无                 | 内置聊天窗口的初始外观。                                                                                                                            |
| `serviceUrls`            | `{ sessionFetch?: string; pixelStreamBase?: string }` | Convai 的服务        | 自托管服务 URL。请参阅 [配置本地部署](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/on-premise-deployment.md). |
| `avatarStudio`           | `boolean`                                             | 无                 | 当 `true`时，请求 `vhh_character_creator` 会话模式。                                                                                              |

`PixelStreamClient` 也接受 [回调](#callbacks) 中的所有回调作为选项。

### PixelStreamClient 方法

`PixelStreamClient` 具有 `PixelStreamComponentHandles`中的方法，但有以下差异：

| 方法                                                  | 差异                                                                     |
| --------------------------------------------------- | ---------------------------------------------------------------------- |
| `enableCharacterAudio()`, `disableCharacterAudio()` | 返回值 `Promise<boolean>`，在消息发送后解析为 `true` 。                              |
| `setChatStyle(style: ChatStyle)`                    | 将 `style` 合并到当前样式中，因此未指定的字段会保留原值。可在体验加载前调用。                            |
| `destroy()`                                         | 仅适用于 `PixelStreamClient`。停止监听来自流页面的消息。它不会移除 iframe；请自行清除 `container` 。 |

### 回调

流页面发布匹配的消息时，会触发相应的回调。回调中抛出的错误会记录到控制台，但不会导致嵌入内容停止运行：

| 回调                   | 触发时机                                                                    | 载荷                                                                                              |
| -------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `onIframeLoaded`     | 流页面已加载。每个会话触发一次。                                                        | `时显示为灰色。`                                                                                       |
| `onCharacterMessage` | 用户或角色说话。角色的回复会分段到达。                                                     | 来自体验的消息对象，包含 `message`（文本）； `player`, `为` true `endofmessage`, `为` （回复的最后一段）；以及 `sentenceready` |
| `onAfk`              | 流断开连接。                                                                  | `'Disconnected'`                                                                                |
| `onCameraStatus`     | 摄像头开启或关闭。                                                               | `boolean`                                                                                       |
| `onCameraStream`     | 体验开始或停止摄像头流。                                                            | `boolean`                                                                                       |
| `onUserUpdated`      | 体验更新用户详细信息。                                                             | `时显示为灰色。`                                                                                       |
| `onConfigChanged`    | 体验更改其配置。                                                                | `时显示为灰色。`                                                                                       |
| `onMicStatus`        | 流页面会应用 `muteMicrophone()` 或 `unmuteMicrophone()`、用户点击内置聊天中的麦克风按钮，或流连接时。 | `{ muted: boolean }`                                                                            |

### ChatStyle

| 字段                  | 类型       | 默认值   | 说明                                                 |
| ------------------- | -------- | ----- | -------------------------------------------------- |
| `backgroundOpacity` | `number` | `0.7` | 聊天文本背板的不透明度，范围从 `0`（完全透明）到 `1`。输入框和麦克风按钮也会按相同比例缩放。 |

超出 `0` 到 `1` 范围的值会被限制在该范围内，非数字值则会被忽略。

### getPixelStream

```ts
getPixelStream(options: {
  exp_id: string
  exp_base?: string
  avatarStudio?: boolean
  end_user_id?: string
  auth_token?: string
}): Promise<{ loading: boolean; data: { session: { session_id: string } } | null; error: string | null }>
```

会话请求由 `PixelStreamComponent` 在渲染 iframe 前发起。请求会发送到 `POST <exp_base>/xp/streams/viewPublishedExperience`，其中 `exp_base` 默认为 `https://api.convai.com`，并将 `auth_token` 放在 `API-AUTH-TOKEN` 请求头中。该函数不会抛出异常：失败信息会通过 `error`.

### 错误

返回。会话请求失败时，嵌入内容会显示错误页面，而不是体验内容：

| 条件                                       | 错误页面上的提示                                                                           |
| ---------------------------------------- | ---------------------------------------------------------------------------------- |
| 未设置 `authToken`，且请求失败                    | `Please contact convai to get <origin> whitelisted!`                               |
| `已设置 authToken` ，且 Convai 的错误信息提到了身份验证令牌 | `This experience couldn't start: the Convai auth token is invalid or has expired.` |
| `已设置 authToken` ，且请求因其他原因失败              | `This experience couldn't start. Please try again later.`                          |

### 相关参考

{% content-ref url="/pages/160b67ed81203fc1670d38b8323bb9e39264f2cb" %}
[发布并授权体验](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/whitelisting-and-publishing-an-experience.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/convai-pixel-streaming-embed/api-reference.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.
