> 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/sse-transport.md).

# 通过 SSE 传输聊天

通过服务器发送事件将文本发送给 Convai 角色，将 API 密钥保留在你的服务器上，播放角色的声音，并在 Node 下运行客户端。

通过 SSE 传输与 Convai 角色聊天：发送文本，回复以文本流的形式返回，也可以选择以语音形式返回。每条消息对应一个 HTTP `POST` 请求，其响应是事件流，消息之间不会保持连接打开。SSE 传输不使用 WebRTC、房间或麦克风，因此也能在 Node 环境中运行。使用本页设置聊天、避免 API 密钥暴露在页面上、播放角色语音，或从服务器调用角色。

{% hint style="warning" %}
SSE 传输所依赖的交互 API 目前处于 Beta 阶段。可在生产环境通过以下地址访问： `https://interaction-api.convai.com/v1/interactions`；在预发布环境（`https://interaction-api-stg.convai.com/v1/interactions`）以及自托管部署中也可访问。
{% endhint %}

### 前提条件

* 已安装 Convai Web SDK。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).
* 交互 API URL：上述生产或预发布端点、自托管端点，或转发到其中一个端点的自有服务器路由。

### 连接并发送消息

提供 `interactionApiUrl` 后，如果未指定 `transport` ，就会选择 SSE 传输。你也可以显式设置 `transport: 'sse'` 。

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

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

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    interactionApiUrl: 'YOUR_INTERACTION_API_URL',
  });

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

{% endcode %}
{% endtab %}

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

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

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

client.on('characterSessionId', (id) => console.log('session', id));
client.on('messagesChange', (messages) => {
  const last = messages.at(-1);
  if (last) console.log(last.type, last.content);
});
client.on('botTurnCompleted', () => console.log('reply finished'));

await client.connect();
client.sendUserTextMessage('Say hello in exactly five words.');
```

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

以下两种配置会使 `connect()` 抛出异常：

| 配置                                          | 错误                                                           |
| ------------------------------------------- | ------------------------------------------------------------ |
| `transport: 'sse'` 但未设置 `interactionApiUrl` | `interactionApiUrl is required when using the SSE transport` |
| `transport: 'sse'` 且设置了 `enableVideo: true` | `The SSE transport supports text interactions only`          |

#### 关键行为

* **`connect()` 不会发起网络请求。** 它会将会话标记为就绪，并触发 `connect` 和 `botReady` 立即发出。发送消息时会发出第一个请求。
* **角色会话 ID 会在首次交互时返回。** 没有 `/connect` 握手，因此服务器会在第一条消息时分配 ID，客户端则会发出 `characterSessionId`。后续消息可能会再次触发此事件，且值相同，因此请将其视为幂等操作。
* **API 密钥会通过 `Authorization: Bearer …`传递，身份验证令牌则通过 `API-AUTH-TOKEN`.** 同时提供两者时，SDK 只会发送 `authToken`。在 1.9.3 及更早版本中，SDK 也会将 `authToken` 作为 Bearer 值发送，但交互 API 会拒绝此请求，并返回 `401`.
* **`botTurnCompleted` 表示回复结束。** `turnEnd` 在 SSE 上不会触发，因为它取决于角色的说话状态，而此传输方式不会报告该状态。
* **麦克风、视频、屏幕共享和口型同步在此传输方式下均不起作用。** 语音输出是个例外；请参阅 [播放角色语音](#play-the-characters-voice).

### 将 API 密钥保存在服务器路由中

浏览器代码中的 API 密钥对任何打开页面的人都可见。请将 `interactionApiUrl` 指向你自己的服务器上的路由。该路由会添加密钥、固定角色，并以不缓冲的方式流式传回响应，让文本在生成时即可到达。

{% code title="api/interactions.ts" %}

```ts
// Vercel Edge 函数；任何能够流式传输响应的服务器都可以。
export const config = { runtime: 'edge' };

