> 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/raw-messages.md).

# 读取原始传输消息

使用带类型的 rawMessage 事件观察会话通过任意传输接收的每条消息，包括 MCP 工具生命周期帧和未知类型。

观察 Convai 会话收到的消息，这些消息已从线上数据解码，但尚未经过 SDK 解析。使用 `rawMessage` 事件记录流量、读取 MCP 工具生命周期帧，或处理 SDK 不会转换为自身事件的消息类型。它在 LiveKit、WebSocket 和 SSE 上的工作方式相同。

### 前提条件

* 已安装 Convai Web SDK，并且有一个可连接的客户端。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).

### 订阅原始消息

调用 `client.on('rawMessage', listener)`。它会返回一个取消订阅函数。React hook 也通过其 `on` 和 `off` 方法提供相同的监听器。

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

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

const config = {
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  startWithAudioOn: false,
};

export default function Chat() {
  const client = useConvaiClient(config);

  useEffect(() => client.on('rawMessage', (event) => {
    console.log(event.transport, event.message);
    if (event.transport === 'sse') console.log(event.request.logicalTurnIds);
  }), [client.on]);

  return <ConvaiWidget convaiClient={client} />;
}
```

{% endcode %}

像上面的示例一样，从 effect 中返回取消订阅函数，以便在组件卸载或重新渲染时移除监听器。
{% endtab %}

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

```typescript
import { ConvaiClient } from '@convai/web-sdk/core';
import { createConvaiWidget } from '@convai/web-widget/vanilla';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  startWithAudioOn: false,
});

const unsubscribe = client.on('rawMessage', (event) => {
  console.log(event.transport, event.message);
});

createConvaiWidget(document.body, { convaiClient: client });

// 当宿主视图被释放时：
// unsubscribe();
```

{% endcode %}

也可以使用 `client.off('rawMessage', listener)`移除监听器，传入同一个函数引用即可。
{% endtab %}
{% endtabs %}

订阅不会建立连接或发送任何内容。连接由小组件或你自己调用 `connect()`控制。监听器仅处理入站消息；它不会发布事件，也不会观察出站流量。

### 读取事件载荷

每个事件都包含 `message`, `byteLength` 和 `transport`。其余字段取决于传输方式，因此请先检查 `event.transport` ，TypeScript 会自动为你缩窄类型。

| 传输方式          | `message`                                                  | 额外字段                                               |
| ------------- | ---------------------------------------------------------- | -------------------------------------------------- |
| `'livekit'`   | 解码后的 JSON 信封，其中包含嵌套的 `server-message` 数据。不会发出非 JSON 数据包。   | `participant`：由房间提供的发送方信息。该字段可能不存在。                |
| `'websocket'` | 解码后的 JSON 信封，其中包含嵌套的 `server-message` 数据。不会发出非 JSON 数据包。   | 无                                                  |
| `'sse'`       | `{ type: eventName, data: decodedData }`。非 JSON 数据会保留为字符串。 | `request`：来源请求的 `logicalTurnIds` 和 `messageTypes`. |

* `message` 为 `unknown`。使用前请先验证其结构。
* `message` 以及 SSE 请求元数据与 SDK 自身的处理过程相互独立。请将它们视为只读数据。
* `byteLength` 表示传入负载的大小。对于 SSE，它统计合并后的 data 字段，不包括事件帧封装。
* 对于 SSE，session、done、error 和 unknown 帧都会计入。SSE 注释以及不含 data 的帧则不会计入。
* SSE 会在 SDK 将文本帧批量处理为聊天消息之前，逐个报告这些帧。

#### 检查消息的来源

对于 LiveKit，请将发送方 `event.participant` 与当前房间中的参与者进行验证。它是原始参与者对象，而不是副本。

对于 SSE，请使用 `event.request.logicalTurnIds` 将帧与触发它的用户轮次相匹配。仅包含控制信息的请求可能会返回空列表。请求中断时，不会发送该请求剩余的帧。

### 读取 MCP 工具生命周期帧

与工具调用（包括 MCP 工具）相关的消息，会像其他帧一样通过 `rawMessage` 传入，同时也会包含 SDK 不会解析的事件类型。读取 `type` 字段 `message` 以筛选出所需帧，例如 `llm-function-call-in-progress` 和 `llm-function-call-stopped`，或 `server-message` 中 `data.type` 为 `mcp-tool-heartbeat`.

{% code title="src/tools.ts" %}

```typescript
client.on('rawMessage', ({ message }) => {
  const frame = message as { type?: string; data?: { type?: string; tool_call_id?: string } };
  if (frame.type === 'llm-function-call-in-progress') showToolSpinner(frame.data?.tool_call_id);
  if (frame.type === 'llm-function-call-stopped') hideToolSpinner(frame.data?.tool_call_id);
});
```

{% endcode %}

### 何时使用 rawMessage

请使用 SDK 的常规事件，这些事件列于 [Web SDK 事件参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md)，适用于它们已涵盖的内容。对于 `rawMessage` ，则用于处理它们未涵盖的内容：调试和记录流量、工具与 MCP 生命周期帧、SDK 不会解析的服务器消息类型，以及 SSE 上的逐请求关联信息。

{% hint style="warning" %}
原始消息是一种观测结果，并不能证明某项操作已成功。在 SSE 上，服务器可能会发送冲突的终止帧，随后 SDK 会拒绝该帧。要确认一轮交互已完成，请使用 `botTurnCompleted` 事件。
{% endhint %}

监听器中抛出的异常不会阻止 SDK 正常处理消息。

### API 参考

| 属性 / 方法                              | 类型                                                                       | 说明                                                |
| ------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------- |
| `client.on('rawMessage', listener)`  | `(listener: (event: RawMessageEvent) => void) => () => void`             | 订阅传入消息。返回一个取消订阅函数。                                |
| `client.off('rawMessage', listener)` | `void`                                                                   | 通过引用移除同一个监听器。                                     |
| `RawMessageEvent`                    | 联合类型                                                                     | 事件负载。可根据 `transport`.                             |
| `event.message`                      | `unknown`                                                                | 已解码的线路消息，尚未经过 SDK 解析。使用前请验证其结构。                   |
| `event.byteLength`                   | `number`                                                                 | 传入负载的大小。对于 SSE，指拼接后的 data 字段，不包含事件帧。              |
| `event.transport`                    | `'livekit' \| 'websocket' \| 'sse'`                                      | 传递该消息的传输方式。                                       |
| `event.participant`                  | `unknown`                                                                | 仅适用于 LiveKit。由房间提供的发送者；可能不存在。                     |
| `event.request`                      | `SSERequestContext`                                                      | 仅适用于 SSE。发起请求的 `logicalTurnIds` 和 `messageTypes`. |
| `SSERequestContext`                  | `{ transport: 'sse'; logicalTurnIds: string[]; messageTypes: string[] }` | 生成该事件的 SSE 请求的标识信息。                               |


---

# 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/raw-messages.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.
