> 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/published-text-chat.md).

# 连接到已发布的文本聊天

通过一次性启动授权，从已发布的 Convai 角色开始一段无需凭证、仅文本的聊天，可在 React、原生 TypeScript 中使用，或作为可复制粘贴的嵌入内容。

让访客与已发布的角色聊天，同时不在浏览器中放置 API 密钥、角色 ID 或任何可重复使用的凭据。将已发布的聊天嵌入自己的应用，或将页面从已移除的 `<convai-chat>` 元素迁移时，请使用本页说明。

### 已发布聊天的工作原理

已发布的聊天由发布 ID 标识。浏览器不会获取角色配置；它会通过发布 API 的两个公开端点，以及与 Core 的一次交互来完成连接：

1. 获取公开描述信息：显示名称、描述、图片和模式（始终为 `"text"`).
2. 生成一个短时有效、仅可使用一次的启动授权。
3. 将授权传给 `connectWithPublicationGrant()`；该方法会将授权交给 Core 兑换，并加入会话。

该会话仅支持文本。 `client.connectionType` 的值为 `"text"` ，且 `client.isPublishedChatSession` 的值为 `的值为`true

。Core 签发的房间令牌不允许发布麦克风或摄像头轨道。每个授权只能使用一次，因此每个新会话都需要新的授权。 `@convai/web-sdk/embed`中的辅助函数可用于步骤 1 和步骤 2。它们不依赖传输层，可安全地在服务器上导入。

### 前提条件

* `@convai/web-sdk` 需安装 1.9.0 或更高版本。
* 已发布角色的发布 ID（UUID）。
* 部署所用的发布 API 源站和 Core 源站。默认值为 `https://api.convai.com` 和 `https://realtime-api.convai.com`；用于暂存或本地部署时，请显式传入这两个值。

### 连接并显示聊天

`loadPublishedChatSession()` 会同时获取描述信息和一个授权。使用该授权连接，根据描述信息设置组件标签，并将 `requestPublicationGrant` 传给组件，以便它之后能自行启动新会话。

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

```tsx
import { useState } from 'react';
import { useConvaiClient } from '@convai/web-sdk/react';
import { ConvaiWidget } from '@convai/web-widget/react';
import {
  getPublishedChatEndpoints,
  loadPublishedChatSession,
  requestPublishedChatGrant,
} from '@convai/web-sdk/embed';

const publicationId = 'PUBLICATION_UUID';
const publicationApiUrl = 'https://api.convai.com';
const coreUrl = 'https://realtime-api.convai.com';

export default function PublishedChat() {
  const client = useConvaiClient();
  const [descriptor, setDescriptor] =
    useState<{ display_name: string; image_url: string | null }>();

  const connect = async () => {
    const session = await loadPublishedChatSession(publicationId, publicationApiUrl);
    setDescriptor(session.descriptor);
    await client.connectWithPublicationGrant(session.launchToken, { url: coreUrl });
  };

  const { launchGrantUrl } = getPublishedChatEndpoints(publicationId, publicationApiUrl);

  return (
    <>
      <button onClick={connect}>开始聊天</button>
      <ConvaiWidget
        convaiClient={client}
        defaultVoiceMode={false}
        publishedChatDescriptor={descriptor}
        publishedChatConnectOptions={{ url: coreUrl }}
        requestPublicationGrant={() => requestPublishedChatGrant(launchGrantUrl.toString())}
      />
    </>
  );
}
```

{% endcode %}
{% endtab %}

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

