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

# 交互 API

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

{% hint style="danger" %}
此 API 仅适用于 Professional 套餐及更高级别的套餐。
{% endhint %}

## 与角色互动

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

用户可以为终端用户实现聊天机器人会话，以便他们与角色交谈。用户可以在发出的 API 请求中维护 session-id，以保留对话上下文。

请务必阅读文末的“重要注意事项”列表，其中包含成功调用此端点所需遵循的限制和要求等关键信息。

#### 请求头

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

#### 请求正文

<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：成功。角色能够生成对用户的回复" %}

```json
{
    "charID": "<character id sent in the request body>",
    "text": "<response generated by the language model to the query>",
    "audio": null / "<base64 encoded audio>"
    "sample_rate": null / "<sample rate of the audio in Hz>"
    "sessionID": "<your session id. In case of a new session, it returns a newly generated value or returns the old one>"
}
```

{% endtab %}

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

```json
{
    "charID": "<character id sent in the request body>",
    "text": "process_failure, error: <error representation>"
}
```

{% endtab %}

{% tab title="400：错误请求。输入有误时返回" %}

```json
{
    "ERROR": "Expecting only one; either an audio file or user's query as a string"
}
```

{% endtab %}
{% endtabs %}

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

* 此 API 端点要求请求正文中只能包含一种输入（文本输入，通过 **userText**，或音频输入，通过 file）。如果同时包含两种输入，或两种都不包含， **则会导致错误。**
* 我们严格遵守 OpenAI 的 API 使用内容政策，并要求用户也遵守相关规则，以防生成有毒和不当内容。屡次违规将导致 API 密钥被列入黑名单。
* 请注意，请求正文应采用 **表单数据**格式。这样可以确保上传音频文件时格式一致。
* 将 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': 'What is your name ?',
    'charID': '<your character id>',
    'sessionID': '-1',
    'voiceResponse': 'True'
}

headers = {
  'CONVAI-API-KEY': '<your 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: <your api key>' \
--form 'userText="What is your name ?"' \
--form 'charID="<your character 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': '<your character id>',
		'sessionID': '-1',
		'responseLevel': '5',
		'voiceResponse': 'True'}
files=[
  ('file',('audio.wav',open('<path to the audio file audio.wav>','rb'),'audio/wav'))
]
headers = {
  'CONVAI-API-KEY': '<your api key>'
}

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

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

print("Session ID: ", sessionID)
print("Response: ", 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: <your api key>' \
--form 'charID="<your character id>"' \
--form 'sessionID="-1"' \
--form 'voiceResponse="True"' \
--form 'file=@"<path to the audio file audio.wav>"'
```

{% endtab %}
{% endtabs %}

## 生成对话选项

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

生成开场对话 API 通过服务器发送事件（SSE）实现。它会根据角色背景故事和当前聊天记录，生成一组可能的后续对话选项。

#### 请求头

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

#### 请求正文

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

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

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

data: 我很好奇，你经历过的最具挑战性的比赛是什么。

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

{% endtab %}

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

```json
{
    "ERROR": "Invalid API key provided."
}
```

{% 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': '<Your-API-Key>',
}

form_data = { 
    'charId': '<Your-Character-ID>',
    'sessionId': '<Your-Session-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: <Your-API-Key>" \
-d "charId=<Your-Character-ID>" \
-d "sessionId=<Your-Session-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.
