> 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/api-can-kao/core-api-reference/interaction-apis/interaction-api.md).

# 交互 API

本页详细说明了如何与角色交互。

{% hint style="danger" %}
此 API 仅适用于 Professional Plan 及以上套餐。
{% endhint %}

## 与角色交互

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/character/getResponse`

用户可以为终端用户实现一个聊天机器人会话，让他们与自己的角色进行对话。用户可以通过在所发出的 API 请求中维护 session-id 来保留对话上下文。

请记得查看末尾提到的“重要注意事项”列表。它们包含执行成功调用此端点所需的约束和要求的关键信息。

#### 标头

| 名称                                              | 类型  | 说明                  |
| ----------------------------------------------- | --- | ------------------- |
| CONVAI-API-KEY<mark style="color:红色;">\*</mark> | 字符串 | 为每位用户提供的唯一 api-key。 |

#### 请求体

<table><thead><tr><th width="166">名称</th><th>类型</th><th>说明</th></tr></thead><tbody><tr><td>userText<mark style="color:红色;">*</mark></td><td>字符串</td><td>用户与角色交互时的查询或输入。</td></tr><tr><td>charID<mark style="color:红色;">*</mark></td><td>字符串</td><td>用户正在交互的角色的 ID。</td></tr><tr><td>sessionID<mark style="color:红色;">*</mark></td><td>字符串</td><td>用于标识一个对话会话，以保留上下文。</td></tr><tr><td>voiceResponse<mark style="color:红色;">*</mark></td><td>布尔值</td><td>用于生成角色声音的回复音频文件。</td></tr><tr><td>file<mark style="color:红色;">*</mark></td><td>文件</td><td>包含用户查询的音频文件。必须为 WAV 格式且为单声道。</td></tr><tr><td>sample_rate</td><td>字符串</td><td>所发送音频文件的采样率。</td></tr><tr><td>stream</td><td>字符串（“True”或“False”）</td><td>用于启用 SSE 流式传输，使回复能够以实时分块形式传递，而无需等待完整响应。</td></tr></tbody></table>

{% tabs %}
{% tab title="200：OK 角色能够为用户生成回复" %}

```json
{
    "charID": "<请求体中发送的角色 ID>",
    "text": "<语言模型针对该查询生成的回复>",
    "audio": null / "<base64 编码的音频>"
    "sample_rate": null / "<音频的采样率（Hz）>"
    "sessionID": "<您的会话 ID。如果是新会话，则返回新生成的值；否则返回旧值>"
}
```

{% endtab %}

{% tab title="404：未找到。请求的响应生成失败" %}

```json
{
    "charID": "<请求体中发送的角色 ID>",
    "text": "process_failure, error: <错误表示>"
}
```

{% endtab %}

{% tab title="400：Bad Request 输入不正确时" %}

```json
{
    "ERROR": "仅应提供一个；要么是音频文件，要么是用户的字符串查询"
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
重要注意事项：

* 该 API 端点要求请求体只包含一种输入类型（要么是通过 **userText**进行的文本输入，要么是通过 file 提供的音频输入）。同时包含 **两种输入类型或都不提供都会导致错误。**
* 我们严格遵守 OpenAI 的内容政策来使用 API，并期望用户也遵守这些规则，以防止生成有害和不适当的内容。重复违规将导致 API key 被列入黑名单。
* 请注意，请求体应为 **form-data**。这样做是为了在上传音频文件时保持格式一致。
* 将 session ID 值发送为 -1 **会开启一个新的聊天会话**。请在后续的 getResponse 请求中使用返回的 session ID，以确保对话上下文得以保留。
* 发送音频文件时，请确保其具有 **位深度** 至少 **16 位或更高**.
  {% endhint %}

以下是一些示例代码，用于演示该端点的请求格式 -->

仅文本请求： **仅文本：**

{% tabs %}
{% tab title="Python" %}

```python
import requests
import json
import base64

url = "https://api.convai.com/character/getResponse"

payload={
    'userText': '你叫什么名字？',
    'charID': '<您的角色 ID>',
    'sessionID': '-1',
    'voiceResponse': 'True'
}

headers = {
  'CONVAI-API-KEY': '<您的 api key>'
}

response = requests.request("POST", url, headers=headers, data=payload)

data = response.json()

character_response = data["text"]

decode_string = base64.b64decode(data["audio"])

with open('audioResponse.wav','wb') as f:
  f.write(decode_string)
```

{% endtab %}

{% tab title="cURL" %}

```shell
curl --location --request POST 'https://api.convai.com/character/getResponse' \
--header 'CONVAI-API-KEY: <您的 api key>' \
--form 'userText="你叫什么名字？"' \
--form 'charID="<您的角色 ID>"' \
--form 'sessionID="-1"' \
--form 'voiceResponse="True"'
```

{% endtab %}
{% endtabs %}

仅文本请求： **仅音频：**

{% tabs %}
{% tab title="Python" %}

```python
import requests
import json
import base64

url = "https://api.convai.com/character/getResponse"

payload={
		'charID': '<您的角色 ID>',
		'sessionID': '-1',
		'responseLevel': '5',
		'voiceResponse': 'True'}
files=[
  ('file',('audio.wav',open('<音频文件 audio.wav 的路径>','rb'),'audio/wav'))
]
headers = {
  'CONVAI-API-KEY': '<您的 api key>'
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)
data = response.json()

character_response = data["text"]
sessionID = data["sessionID"]

print("会话 ID：", sessionID)
print("回复：", character_response)

decode_string = base64.b64decode(data["audio"])

with open('audioResponse.wav','wb') as f:
  f.write(decode_string)
```

{% endtab %}

{% tab title="cURL" %}

```shell
curl --location --request POST 'https://api.convai.com/character/getResponse' \
--header 'CONVAI-API-KEY: <您的 api key>' \
--form 'charID="<您的角色 ID>"' \
--form 'sessionID="-1"' \
--form 'voiceResponse="True"' \
--form 'file=@"<音频文件 audio.wav 的路径>"'
```

{% endtab %}
{% endtabs %}

## 生成对话选项

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/character/generate-starter-conversation`

Generate Starter Conversation API 实现为服务器发送事件（SSE）。它使用角色背景故事和当前聊天历史来生成接下来与角色可能的后续对话选项。

#### 标头

| 名称                                              | 类型  | 说明                                            |
| ----------------------------------------------- | --- | --------------------------------------------- |
| CONVAI-API-KEY<mark style="color:红色;">\*</mark> | 字符串 | 为每位用户提供的唯一 api-key。登录您的 Convai 账户后，可在钥匙图标下找到。 |

#### 请求体

| 名称        | 类型  | 说明                                    |
| --------- | --- | ------------------------------------- |
| charId    | 字符串 | 要为其生成对话选项的角色 ID。                      |
| sessionId | 字符串 | 要为其生成下一轮对话的会话 ID。将其设为 "-1" 可生成开场对话选项。 |

{% tabs %}
{% tab title="200：OK 返回多个 SSE 事件。" %}

```json
# 输出格式：
# 响应将以服务器发送事件（SSE）的形式流式传输。
# 每个事件都将包含一个 'data' 字段，其中包含一个字符串，即一条聊天建议。
# 单个事件示例：

data: 我很好奇你有史以来最具挑战性的比赛。

# 将收到多个事件，每个事件都包含一条聊天建议。
```

{% endtab %}

{% tab title="401 API 密钥验证失败" %}

```json
{
    "ERROR": "提供的 API key 无效。"
}
```

{% endtab %}
{% endtabs %}

以下是一些示例代码，用于演示该端点的请求格式 -->

{% tabs %}
{% tab title="Python" %}
{% code overflow="wrap" %}

```python
import json
import requests

url = "https://api.convai.com/character/generate-starter-conversation"

headers = { 
    'CONVAI-API-KEY': '<您的 API 密钥>',
}

form_data = { 
    'charId': '<您的角色 ID>',
    'sessionId': '<您的会话 ID>'
}

response = requests.post(url, headers=headers, data=form_data)

print(response.text)
```

{% endcode %}
{% endtab %}

{% tab title="cURL" %}
{% code overflow="wrap" %}

```shell
curl -X POST "https://api.convai.com/character/generate-starter-conversation" \
-H "CONVAI-API-KEY: <您的 API 密钥>" \
-d "charId=<您的角色 ID>" \
-d "sessionId=<您的会话 ID>"
```

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


---

# 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/api-can-kao/core-api-reference/interaction-apis/interaction-api.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.
