> 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/character-crafting-apis/action-api.md).

# 动作 API

参考面向现有客户端保留的基于字符串的 Action API 工作流，并查找面向新集成的 Agentic Actions 和 Live API 替代方案。

本页面保留了基于字符串的 Action API 工作流，供现有客户端调用 `POST /character/getResponse`.

{% hint style="warning" %}
**自 2026 年 8 月 26 日起，不建议在新的动作集成中使用。** 请使用 [Agentic Actions](https://docs.convai.com/api-docs/zh/convai-playground/character-customization/agentic-actions.md) 来编写角色契约，然后使用 [Connect API](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/connect-api.md) 或当前版本的 SDK 来声明并接收结构化动作。现有客户端在迁移期间可以继续使用本页面。
{% endhint %}

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

如果对话能够推动角色行为，并赋予角色操控环境的能力，就会变得更加引人入胜。Action API 通过允许你定义角色可以执行的各种动作来实现这一点。这些动作通常与环境中可用的对象相关联。

要充分利用 Action API，需要了解一些事项。这里将介绍一些指导你编写这些内容的原则。

本教程将通过代码示例和注释，展示如何有效使用 Action API。

### 设置

要顺利跟随本教程操作，需要先完成以下准备工作。创建一个 Colab 笔记本即可，无需安装任何软件包。

```python
# 导入几个库
import base64
import json
import requests

# 在此填写你的角色 ID
CHAR_ID = "<your character id>"

# 在此设置你的 Convai API 密钥
CONVAI_KEY = "<your convai api key>"

# 此 URL 用于生成动作和响应
action_url = "https://api.convai.com/character/getResponse"

# 用于更新背景故事的 URL
url = "https://api.convai.com/character/update"
```

### Action API 的组成部分

在环境中生成动作所需的构成要素如下：

1. 动作
2. 对象
3. 角色
4. 背景故事

现在让我们详细讨论这些内容。这里先列出它们；设置时，请返回相应章节查看。

### 对象

与动作一样，用户也需要了解有关对象的一些细节。如果有多个相似对象，最好为它们编号。例如，不要写“5 把椅子”，而应写“椅子#1”“椅子#2”等。如果需要角色为你拿来某个特定对象，也应明确提出，例如：“把 3 号椅子拿给我”。你还可以提及与该对象交互的动作，以提高效果。

下面提供两个定义对象的示例，并说明如何更好地定义对象。

```python
## 基本定义
# 定义对象最简单的方法如下：使用 convert()
# 函数可直接将其转换为 API 所需的格式； 
# 如何调用 API，请参阅 API 参考文档。

# objects = [{"name": "Mojito","description": "说真的，这是一杯无酒精莫吉托。"},
#            {"name": "Tequilla Sunrise","description": "不是我个人最喜欢的饮品。"},
#            {"name": "White Russian","description": "The Dude 最喜欢的饮品。"},
#            {"name": "A Jukebox","description": "一台有很多歌曲的点唱机。"},
#            {"name": "Freshly sliced oranges","description": "一些清爽开胃的新鲜橙子。"},
#            {"name": "Fish and Chips","description": "经典的炸鱼薯条。"},
#            {"name": "Some Samosas","description": "美味的印度小吃。"},
#            {"name": "Book","description": "用餐时消磨时间的一本书。"},
#            ]

## 高级（更佳）定义
# 更好的对象定义方式，是在名称中也注明可以对它们执行 
# 哪些动作。请记住，"name" 和 "description" 字段中都不要使用分号 ;， 
# 因为 API 调用会使用分号作为分隔符，
# 使用分号可能导致行为不稳定。
#
# 这样定义对象可能更复杂，但根据我们的经验， 
# 这能显著提升效果。"Play, Serve, Give, Call Cab"
objects = [{"name": "莫吉托（可执行：Served|不可执行：Played, Given）","description": "终于来了一杯无酒精莫吉托。"},
           {"name": "龙舌兰日出（可执行：Served|不可执行：Played, Given）","description": "这不是我最喜欢的饮品。"},
           {"name": "白俄罗斯（可执行：Served|不可执行：Played, Given）","description": "The Dude 最喜欢的饮品。"},
           {"name": "点唱机（可执行：Played|不可执行：Served, Given）","description": "一台曲库丰富的点唱机。"},
           {"name": "鲜切橙子（可执行：Served|不可执行：Played, Given）","description": "来点清爽的橙子，让你精神一振。"},
           {"name": "炸鱼薯条（可执行：Served|不可执行：Played, Given）","description": "经典的炸鱼薯条。"},
           {"name": "咖喱角（可执行：Served|不可执行：Played, Given）","description": "美味的印度小吃。"},
           {"name": "书（可执行：Given|不可执行：Played, Served）","description": "用餐时读本书，打发一下时间。"},
           ]
```

### 背景故事

需要注意的是，背景故事也会影响 Action API 的表现。要想有效生成动作，最重要的是在背景故事中加入关于物品、角色和动作的信息。（你也可以将这些信息放入知识库，但我们建议用背景故事来提供。）下面我们会举例说明。你可以看到，我们会说明场景中有哪些物品，并介绍一些相关信息。如果可以，也最好在这里补充一些环境信息。

关于角色本身的信息可以放在知识库中。

```python
backstory = """一位酒保角色，可以帮助完成各种任务。 

他可以提供几种饮品：
1. 莫吉托
2. 龙舌兰日出
3. 白俄罗斯

周围还有一些物品，包括：
1. 一台点唱机
2. 一碗花生
3. 鲜切橙子
4. 炸鱼薯条
5. 一些咖喱角
6. 一本书

这个角色可以对上述物品执行一些动作。 
对于用户要求的任务，角色可以同意或拒绝执行。 
同样，如果用户要求对其他物品执行某项操作，只有在相应动作 
适用于可用物品时，角色才能执行。用户提出请求时，角色还可以执行 Call Cab
动作。"""

# 另外，如果你想修改并自行尝试，下面提供了更新背景故事的代码
#。
payload = json.dumps({
  "charID": CHAR_ID,
  "backstory": backstory,
})
headers = {
  'CONVAI-API-KEY': CONVAI_KEY,
  'Content-Type': 'application/json'
}

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

```

### 动作

动作是此 API 的核心。要创建有效的动作，需要确保这些动作适用范围广且简单。尽量不要让动作过于具体。例如，名为“Show”的动作会比“Demonstrate”更有效。同样，“Moves To”或“Go To”也会比“Walks To”或“Runs To”更有效，因为前一组在某种意义上比后一组更通用。

定义动作时还应保持大小写一致。如果选择使用小写，就将所有动作都写成小写，依此类推。要获得最佳效果，动作还必须符合角色背景。

可以通过 API 调用发送动作，也可以在 Playground UI 中设置。这里演示通过 API 调用设置。如果要通过 UI 设置，请前往 <https://convai.com/pipeline/dashboard/character> 点击 Actions 按钮，添加动作，最后点击 `Update` 按钮。

```python
actions = "Play, Serve, Give, Call Cab"
```

### 角色

提供场景中出现的角色。你可以添加两个以上的角色；例如，如果场景是在有多人的餐厅中，可以在此添加所有人。

请确保将角色的重要信息放入知识库或背景故事中，不要把任何真正重要的信息放在简介（bio）中。

```python
characters = [{"name": "用户", "bio": "使用 Action API 的人。"},
              {"name": "Action-API-Doc-Bot", "bio": "在 Convai 帮助编写文档。"},]
```

### API 参考

现在，我们可以通过 API 参考以及调用 Action API 的各种方式来结束本教程。

```python
userText = input("输入你的命令：")

payload={'userText': userText,
  'charID': CHAR_ID,
  'sessionID': '-1',
  'voiceResponse': 'false',
  'actions': actions,
  'classification':'multistep', 
  'objects': json.dumps(objects),
  'characters': json.dumps(characters),
  }

files = []

headers = {
  'CONVAI-API-KEY': CONVAI_KEY 
}

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

response = json.loads(response.text)

print(json.dumps(response, indent=4))

# 响应正文
# {
#     "userQuery": "Can you give me a drink?",
#     "charID": "17e9cbde-abcd-11ed-9d60-42010a80000d",
#     "sessionID": "4ba18da3db1627953bf04f3a4021779f",
#     "text": "Sure! What would you like? I have Mojito, Tequilla Sunrise, and White Russian available.",
#     "response": "Sure! What would you like? I have Mojito, Tequilla Sunrise, and White Russian available.",
#     "actionSequence": " \nServe Mojito\n Serve Tequilla Sunrise\n Serve White Russian"
# }
```


---

# 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/character-crafting-apis/action-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.