export default async function handler(request: Request): Promise<Response> {
  if (request.method !== 'POST') return new Response(null, { status: 405 });
  const body = await request.json();

  const upstream = await fetch(process.env.CONVAI_INTERACTION_API_URL!, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.CONVAI_API_KEY}`,
      Accept: 'text/event-stream',
      'Content-Type': 'application/json',
    },
    // 在此固定角色，避免此路由被用于其他角色。
    body: JSON.stringify({ ...body, character_id: process.env.CONVAI_CHARACTER_ID }),
    signal: request.signal,
  });

  return new Response(upstream.body, {
    status: upstream.status,
    headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform' },
  });
}
```

{% endcode %}

在浏览器中，为密钥和角色传入占位值，因为实际值由路由提供：

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

```ts
import { ConvaiClient } from '@convai/web-sdk/core';

const client = new ConvaiClient({
  apiKey: 'proxied',
  characterId: 'proxied',
  interactionApiUrl: `${window.location.origin}/api/interactions`,
});
```

{% endcode %}

将 `CONVAI_API_KEY`, `CONVAI_CHARACTER_ID` 和 `CONVAI_INTERACTION_API_URL` 仅设置为服务器环境变量。 `VITE_` 或 `NEXT_PUBLIC_` 前缀会将它们打包到页面中。

### 播放角色的语音

默认情况下，SSE 中的语音处于关闭状态。设置 `ttsEnabled: true`后，携带回复文本的同一响应也会通过 `audioData` 事件传送语音。 `toggleTts(enabled)` 会更改下一条消息的设置。

SDK 会发出音频，但不会播放； `ConvaiWidget` 和 `createConvaiWidget()` 也都不会替你播放。每个 `audioData` 数据块都包含以下字段：

* `audio`: 经过 Base64 编码的有符号 16 位小端 PCM 数据，不带 WAV 文件头。
* `sample_rate` 和 `channels`：构建音频缓冲区时，应从每个数据块读取这些值，而不是将它们写死。

此播放器使用 Web Audio 将各数据块首尾相接地播放，初始为静音，并通过扬声器按钮取消静音：

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

```ts
import { ConvaiClient } from '@convai/web-sdk/core';

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

const ctx = new AudioContext();
let botMuted = true;
let endsAt = 0;
const sources = new Set<AudioBufferSourceNode>();

function stopVoice() {
  sources.forEach((s) => s.stop());
  sources.clear();
  endsAt = 0;
}

client.on('audioData', ({ audio, sample_rate, channels }) => {
  if (botMuted) return;
  const bytes = Uint8Array.from(atob(audio), (c) => c.charCodeAt(0));
  const view = new DataView(bytes.buffer);
  const frames = bytes.length / 2 / channels;
  const buffer = ctx.createBuffer(channels, frames, sample_rate);
  for (let ch = 0; ch < channels; ch++) {
    const out = buffer.getChannelData(ch);
    for (let i = 0; i < frames; i++) out[i] = view.getInt16((i * channels + ch) * 2, true) / 0x8000;
  }
  const source = ctx.createBufferSource();
  source.buffer = buffer;
  source.connect(ctx.destination);
  source.onended = () => sources.delete(source);
  sources.add(source);
  const startAt = Math.max(endsAt, ctx.currentTime + 0.04);
  source.start(startAt);
  endsAt = startAt + buffer.duration;
});

// 将此项关联到扬声器按钮。浏览器只会在用户手势触发后播放音频。
function setBotMuted(muted: boolean) {
  botMuted = muted;
  if (muted) stopVoice();
  else void ctx.resume();
  client.toggleTts(!muted);
}

function send(text: string) {
  stopVoice(); // 新消息会中断上一条回复的语音
  client.sendUserTextMessage(text);
}

await client.connect();
```

{% endcode %}

在 React 中，可改为在 effect 中订阅： `useEffect(() => client.on('audioData', play), [client])`. `on()` 会返回取消订阅函数，因此 effect 会自行清理。

#### 播放提示

* **通过用户手势解锁音频。** 在点击或按键事件中调用 `AudioContext.resume()` ，否则浏览器会让上下文保持挂起状态，无法播放任何内容。
* **用户发送消息时，停止队列中的音频。** `botTurnCompleted` 会在最后一个分块送达时触发，而不是在它播放完毕时触发，因此上一条回复可能仍在播放。
* **文本和音频会分别到达。** `bot-llm-text` 消息与 `audioData` 分块互不等待。
* **没有语音播放状态。** `isSpeaking` 在没有麦克风时意义不大。请根据自己的来源 `onended`.

### 在 Node 或服务器上使用客户端

SSE 不需要 WebRTC 或 DOM，因此它是唯一可在浏览器之外运行的传输方式：适用于 Node 脚本、服务器端渲染、无服务器函数、CI 检查和批处理作业。在这些环境中导入 `@convai/web-sdk/core` 。根入口和 `@convai/web-sdk/react` 入口会加载仅限浏览器的代码。

{% code title="ask.mjs" %}

```js
import { ConvaiClient } from '@convai/web-sdk/core';

const client = new ConvaiClient({
  apiKey: process.env.CONVAI_API_KEY,
  characterId: 'YOUR_CHARACTER_ID',
  interactionApiUrl: 'YOUR_INTERACTION_API_URL',
});

client.on('botTurnCompleted', async () => {
  const reply = client.chatMessages.filter((m) => m.type === 'bot-llm-text').at(-1);
  console.log(reply?.content);
  await client.disconnect();
});

await client.connect();
client.sendUserTextMessage('Summarize your role in one sentence.');
```

{% endcode %}

{% hint style="info" %}
你自己输入的消息不会显示在 `chatMessages` 中作为用户条目；与其他传输方式一样，对话记录由服务器发送的消息填充。请根据自己的状态渲染用户输入。
{% endhint %}

### API 参考

| 属性 / 方法                               | 类型                                                             | 说明                                                                                                 |
| ------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `transport`                           | `"livekit" \| "websocket" \| "sse"`                            | 选择传输方式。未设置时，如果设置了 `"sse"` ，则解析为 `interactionApiUrl` ；否则解析为 `"livekit"`.                            |
| `interactionApiUrl`                   | `string`                                                       | 交互 API 端点，或转发请求到该端点的服务器路由。SSE 模式下必填。                                                               |
| `ttsEnabled`                          | `boolean`                                                      | 为每条回复生成语音。SSE 模式下默认为 `false` 。                                                                     |
| `toggleTts(enabled)`                  | `(enabled: boolean) => void`                                   | 为下一条消息开启或关闭语音。                                                                                     |
| `sendUserTextMessage(text, options?)` | `(text: string, options?: SendUserTextMessageOptions) => void` | 将一条文本消息作为一个 `POST`.                                                                                |
| `sendInterruptMessage()`              | `() => void`                                                   | 停止正在进行的回复。                                                                                         |
| `characterSessionId` 事件               | `(id: string) => void`                                         | 触发时会提供服务器分配的会话 ID。可能会重复触发，但值相同。                                                                    |
| `audioData` 事件                        | `(data: AudioDataEvent) => void`                               | 触发时会提供一个语音块： `audio` （base64 PCM）、 `sample_rate`, `channels`, `includes_wav_header` （始终为 `false`). |
| `botTurnCompleted` 事件                 | `(data: unknown) => void`                                      | 回复完整发送完毕时触发。                                                                                       |

### 后续步骤

若要在 SSE 和实时传输方式之间进行选择，并设置推荐的 SSE 聊天搭配实时语音模式，请参阅 [选择传输方式](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/choose-a-transport.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/sse-transport.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.
