> 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-1/getting-started.md).

# 入门指南

{% hint style="info" %}
:no\_entry: 此插件已被弃用，不再受支持。

\
如果你仍在使用旧插件，我们建议切换到新的 Convai Web SDK： [链接](https://docs.convai.com/api-docs/plugins-and-integrations/web-plugins/convai-web-sdk)

\
仅供历史参考——这些文档已不再维护。
{% endhint %}

首先从 convai-web-sdk 导入 Convai 客户端。

```javascript
import { ConvaiClient } from "convai-web-sdk";
```

声明 `convaiClient` 变量，使用 React 库提供的 `useRef` 钩子。 `useRef` 该钩子返回一个可变的 ref 对象，可用于存储在组件重渲染之间保持不变的值。

```javascript
const convaiClient = useRef(null);
```

在一个 `useEffect` 钩子内初始化 Convai 客户端，以确保它只在组件挂载时运行一次。通过将空依赖数组作为 `useEffect` 钩子的第二个参数，初始化代码将只在首次渲染时执行。

```javascript
convaiClient.current = new ConvaiClient({
      apiKey: string //在这里输入你的 API Key，
      characterId: string //在这里输入你的角色 ID，
      enableAudio: boolean, //仅文本模式时使用 false。
      sessionId: string //使用此项将对话会话保存起来，以保存对话
      disableAudioGeneration: boolean false, //仅聊天应用的可选参数
    });
```

你的 Convai 客户端已初始化。现在你可以使用 Convai Client 方法与你的 NPC 建立对话。

这些是允许你通过 ConvaiClient 与 NPC 互动和对话的主要方法。

1. **setResponseCallback**

**说明：** 为 ConvaiClient 实例设置响应回调函数。当从 Convai API 收到响应时，将调用此回调函数。这部分代码也应放在与初始化相同的 useEffect 中。

**参数：** `callback` （函数）：当收到响应时将执行的回调函数。它接收一个参数，表示收到的响应数据。

**示例：**

```javascript
//将这部分代码（React hooks）声明在 useEffect 外部
const [userText, setUserText] = useState("");
const [npcText, setNpcText] = useState("");
const [keyPressed, setKeyPressed] = useState(false);
const [isTalking, setIsTalking] = useState(false);
const finalizedUserText = useRef();
const npcTextRef = useRef();
------------------------------------------------------------------------------------


convaiClient.current.setResponseCallback((response) => {
      if (response.hasUserQuery()) {
        var transcript = response.getUserQuery();
        var isFinal = transcript.getIsFinal();
        if (isFinal) {
          finalizedUserText.current += " " + transcript.getTextData();
          transcript = "";
        }
        if (transcript) {
          setUserText(finalizedUserText.current + transcript.getTextData());
        } else {
          setUserText(finalizedUserText.current);
        }
      }
      if (response.hasAudioResponse()) {
        var audioResponse = response?.getAudioResponse();
        npcTextRef.current += " " + audioResponse.getTextData();
        setNpcText(npcTextRef.current);
      }
    });
```

这部分代码从响应中获取用户查询，并将最终文本设置为 userText，随后进一步用于生成 NPC 的响应，该响应会存储为 npcText。

另外，请记得在 `onAudioPlay` 和 `onAudioStop` 方法内部声明下面描述的 `useEffect` 在 `setResposeCallback` 方法之后，以避免出现错误。

2. **startAudioChunk**

**说明：** 启动客户端接受用于语音输入的音频块。此方法会通知客户端开始接收和处理音频数据。

**参数：** 无

**示例：**

```javascript
function handleKeyPress(event) {
    //每当用户按下 [Space] 时，客户端将开始接收音频
    if (event.Code === "KeyT" && !keyPressed) {
      setKeyPressed(true);
      finalizedUserText.current = "";
      npcTextRef.current = "";
      setUserText("");
      setNpcText("");
      convaiClient.current.startAudioChunk();
    }
  }
```

你可以使用此方法让客户端仅在用户按下某个特定键时监听并接收音频输入。

3. **endAudioChunk**

**说明：** 指示客户端停止获取用户音频输入，并完成用于语音输入的音频块传输。此方法表示音频输入结束，并允许客户端处理收到的音频数据。

**参数：** 无

**示例：**

```javascript
function handleKeyRelease(event) {
    if (event.Code === "KeyT" && keyPressed) {
      setKeyPressed(false);
      convaiClient.current.endAudioChunk();
    }
  }
```

你可以使用此方法让客户端在松开某个特定键时停止监听音频。

4. **onAudioPlay**

**说明：** 当 NPC 开始说话时通知。

**参数：** 无

**示例：**

```javascript
convaiClient.onAudioPlay(() => {
    setIsTalking(true);
  });
```

{% hint style="info" %}
此方法可用于与动画配合：一旦音频开始，我们就可以将头像设置为执行 `说话` 动画。
{% endhint %}

5. **onAudioStop**

**说明：** 当 NPC 停止说话时通知。

**参数：** 无

**示例：**

```javascript
convaiClient.current.onAudioStop(() => {
      setIsTalking(false);
    });
```

{% hint style="info" %}
此方法也可用于与动画配合：一旦音频停止，我们就可以将头像设置为处于 `待机` 姿态。
{% endhint %}

6. **sendTextChunk**

**说明：** 可用于向客户端发送一个文本块，随后会对其进行处理并生成 NPC 输出。

**参数：** text (string): 接收一个 string 类型的文本块作为输入。

**示例：** 当你使用文本框来获取用户输入时可使用此方法。你可以按以下方式设置文本框，其中

```javascript
const [enter, setEnter] = useState(0);

/*上面的状态将用作触发器；每当用户
在文本框中输入内容并按下 enter 时，我们会将 enter 改为 1；一旦内容发送给客户端， 
我们会再次将 enter 设为 0。*/  

function sendText() {
    finalizedUserText.current = "";
    npcTextRef.current = "";
    setNpcText("");
    convaiClient.current.sendTextChunk(userText);
    setEnter(0);
  }

//处理文本框消息
useEffect(() => {
  if (
    document.activeElement.tagName === "INPUT" ||
    document.activeElement.tagName === "TEXTAREA" ||
    document.activeElement.isContentEditable
  ) {
    if (userText !== "" && enter) {
      sendText();
    }
  }
}, [enter]);
```

你可以使用此方法从文本框获取输入，然后将其发送给客户端进行处理。

7. **resetSession**

**说明：** 用于重置当前会话。

**参数：** 无

**示例：**

```javascript
const ResetHistory = () => {
      convaiClient.current.resetSession();
  };
```

8. **toggleAudioVolume**

**说明：** 可用于将音频模式从开启切换到关闭，或反之。

**参数：** 无

**示例：**

```javascript
const ToggleAudioVolume() {
    convaiClient.current.toggle();
  }
```


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk-1/getting-started.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