```typescript
import { ConvaiClient } from '@convai/web-sdk/core';
import { createConvaiWidget } from '@convai/web-widget/vanilla';
import {
  getPublishedChatEndpoints,
  loadPublishedChatSession,
  requestPublishedChatGrant,
} from '@convai/web-sdk/embed';

const publicationId = 'PUBLICATION_UUID';
const publicationApiUrl = 'https://api.convai.com';
const coreUrl = 'https://realtime-api.convai.com';

const client = new ConvaiClient();

const { launchGrantUrl } = getPublishedChatEndpoints(publicationId, publicationApiUrl);
const session = await loadPublishedChatSession(publicationId, publicationApiUrl);
await client.connectWithPublicationGrant(session.launchToken, { url: coreUrl });

createConvaiWidget(document.body, {
  convaiClient: client,
  defaultVoiceMode: false,
  publishedChatDescriptor: session.descriptor,
  publishedChatConnectOptions: { url: coreUrl },
  requestPublicationGrant: () => requestPublishedChatGrant(launchGrantUrl.toString()),
});
```

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

`useConvaiClient()` 和 `new ConvaiClient()` 在此处无需任何配置：授权凭证包含会话所需的一切信息。

描述符可安全地显示。角色配置、API 密钥及其他仅供发布者使用的数据绝不会返回给浏览器。

### 不使用组件连接

使用 `requestPublishedChatGrant()` 获取授权凭证并进行连接。发送第一条消息前，请等待 `botReady` 事件。

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

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

const { launchGrantUrl } = getPublishedChatEndpoints('PUBLICATION_UUID', 'https://api.convai.com');
const launchToken = await requestPublishedChatGrant(launchGrantUrl.toString());

const client = new ConvaiClient();
const unsubscribe = client.on('botReady', () => {
  unsubscribe();
  client.sendUserTextMessage('Hello!');
});

await client.connectWithPublicationGrant(launchToken, { url: 'https://realtime-api.convai.com' });
```

{% endcode %}

### 开始新会话

授权凭证会在首次连接时被消耗，不能用于重新连接。每次开始新会话时都要申请新的授权凭证。

组件通过 `requestPublicationGrant`实现这一点。重置、断开连接以及重新打开面板时，都会调用此函数以获取新的授权凭证，而不是重复使用已消耗的凭证。如果未提供此函数，从组件开始新会话时会抛出 `Published chat widgets require requestPublicationGrant to start a new session`.

`requestPublicationGrant` 可以调用你自己的后端，而不是发布 API，只要它返回 `launch_token` 字符串：

{% code title="src/PublishedChat.tsx" %}

```tsx
<ConvaiWidget
  convaiClient={client}
  publishedChatDescriptor={descriptor}
  requestPublicationGrant={async () => {
    const response = await fetch(`/api/chat/${publicationId}/grant`, { method: 'POST' });
    if (!response.ok) throw new Error('Unable to relaunch published chat');
    return (await response.json()).launch_token;
  }}
/>
```

{% endcode %}

如果你构建自己的界面，并在不同会话之间保留 `PublishedChatConnectOptions` ，请在每个新会话开始前，将其传入 `freshPublicationGrantOptions()` 。该函数会保留 `url`, `iceTransportPolicy` 和 `signal`，并移除 `connectAttemptId`，因为该值只能在重试同一授权时重复使用。

```typescript
import { freshPublicationGrantOptions, requestPublishedChatGrant } from '@convai/web-sdk/embed';

