> 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).

# 入门

使用我们的 Web SDK 快速入门指南开始构建应用

{% 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";
```

使用 React 库提供的 `convaiClient` 变量，借助 `useRef` 钩子进行声明。该 `useRef` 钩子会返回一个可变的 ref 对象，可用于存储在组件多次渲染间持续保留的值。

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

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

```javascript
convaiClient.current = new ConvaiClient({
      apiKey: string //在此处输入您的 API 密钥，
      characterId: string //输入您的角色 ID，
      enableAudio: boolean, //仅使用文本时设为 false。
      sessionId: string //使用此项保存对话会话，以便保存对话
      disableAudioGeneration: boolean false, //仅聊天应用的可选参数
    });
```

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

以下是使用 ConvaiClient 与 NPC 互动和对话的主要方法。

1. **setResponseCallback**

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

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

**示例：**

```javascript
//在 useEffect 外部声明这部分代码（React 钩子）
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" %}
此方法也可用于处理动画：音频停止后，我们可以将虚拟形象设为 `idle` 状态。
{% endhint %}

6. **sendTextChunk**

**说明：** 可用于向客户端发送文本片段，客户端会进一步处理该片段并生成 NPC 的输出。

**参数：** text (string)：接收一个字符串类型的文本片段作为输入。

**示例：** 如果使用文本框接收用户输入，可以按以下方式设置文本框，其中

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

/*以上状态将用作触发器。当用户在文本框中输入内容并按下回车键时，我们会将 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 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-1/getting-started.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.
