> 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/use-cases/website-assistant.md). Agents can also search and read this documentation through its [MCP server](https://docs.convai.com/api-docs/~gitbook/mcp).

# 构建网站助手

在你网站的每个页面添加一个 Convai 角色，它知道访客当前所在的页面，并且可以为他们导航、突出显示元素以及填写表单。

在本教程中，我们将为一个多页面网站添加网站助手：一个 Convai 角色会跟随访客从一个页面到另一个页面，回答有关当前屏幕内容的问题，并执行诸如“带我去定价页面”或“把我的电子邮件填入联系表单”之类的请求。完成后，每个页面都会有一个助手面板，访客可以通过文字或语音让助手在网站中导航。

### 我们将构建什么

我们将为一个示例网站构建助手，该网站包含主页、定价、文档和联系页面。助手可以完成以下四件事：

* **知道访客当前所在的位置。** 每次页面发生变化时，网站都会向角色发送页面名称、页面元素及其文本。
* **在网站上执行操作。** 角色会选择诸如 `Navigate To Pricing page` 或 `Highlight Start free trial button`之类的操作，然后由网站执行这些操作。
* **接收执行结果。** 执行操作后，网站会告知角色发生了什么，因此角色的下一条回复会准确无误。
* **保持同一段对话。** 即使页面切换或重新加载，访客仍会与同一个会话继续交流。

每项操作仍由你的应用负责：角色只会指出要执行的操作，而是否执行以及如何执行由你的代码决定。

以下步骤使用不依赖框架的 TypeScript 和 History API 路由器。同样的调用方式也适用于 React、Vue 或服务端渲染的网站。请参阅 [在 React 中使用](#use-it-in-react) 以了解 React 版本。

### 前提条件

* Convai Web SDK 1.9.4 或更高版本。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).
* 一个 Convai 角色和一个 API 密钥。在生产环境中，请使用身份验证令牌而非 API 密钥进行连接。请参阅 [使用身份验证令牌连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md).
* 你的网站页面，以及助手可以指向的元素。

该助手既可与 Convai 配合使用，也可用于自托管部署，并支持默认实时传输方式和 SSE 传输方式。

### 描述你的网站

列出助手可以使用的页面和元素。每个 `name` 是角色选择操作目标时使用的名称，因此请确保名称简短且明确。每个 `description` 都有助于角色进行选择。

```ts
// site.ts
export interface SitePage {
  name: string;
  path: string;
  description: string;
}

export interface SiteElement {
  name: string;
  description: string;
  path: string; // the page the element lives on
  selector: string;
}

export const PAGES: SitePage[] = [
  { name: 'Home page', path: '/', description: 'Overview of Acme Robotics and its warehouse robots' },
  { name: 'Pricing page', path: '/pricing', description: 'Plans and prices: Starter, Team, and Enterprise' },
  { name: 'Docs page', path: '/docs', description: 'Setup guides for installing robots' },
  { name: 'Contact page', path: '/contact', description: 'Contact form to reach the sales team' },
];

export const ELEMENTS: SiteElement[] = [
  { name: 'Start free trial button', description: 'Starts a free trial', path: '/pricing', selector: '#start-trial' },
  { name: 'Install guide', description: 'How to install a robot', path: '/docs', selector: '#install-guide' },
  { name: 'Email field', description: 'Email input of the contact form', path: '/contact', selector: '#contact-email' },
  { name: 'Message field', description: 'Message input of the contact form', path: '/contact', selector: '#contact-message' },
];

export function currentPage(): SitePage {
  return PAGES.find((page) => page.path === location.pathname) ?? PAGES[0];
}
```

### 声明动作

传入动作及其可能的目标 `actionConfig`。页面和元素都放入 `objects`，因此角色可以将两者中的任意一个作为目标。

```ts
// assistant.ts
import { ConvaiClient, type ConvaiAction } from '@convai/web-sdk/core';
import { ELEMENTS, PAGES, currentPage, type SitePage } from './site';

const actionConfig = {
  actions: ['Navigate To', 'Highlight', 'Fill Email', 'Fill Message'],
  objects: [
    ...PAGES.map(({ name, description }) => ({ name, description })),
    ...ELEMENTS.map(({ name, description }) => ({ name, description })),
  ],
  characters: [{ name: 'Visitor', bio: 'The person browsing this website' }],
};
```

会话连接时会发送此配置，因此请声明助手可能需要的所有页面和元素，而不仅仅是当前页面上的内容。有关完整的动作约定，请参阅 [处理角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/actions.md).

### 告知角色访客所在的位置

编写一个描述当前页面的函数。请以助手的角色说明开头，因为每次更新都会整体替换先前的动态信息。

```ts
const ROLE =
  '你是 Acme Robotics 网站的助手。回答有关该网站的问题；当' +
  '访客要求前往某处、查看某项内容或填写信息时，执行相应的动作。' +
  '以 "Action result" 开头的行会报告网站执行的操作。如果你选择的动作没有' +
  '结果，说明它并未运行：告知访客这一点，并再次选择该动作。';

function describePage(page: SitePage): string {
  const visibleText = (document.querySelector<HTMLElement>('main')?.innerText ?? '')
    .replace(/\s+/g, ' ')
    .slice(0, 1500);
  const elements = ELEMENTS.filter((element) => element.path === page.path).map((element) => element.name);
  return [
    ROLE,
    `访客当前位于 ${page.name}（${page.path}）。`,
    elements.length ? `此页面上的元素：${elements.join(', ')}。` : '',
    `页面文本：${visibleText}`,
  ].filter(Boolean).join('\n');
}
```

连接时使用 `dynamicInfo`发送描述，然后在 `updateDynamicInfo` 页面发生变化时再次发送。 `updateDynamicInfo` 在会话就绪之前不会执行任何操作，因此也要在 `botReady`.

```ts
export const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  endUserId: visitorId(),
  characterSessionId: sessionStorage.getItem('assistant-session') ?? undefined,
  startWithAudioOn: false,
  actionConfig,
  dynamicInfo: describePage(currentPage()),
});

client.on('botReady', () => client.updateDynamicInfo(describePage(currentPage())));

// 每次页面渲染后，在路由器中调用此函数。
export function onPageChange(page: SitePage): void {
  client.updateDynamicInfo(describePage(page));
}
```

页面文本应简短。概述页面上可见的内容即可，让角色能够回答相关问题。

{% hint style="success" %}
打开“定价”页面并询问“我现在在哪个页面？”。角色会说出“定价”页面，并能回答有关其套餐的问题。
{% endhint %}

### 跨页面延续同一段对话

`endUserId` 用于标识访客， `characterSessionId` 用于恢复其对话。请长期保存访客 ID，并将会话 ID 存储在浏览器标签页中，这样重新加载或完整加载页面时就能继续同一段对话。

```ts
function visitorId(): string {
  let id = localStorage.getItem('assistant-visitor-id');
  if (!id) {
    id = crypto.randomUUID();
    localStorage.setItem('assistant-visitor-id', id);
  }
  return id;
}

client.on('characterSessionId', (id: string) => sessionStorage.setItem('assistant-session', id));
```

在单页应用中，应在根组件中只创建一次客户端，并在访客切换路由时保持连接。在完整加载页面的网站中，则应在每个页面上创建客户端：存储的会话 ID 会让对话从中断处继续。客户端的聊天消息在每次连接时都会清空，因此完整加载页面后面板会显示为空白，但角色仍记得之前的对话。若要显示之前的对话轮次，请将对话记录副本保存在自己的 `sessionStorage`中。若要为已登录的访客提供长期记忆，请使用其账户 ID 作为 `endUserId`。请参阅 [使用长期记忆](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/long-term-memory.md).

### 执行操作

订阅 `actionResponse`。每个事件都会按顺序携带一个轮次中的操作，因此请依次执行。

```ts
client.on('actionResponse', ({ actions }: { actions: ConvaiAction[] }) => {
  void runActions(actions);
});

async function runAction({ name, target }: ConvaiAction): Promise<string> {
  switch (name) {
    case 'Navigate To': {
      const page = PAGES.find((p) => p.name === target) ?? pageNamedIn(lastVisitorText);
      if (!page) return 'failed, unknown page';
      navigate(page.path); // 你的路由器
      return `done, now on the ${page.name}`;
    }
    case 'Highlight': {
      const element = ELEMENTS.find((e) => e.name === target);
      if (!element) return 'failed, unknown element';
      if (element.path !== location.pathname) navigate(element.path);
      return spotlight(element.selector) ? 'done' : 'failed, element not on screen';
    }
    case 'Fill Email':
      return fill('/contact', '#contact-email', valueFrom(target, /[\w.+-]+@[\w-]+\.[\w.-]+/));
    case 'Fill Message':
      return fill('/contact', '#contact-message', valueFrom(target, /"([^"]+)"/));
    default:
      return 'failed, not supported';
  }
}
```

Convai 也可能将目标放在操作名称中返回，例如 `Navigate To: Contact page` 且不带 `target`. `normalize` 会将声明的操作名称与其余部分拆分开来，因此两种格式都能以相同的方式运行。 `runActions` 在 [报告发生了什么](#report-what-happened) 会在……之前应用它 `runAction`:

```ts
const ACTIONS = actionConfig.actions;

function normalize(action: ConvaiAction): ConvaiAction {
  if (ACTIONS.includes(action.name)) return action;
  const name = ACTIONS.find((known) => action.name.toLowerCase().startsWith(known.toLowerCase()));
  if (!name) return action;
  const rest = action.name.slice(name.length).replace(/^[\s:-]+/, '').trim();
  return { name, target: action.target ?? (rest || undefined) };
}
```

其他辅助函数会将元素滚动到视野内并为其添加轮廓，还会向字段中输入一个值：

```ts
function spotlight(selector: string): boolean {
  const element = document.querySelector<HTMLElement>(selector);
  if (!element) return false;
  element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  element.classList.add('spotlight'); // style this class with an outline
  return true;
}

function fill(path: string, selector: string, value: string | undefined): string {
  if (location.pathname !== path) navigate(path);
  const field = document.querySelector<HTMLInputElement | HTMLTextAreaElement>(selector);
  if (!field) return 'failed, field not found';
  spotlight(selector);
  if (!value) return 'failed, no value given: ask the visitor what to enter';
  field.value = value;
  field.dispatchEvent(new Event('input', { bubbles: true }));
  return `done, entered "${value}"`;
}
```

将目标与您自己的列表进行匹配，并忽略其他内容，这样角色就只能访问您声明的页面和元素。不可逆的操作（例如提交表单或付款）应留给访客执行：高亮显示按钮，而不要替访客点击。

#### 从访客的消息中读取值

操作目标指向您声明的对象。电子邮件地址等访客口述的自由格式值并非声明对象，因此操作可能不带目标。请保留访客的最新消息，并在缺少目标时从中读取该值。

```ts
let lastVisitorText = '';
export function rememberVisitorText(text: string): void {
  lastVisitorText = text;
}

function valueFrom(target: string | undefined, pattern: RegExp): string | undefined {
  if (target && pattern.test(target)) return target;
  const match = lastVisitorText.match(pattern);
  return match ? (match[1] ?? match[0]) : undefined;
}

function pageNamedIn(text: string): SitePage | undefined {
  const words = text.toLowerCase();
  return PAGES.find((page) => words.includes(page.name.replace(' page', '').toLowerCase()));
}
```

在 `rememberVisitorText` 之前 `sendUserTextMessage`，并从 `messagesChange` 对于口头请求，下一节将展示相关处理方式。 `pageNamedIn` 用于处理偶尔出现的 `Navigate To` 请求，这类请求没有附带目标。

### 报告执行结果

操作运行后，将结果追加到角色的上下文中，而不要求它回复。角色会在下一轮读取这些结果，因此可以确认发生了什么，或重试。

```ts
async function runActions(actions: ConvaiAction[]): Promise<void> {
  const results: string[] = [];
  for (const action of actions.map(normalize)) {
    // 跳过未声明的名称，而不是将它们报告为失败。
    if (!ACTIONS.includes(action.name)) continue;
    results.push(`${action.name}${action.target ? ` ${action.target}` : ''}: ${await runAction(action)}`);
  }
  if (results.length) {
    client.updateContext({ text: `Action result: ${results.join('; ')}`, mode: 'append', run_llm: 'false' });
  }
}
```

如果没有结果，选择了某项操作的角色就无法判断该操作是否已运行，可能会错误地告诉访客操作已经执行。有关其他 `updateContext` 选项，请参阅 [在运行时更新角色上下文](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/dynamic-context.md).

### 添加聊天面板

呈现对话、发送文本消息，并允许访客通过语音交谈。 `AudioRenderer` 用于播放角色的语音。

```ts
// main.ts
import { AudioRenderer } from '@convai/web-sdk/vanilla';
import type { ChatMessage } from '@convai/web-sdk/core';
import { client, rememberVisitorText } from './assistant';

const transcript = document.querySelector<HTMLOListElement>('#transcript')!;
const composer = document.querySelector<HTMLFormElement>('#composer')!;
const input = document.querySelector<HTMLInputElement>('#message')!;
const mic = document.querySelector<HTMLButtonElement>('#mic')!;

const SPEAKERS: Partial<Record<ChatMessage['type'], string>> = {
  'user-llm-text': 'visitor',
  'user-transcription': 'visitor',
  'bot-llm-text': 'assistant',
};

client.on('messagesChange', (messages: ChatMessage[]) => {
  transcript.replaceChildren(
    ...messages
      .filter((message) => SPEAKERS[message.type] && message.content)
      .map((message) => {
        const item = document.createElement('li');
        item.className = `from-${SPEAKERS[message.type]}`;
        item.textContent = message.content;
        return item;
      }),
  );
  const latest = messages.filter((m) => SPEAKERS[m.type] === 'visitor').at(-1);
  if (latest?.content) rememberVisitorText(latest.content);
});

composer.addEventListener('submit', (event) => {
  event.preventDefault();
  const text = input.value.trim();
  if (!text) return;
  rememberVisitorText(text);
  client.sendUserTextMessage(text);
  input.value = '';
});

mic.addEventListener('click', () => void client.audioControls.toggleAudio());

void client.connect().then(() => new AudioRenderer(client.room));
```

在访客点击、轻触或按下页面上的按键之前，浏览器会阻止播放声音，而客户端通常会在此之前连接。 `AudioRenderer` 会处理这种情况：当浏览器阻止播放时，它会在访客首次与页面交互时启动语音，例如输入消息或按下麦克风按钮。

面板使用纯 HTML 构建：用有序列表显示对话记录，并用表单包含麦克风按钮、文本输入框和一个 **发送** 按钮。将面板固定在页面一侧，这样即使下方页面发生变化，面板也会保持原位。

### 试用助手

启动网站，等待面板连接，然后按顺序尝试以下请求：

1. “带我去定价页面。”网站会打开定价页面。
2. “Team 套餐多少钱？”角色会根据页面文本回答。
3. “给我看看免费试用按钮。”页面会滚动到该按钮，并为其添加轮廓。
4. “前往联系页面，并在电子邮件字段中填入 <jane@example.com>。”只需一个请求，网站就会打开联系页面并填入电子邮件字段。
5. “刚才操作成功了吗？”角色会根据操作结果进行确认。

{% hint style="success" %}
角色说话时，页面会发生变化，相关元素也会显示轮廓；角色还会正确确认操作结果。重新加载页面后，对话会从上次中断处继续。
{% endhint %}

选择麦克风，大声说出相同的请求。语音请求会触发相同的操作。

### 在 React 中使用

`useConvaiClient` 接受相同的选项。使用一个在路由变化时运行的 effect 更新上下文，并在另一个 effect 中处理操作。

```tsx
import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useConvaiClient } from '@convai/web-sdk/react';

export function useWebsiteAssistant() {
  const location = useLocation();
  const navigate = useNavigate();
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    endUserId: visitorId(),
    actionConfig,
    dynamicInfo: describePage(currentPage()),
  });

  useEffect(() => {
    // 等待一帧，让新路由完成渲染后再读取其文本。
    const frame = requestAnimationFrame(() => client.updateDynamicInfo(describePage(currentPage())));
    return () => cancelAnimationFrame(frame);
  }, [client, location.pathname]);

  useEffect(
    () => client.on('actionResponse', ({ actions }) => void runActions(actions, navigate)),
    [client, navigate],
  );

  return client;
}
```

在根布局中只挂载一次此 hook，这样对话就能在路由切换后继续保留。

### 后续步骤

{% content-ref url="/pages/503cd2436973022c29d385f47025d13de33f428c" %}
[处理角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/actions.md)
{% endcontent-ref %}

{% content-ref url="/pages/4c37a8e73c580fc9f3ebe503a43373bd3551a22e" %}
[在运行时更新角色上下文](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/dynamic-context.md)
{% endcontent-ref %}

{% content-ref url="/pages/534e8cdc1d57114dcd7601d4455823f77a9ad2ef" %}
[使用认证令牌连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md)
{% endcontent-ref %}

{% content-ref url="/pages/000d34cc8d7b752e53fed78c1eab5ccdcdaf9a00" %}
[连接到自托管部署](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/self-hosted-deployments.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/use-cases/website-assistant.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.