const launchToken = await requestPublishedChatGrant(launchGrantUrl.toString());
await client.connectWithPublicationGrant(launchToken, freshPublicationGrantOptions(savedOptions));
```

### 重试、取消和错误

`connectWithPublicationGrant()` 会为每次交换请求发送一个幂等键，即 `connectAttemptId`。如果未提供该值，SDK 会自动生成。若交换因网络错误、5xx 状态码或格式错误的响应而失败，SDK 会使用相同的键重试一次，因此 Core 会重放同一个逻辑连接，而不是让授权悬而未决或创建第二个会话。

{% hint style="warning" %}
不要缓存授权令牌、将其放入 URL，或使用新签发的授权令牌重试。如果你在 SDK 的重试机制之上添加自己的重试逻辑，请使用相同的 `connectAttemptId` 和同一个授权令牌。
{% endhint %}

| 情况                         | 处理结果                                                                                                                                                                |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 授权令牌不是长度为 32 到 512 个字符的字符串 | 抛出 `A valid publication launch token is required` ，且不会发送任何请求。                                                                                                       |
| 客户端已连接或正在连接                | 抛出 `Disconnect the current session before connecting again`。请先调用 `disconnect()` 。                                                                                   |
| `signal` 触发中止              | 交换请求或房间连接会被取消并拆除，Promise 会以 `AbortError`.                                                                                                                           |
| Core 拒绝授权令牌                | Promise 会以服务器返回的消息拒绝， `error` 事件会以相同的错误触发，并且 `client.requestTraceId` 当服务器返回跟踪 ID 时，保存该 ID。                                                                          |
| 发布 API 拒绝描述符或授权请求时         | `loadPublishedChatSession()` 或 `requestPublishedChatGrant()` 会返回服务器提供的错误消息，或者 `Unable to load published chat (status)` / `Unable to start published chat (status)`. |

引用 `client.requestTraceId` 报告连接失败时，请提供此 ID。

### 网络与部署

已发布的聊天默认通过 WebRTC 连接，并使用 `iceTransportPolicy: 'relay'` ，因此流量会经由 TURN 服务器传输。Convai 托管的 Core 已提供 TURN 服务器。若部署环境没有 TURN，请传入 `iceTransportPolicy: 'all'`.

```typescript
await client.connectWithPublicationGrant(launchToken, {
  url: 'https://realtime.example.com',
  iceTransportPolicy: 'all',
});
```

### 从服务器调用授权辅助函数

在浏览器中， `requestPublishedChatGrant()` 和 `loadPublishedChatSession()` 会为每个浏览器生成独立的请求者 ID，并在每次授权请求中发送该 ID。在服务器或服务器端渲染期间，没有可用于限定 ID 范围的浏览器，因此除非传入所服务访客的请求者 ID，否则调用会抛出异常：该 ID 长度为 16 到 128 个字符，由字母、数字， `_` 或 `-`.

```typescript
const launchToken = await requestPublishedChatGrant(
  launchGrantUrl.toString(),
  fetch,
  undefined,        // signal
  visitorScopedId,  // one ID per visitor
);
```

{% hint style="warning" %}
不要让所有访客共用同一个进程级请求者 ID。
{% endhint %}

### 无需构建步骤即可嵌入

如果页面只需直接嵌入聊天功能，请使用 `<convai-widget>` 元素，它来自 [`@convai/web-widget`](https://www.npmjs.com/package/@convai/web-widget)。它会为每个会话自行生成授权，并根据公开描述符设置标题，因此宿主页面无需持有角色 ID 或凭证。

{% code title="index.html" %}

```html
<script src="https://cdn.jsdelivr.net/npm/@convai/web-widget/v1.js" async></script>

<convai-widget
  publication-id="PUBLICATION_UUID"
  publication-api-url="https://api.convai.com"
  core-url="https://realtime-api.convai.com"
  placement="inline"
  style="display:block;width:100%;height:640px">
</convai-widget>
```

{% endcode %}

有两点需要注意，任何一点配置错误都会导致内容无法显示：

* 不要添加 `type="module"` 添加到 script 标签中。加载器会读取 `document.currentScript`，它在模块脚本中为 `null` 。
* 设置 `placement="inline"` ，即可将面板放置在由 `style`设置尺寸的位置。否则，组件会显示为位于右下角的悬浮启动器。

主题、事件以及元素的其他属性，请参阅 `@convai/web-widget` 软件包的文档。

### 从 `<convai-chat>`

迁移 `1.9.0 版本移除了` 元素和 `入口点（` ）。请替换 script 标签和元素；发布属性保持不变。`dist/embed/chat-embed-v1.js`。请替换 script 标签和元素；发布属性保持不变。

{% code title="index.html" %}

```html
<!-- 之前 -->
<script
  type="module"
  src="https://cdn.jsdelivr.net/npm/@convai/web-sdk@X/dist/embed/chat-embed-v1.js"
></script>
<convai-chat
  publication-id="…"
  publication-api-url="…"
  core-url="…"
></convai-chat>

<!-- 之后 -->
<script
  src="https://cdn.jsdelivr.net/npm/@convai/web-widget@X/v1.js"
  async
></script>
<convai-widget
  publication-id="…"
  publication-api-url="…"
  core-url="…"
  placement="inline"
></convai-widget>
```

{% endcode %}

请注意， `type="module"` 已移除，并且 `placement="inline"` 已添加。 `中的辅助函数` 和 `connectWithPublicationGrant()` 保持不变。

### API 参考

| 属性 / 方法                                          | 类型                                                                                                    | 说明                                                                |
| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `connectWithPublicationGrant`                    | `(launchToken: string, options?: PublishedChatConnectOptions) => Promise<void>`                       | 将一次性授权与 Core 交换，并开启纯文本会话。                                         |
| `PublishedChatConnectOptions.url`                | `string`                                                                                              | 核心源站地址。默认为 `https://realtime-api.convai.com`.                     |
| `PublishedChatConnectOptions.iceTransportPolicy` | `RTCIceTransportPolicy`                                                                               | 默认为 `'relay'`。仅当部署没有 TURN 服务器时，才使用 `'all'` 。                      |
| `PublishedChatConnectOptions.signal`             | `AbortSignal`                                                                                         | 取消正在进行的授权交换或房间连接，并将其清理。                                           |
| `PublishedChatConnectOptions.connectAttemptId`   | `string`                                                                                              | 幂等键。未提供时会自动生成；仅在重试同一授权时复用。                                        |
| `client.connectionType`                          | `'audio' \| 'video' \| 'text' \| null`                                                                | `'text'` ，表示已发布的聊天会话。                                             |
| `client.isPublishedChatSession`                  | `boolean`                                                                                             | 表示客户端最近一次是否通过发布授权连接。                                              |
| `client.requestTraceId`                          | `string \| null`                                                                                      | 最近一次连接请求的服务器跟踪 ID（如果有提供）。                                         |
| `loadPublishedChatSession`                       | `(publicationId, publicationApiUrl?, fetch?, signal?, requesterId?) => Promise<PublishedChatSession>` | 获取公开描述信息和一个授权。成功时返回 `{ descriptor, launchToken }`.                |
| `requestPublishedChatGrant`                      | `(launchGrantUrl, fetch?, signal?, requesterId?) => Promise<string>`                                  | 为新会话创建授权。服务器调用方必须传入 `requesterId`.                                |
| `getPublishedChatEndpoints`                      | `(publicationId, publicationApiUrl?) => PublishedChatEndpoints`                                       | 返回经过验证的 `descriptorUrl` 和 `launchGrantUrl`。如果发布 ID 不是 UUID，则抛出异常。 |
| `fetchPublishedChatDescriptor`                   | `(descriptorUrl, fetch?, signal?) => Promise<PublishedChatDescriptor>`                                | 仅获取公开描述信息。                                                        |
| `freshPublicationGrantOptions`                   | `(options?: PublishedChatConnectOptions) => PublishedChatConnectOptions \| undefined`                 | 复制选项，但不包含 `connectAttemptId`，用于启动新会话。                             |
| `PublishedChatDescriptor`                        | `{ publication_id, display_name, description, image_url, mode: 'text' }`                              | 出版物的公开显示数据。                                                       |
| `requestPublicationGrant` （组件选项）                 | `() => Promise<string>`                                                                               | 组件在后续会话启动时会申请新的授权凭证。发布的聊天功能必须提供此选项。                               |
| `publishedChatConnectOptions` （组件选项）             | `PublishedChatConnectOptions`                                                                         | 组件传递给 `connectWithPublicationGrant()`.                            |
| `publishedChatDescriptor` （组件选项）                 | `{ display_name, image_url }`                                                                         | 无需查询角色，即可为组件标题栏指定标签。                                              |


---

# 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/published-text-chat.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.
