> ## Documentation Index
> Fetch the complete documentation index at: https://www.krea.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Bots API

> 通过 HTTP 与你的 Krea bot 交互：列出 bot、开始聊天、发送消息、轮询回复、回答问题，以及停止或重试一轮。

使用 Bots API，可以从你自己的应用中使用 Krea bot。API 密钥能做的事与其所属的人在 bot 聊天中能做的事相同：通过 API 发送的消息会启动同样的 bot 轮次，并与在 Krea 应用中发送的消息出现在同一个聊天中。请求和响应使用 snake\_case 格式的 JSON 字段。

| 端点 | 用途 |
| - | - |
| [`GET /bots`](https://www.krea.ai/docs/api-reference/bots/list-bots) | 列出你可以使用的 bot。 |
| [`GET /bots/{bot_id}`](https://www.krea.ai/docs/api-reference/bots/get-bot) | 读取一个 bot。 |
| [`GET /bots/chats`](https://www.krea.ai/docs/api-reference/bots/list-bot-chats) | 按从新到旧列出你所在的聊天。 |
| [`POST /bots/chats`](https://www.krea.ai/docs/api-reference/bots/start-bot-chat) | 与一个 bot 开启私聊，或与多个 bot 和队友开启群聊。 |
| [`GET /bots/chats/{chat_id}`](https://www.krea.ai/docs/api-reference/bots/get-bot-chat) | 读取一个聊天及其一页消息。 |
| [`DELETE /bots/chats/{chat_id}`](https://www.krea.ai/docs/api-reference/bots/delete-bot-chat) | 为所有成员删除聊天。 |
| [`GET /bots/chats/{chat_id}/messages`](https://www.krea.ai/docs/api-reference/bots/read-new-bot-chat-messages) | 轮询新消息和聊天状态。 |
| [`POST /bots/chats/{chat_id}/messages`](https://www.krea.ai/docs/api-reference/bots/send-bot-chat-message) | 向聊天发送消息。 |
| [`POST /bots/chats/{chat_id}/members`](https://www.krea.ai/docs/api-reference/bots/add-bot-chat-members) | 向聊天添加 bot 和队友。 |
| [`DELETE /bots/chats/{chat_id}/members/{member_id}`](https://www.krea.ai/docs/api-reference/bots/remove-bot-chat-member) | 将某人移出群聊，或自己退出群聊。 |
| [`DELETE /bots/chats/{chat_id}/bots/{bot_id}`](https://www.krea.ai/docs/api-reference/bots/remove-bot-from-chat) | 将 bot 移出群聊。 |
| [`POST /bots/chats/{chat_id}/questions/{question_id}/answer`](https://www.krea.ai/docs/api-reference/bots/answer-bot-question) | 回答 bot 正在等待的问题。 |
| [`POST /bots/chats/{chat_id}/stop`](https://www.krea.ai/docs/api-reference/bots/stop-bot-chat) | 停止在聊天中工作的 bot。 |
| [`POST /bots/chats/{chat_id}/retry`](https://www.krea.ai/docs/api-reference/bots/retry-bot-chat) | 恢复因工作区计算单位用完而被暂停的 bot。 |

bot 在后台工作。发送后会立即返回一个 `cursor`。之后用该 cursor 轮询聊天，直到 bot 完成、提出问题、失败或被停止。没有流式传输，也没有 webhook。

## 认证与访问

向 `https://api.krea.ai` 发送的每个请求都要带上 `Authorization: Bearer KREA_API_KEY`。Bots API 使用与其他[公开 API](https://www.krea.ai/docs/cn/developers/api-keys-and-billing.md) 相同的密钥。

密钥所属的工作区和人员决定了你能看到什么：

* **Bot：** 你自己的 bot，以及共享给工作区的 bot。
* **聊天：** 仅限你所在的聊天。你不在其中的聊天会返回 `404`，即使对同一工作区的队友也是如此。

Bots 需要 Max 或更高套餐，或者 Bots 邀请。否则，除 stop 外的所有端点都会返回 `403`：

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "error": "Bots needs a Max plan or higher. Upgrade at https://www.krea.ai/pricing to work with bots.",
  "code": "entitlement_denied",
  "required_plan": "Max"
}
```

尚未开放 Bots 的账号会收到带有 `code: "bots_unavailable"` 的 `403`。stop 永远不会因套餐被拒绝，因此正在运行的工作始终可以停止。

每个聊天响应都包含一个 `url`，可在 Krea 应用中打开该聊天。通过 API 发送的消息会在应用中标记为 **via API**，读取时会带有 `"via": "API"`。

## 计费

> [!NOTE]
>
> bot 轮次使用工作区的计算单位余额，与 Krea 应用中的轮次完全相同。它们**不**使用 API 余额。为 bot 或聊天设置的用量上限同样适用。

即使工作区计算单位已用完，发送也会被接受。读取聊天时会看到暂停状态。请参阅[计算单位用完与用量上限](#out-of-compute-units-and-usage-limits)。

## 发送消息并轮询回复

先在环境中设置 `KREA_API_KEY`。可选择使用 `curl` 和 `jq` 的 Bash、使用 `requests` 的 Python，或使用内置 `fetch` 的 Node.js。你至少需要一个 bot。请在 Krea 应用中创建 bot；API 不会创建 bot。

**1. 列出你的 bot**

`GET /bots` 返回你可以使用的 bot。选择一个 bot 的 `id`。

**2. 开始聊天**

使用 `bot_id`、`title` 和 `message` 调用 `POST /bots/chats`。保存返回的 `chat_id` 和 `cursor`。

**3. 轮询回复**

使用 `cursor` 和 `wait=30` 调用 `GET /bots/chats/{chat_id}/messages`。用每次响应中的新 `cursor` 重复调用，直到 `status` 不再是 `working`。

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
set -euo pipefail
: "${KREA_API_KEY:?Set your Krea API key}"
API=https://api.krea.ai
AUTH="Authorization: Bearer $KREA_API_KEY"

BOT_ID=$(curl --fail-with-body --silent --show-error --max-time 60 \
  "$API/bots" -H "$AUTH" | jq -er '.bots[0].id')

START=$(curl --fail-with-body --silent --show-error --max-time 60 \
  "$API/bots/chats" \
  -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg bot_id "$BOT_ID" '{
    bot_id: $bot_id,
    title: "Coffee mug campaign",
    message: "Create three square product images for a ceramic coffee mug on a neutral studio background. Use no text or logos."
  }')")

CHAT_ID=$(printf '%s' "$START" | jq -er '.chat_id')
CURSOR=$(printf '%s' "$START" | jq -er '.cursor')
printf '%s' "$START" | jq -r '.url'

DEADLINE=$((SECONDS + 300))

while (( SECONDS < DEADLINE )); do
  STATE=$(curl --fail-with-body --silent --show-error --max-time 45 --get \
    "$API/bots/chats/$CHAT_ID/messages" \
    -H "$AUTH" \
    --data-urlencode "cursor=$CURSOR" \
    --data-urlencode "wait=30")
  CURSOR=$(printf '%s' "$STATE" | jq -er '.cursor')
  printf '%s' "$STATE" | jq '{status, text, media, files, question, error}'
  STATUS=$(printf '%s' "$STATE" | jq -er '.status')
  if [[ "$STATUS" != "working" ]]; then
    if [[ "$STATUS" == "done" ]]; then exit 0; fi
    printf 'Chat is %s. Open %s\n' "$STATUS" "$(printf '%s' "$STATE" | jq -r '.url')" >&2
    exit 1
  fi
done

printf 'Wait budget exhausted; the bot keeps working. Resume with chat_id=%s cursor=%s\n' \
  "$CHAT_ID" "$CURSOR" >&2
exit 1
```

```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
import json
import os
import time
import requests

api = "https://api.krea.ai"
headers = {"Authorization": f"Bearer {os.environ['KREA_API_KEY']}"}

response = requests.get(f"{api}/bots", headers=headers, timeout=60)
response.raise_for_status()
bots = response.json()["bots"]
if not bots:
    raise SystemExit("No bots yet. Create one in the Krea app first.")

response = requests.post(
    f"{api}/bots/chats",
    headers=headers,
    json={
        "bot_id": bots[0]["id"],
        "title": "Coffee mug campaign",
        "message": "Create three square product images for a ceramic coffee mug on a neutral studio background. Use no text or logos.",
    },
    timeout=60,
)
response.raise_for_status()
start = response.json()
chat_id, cursor = start["chat_id"], start["cursor"]
print(start["url"])

deadline = time.monotonic() + 300
while True:
    if time.monotonic() > deadline:
        raise TimeoutError(
            "Wait budget exhausted; the bot keeps working. Resume with "
            f"chat_id={chat_id} cursor={cursor}"
        )
    response = requests.get(
        f"{api}/bots/chats/{chat_id}/messages",
        headers=headers,
        params={"cursor": cursor, "wait": 30},
        timeout=45,
    )
    response.raise_for_status()
    state = response.json()
    cursor = state["cursor"]
    print(state["text"])
    if state["status"] != "working":
        break

print(json.dumps({key: state.get(key) for key in ("status", "media", "files", "question", "error")}, indent=2))
if state["status"] != "done":
    raise RuntimeError(f"Chat is {state['status']}. Open {state['url']}")
```

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
import { performance } from "node:perf_hooks";

const token = process.env.KREA_API_KEY;
if (!token) throw new Error("Set your Krea API key");
const api = "https://api.krea.ai";

async function call(method, path, { body, query, timeoutMs = 60_000 } = {}) {
  const url = new URL(`${api}${path}`);
  for (const [key, value] of Object.entries(query ?? {})) url.searchParams.set(key, value);
  const response = await fetch(url, {
    method,
    headers: {
      Authorization: `Bearer ${token}`,
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    ...(body ? { body: JSON.stringify(body) } : {}),
    signal: AbortSignal.timeout(timeoutMs),
  });
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  }
  return response.json();
}

const { bots } = await call("GET", "/bots");
if (bots.length === 0) throw new Error("No bots yet. Create one in the Krea app first.");

const start = await call("POST", "/bots/chats", {
  body: {
    bot_id: bots[0].id,
    title: "Coffee mug campaign",
    message: "Create three square product images for a ceramic coffee mug on a neutral studio background. Use no text or logos.",
  },
});
const chatId = start.chat_id;
let cursor = start.cursor;
console.log(start.url);

const deadline = performance.now() + 300_000;
let state;
while (true) {
  if (performance.now() > deadline) {
    throw new Error(
      `Wait budget exhausted; the bot keeps working. Resume with chat_id=${chatId} cursor=${cursor}`,
    );
  }
  state = await call("GET", `/bots/chats/${chatId}/messages`, {
    query: { cursor, wait: 30 },
    timeoutMs: 45_000,
  });
  cursor = state.cursor;
  console.log(state.text);
  if (state.status !== "working") break;
}

const { status, media, files, question, error } = state;
console.log(JSON.stringify({ status, media, files, question, error }, null, 2));
if (status !== "done") throw new Error(`Chat is ${status}. Open ${state.url}`);
```

Python 需使用 `pip install requests` 安装 `requests`。Node.js 需使用 Node.js 22+，并将示例保存为 `example.mjs`。

这些示例发送一条消息，并最多轮询五分钟。遇到 HTTP 错误时会停止，聊天以 `done` 之外的任何状态结束时会报错退出。它们从不自动重试发送。如果发送请求超时，第一次请求可能已经发布了消息。请使用相同的 `idempotency_key` 重复请求，或在再次发送前先读取聊天。

等待时间用完后，bot 仍会继续工作。保存聊天 ID 和 cursor，以便稍后继续轮询。

### 开始聊天

`POST /bots/chats` 返回 `201`，并包含 `chat_id`、`title`、`message_id`、`cursor`、`bots` 和 `url`。

| 字段 | 行为 |
| - | - |
| `bot_id` | 来自 `GET /bots` 的 bot UUID。传入 `bot_id`、`bot_ids` 或两者都传。 |
| `bot_ids` | 最多 20 个 bot UUID，用于群聊。请参阅[群聊](#group-chats)。 |
| `member_ids` | 可选，最多 50 个工作区队友的用户 ID。请参阅[群聊](#group-chats)。 |
| `title` | 可选，最多 80 个字符。带标题时，请求会单独开启一个新聊天。只有一个 bot、没有成员且没有标题时，会打开你与该 bot 的私聊；如果已存在则复用。 |
| `message` | 可选的第一条消息，最多 8,000 个字符。它会启动 bot 的第一轮。 |
| `attachments` | 可选，最多 10 个。此处附件需要配合 `message`。请参阅[附件](#attachments)。 |
| `idempotency_key` | 可选，最多 200 个字符。请参阅[安全地重试发送](#retry-a-send-safely)。 |

不带 `message` 开启的新聊天会让 bot 打招呼。这句问候也是一轮 bot 轮次，并按轮次计费。打开已存在的私聊会返回该聊天。不带 `message` 时，`message_id` 为 `null`。

### 发送后续消息

`POST /bots/chats/{chat_id}/messages` 向现有聊天发布消息，并返回带有新 `cursor` 的 `202`：

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
SENT=$(curl --fail-with-body --silent --show-error \
  "https://api.krea.ai/bots/chats/$CHAT_ID/messages" \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Make a landscape variation of the first image."}')

# Poll with this new cursor.
CURSOR=$(printf '%s' "$SENT" | jq -er '.cursor')
```

`text` 最多 8,000 个字符。发送 `text`、至少一个附件，或两者都发送。

### 安全地重试发送

发送会启动一轮计费的 bot 轮次，因此误发两次会花费两倍。`POST /bots/chats` 和 `POST /bots/chats/{chat_id}/messages` 接受可选的 `idempotency_key`，这是你自定义的用于标识请求的字符串：

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{ "text": "Make a landscape variation of the first image.", "idempotency_key": "order-1842-variation" }
```

如果请求超时或响应丢失，请使用相同的 key 重复请求。API 会返回第一次的聊天和消息，而不会再次发送。key 的作用范围是你本人。每条要发送的消息都使用新的 key，即使文本相同也一样。

### 轮询新消息

`GET /bots/chats/{chat_id}/messages` 接受两个查询参数：

| 参数 | 行为 |
| - | - |
| `cursor` | 上一次响应中的 `cursor`，只返回此后发生的内容。不传时，从你自己最新的消息之后开始读取。 |
| `wait` | 在 bot 完成或提问之前保持请求的秒数，取值 `0` 到 `30`。默认为 `0`，即立即返回。 |

请让 HTTP 客户端的超时时间长于 `wait`。响应描述的是 `cursor` 之后的聊天：

| 字段 | 含义 |
| - | - |
| `status` | bot 在一轮中途时为 `working`，bot 等待 `question` 的回答时为 `needs_input`，之后为 `done`、`failed` 或 `stopped`。 |
| `finished` | 当 `status` 为 `done`、`failed` 或 `stopped` 时为 `true`。 |
| `timed_out` | 当 bot 仍在工作时 `wait` 已用完，或未读内容超出单次响应容量时为 `true`。请用 `cursor` 再次读取。 |
| `messages` | 新的可见消息，从旧到新。每条都有 `id`、`created_at`、`author`、`text`、`attachments`，不是在 Krea 中写的还会有 `via`。 |
| `text` | bot 新消息的文本，拼接在一起。 |
| `media` | bot 发布的图像、视频和音频。每项都有 `url`，并可能包含 `uri`、`name`、`mime_type`、`width` 和 `height`。Krea 文件以签名链接提供。 |
| `files` | bot 发布的其他文件，格式与 `media` 相同。 |
| `question` | 当 bot 等待回答时出现。请参阅[问题卡片](#question-cards)。 |
| `error` | `{ code, message }`，当 `status` 为 `failed` 时出现。 |
| `out_of_compute_bot_ids` | 因工作区计算单位用完而在此聊天中被暂停的 bot。 |
| `working`, `progress` | 进行中的轮次及其新步骤。 |
| `cursor` | 传给下一次读取。 |
| `url` | Krea 应用中该聊天的链接。 |

每次响应只包含 `cursor` 之后的新内容。如果需要完整回复，请在多次读取之间汇总 `text`、`media` 和 `files`。

如需读取聊天历史，请使用 `GET /bots/chats/{chat_id}`。它返回一页消息，从最新的一页开始，`limit` 为 `1` 到 `100`（默认 `30`）。将返回的 `before` 值作为 `before` 传入即可向前翻页。

## 附件

`POST /bots/chats` 和 `POST /bots/chats/{chat_id}/messages` 每条消息最多接受 10 个附件。每个附件为 `{ url, name?, content_type? }`：

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "text": "Use this photo as the reference.",
  "attachments": [
    { "url": "https://example.com/mug.jpg", "name": "mug.jpg", "content_type": "image/jpeg" },
    { "url": "file:550e8400-e29b-41d4-a716-446655440000" }
  ]
}
```

`url` 接受 `http(s)` URL，例如 [`POST /assets`](https://www.krea.ai/docs/api-reference/assets/upload-an-asset) 返回的素材 URL，或你有权访问的 Krea Files URI `file:<uuid>`。`name` 和 `content_type` 是最多 255 个字符的可选字符串。缺失或无权访问的 Krea 文件会返回带有 `code: "attachment_not_found"` 的 `404`。

## 问题卡片

bot 可能会在继续之前停下来提问。此时读取会返回 `status: "needs_input"` 和一个 `question`：

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "status": "needs_input",
  "finished": false,
  "question": {
    "id": "toolu_01A2b3C4d5",
    "bot_id": "3f0c8a52-1d7e-4c3b-9a65-2b8e4f1d7c90",
    "kind": "question",
    "text": "Which cup?",
    "options": ["Mug", "Tumbler"],
    "answerable": true
  }
}
```

使用 `POST /bots/chats/{chat_id}/questions/{question_id}/answer` 回答，然后用回答返回的 `cursor` 再次轮询：

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl --fail-with-body --silent --show-error \
  "https://api.krea.ai/bots/chats/$CHAT_ID/questions/$QUESTION_ID/answer" \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"answer": "Mug"}'
```

要发送的内容取决于 `kind`：

| `kind` | 回答 |
| - | - |
| `question` | 自由文本，或原样发送 `options` 中的一项。当 bot 一次问了多个问题时，`text` 会为它们编号，`options` 为空。按顺序为每个问题提供一个回答，发送 `{ "answers": [...] }`，最多 10 个。 |
| `approval` | `Go ahead` 或 `Not now`。其他任何文本都不算批准，会作为反馈发给 bot。 |
| `permission`, `cost_confirm` | `Allow once`、`Always allow` 或 `Don't allow`。其他文本返回 `400`。 |
| 其他类型 | `answerable` 为 `false`。只能在 Krea 应用的聊天中回答。请打开聊天的 `url`。 |

回答已经回答过的问题会返回 `404`。

## 群聊

包含多个 bot、包含队友或带有标题的聊天就是群聊。使用 `bot_ids` 和可选的 `member_ids` 开启群聊：

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl --fail-with-body --silent --show-error \
  "https://api.krea.ai/bots/chats" \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg lead "$LEAD_BOT_ID" --arg second "$SECOND_BOT_ID" --arg teammate "$TEAMMATE_ID" '{
    bot_ids: [$lead, $second],
    member_ids: [$teammate],
    title: "Coffee mug campaign",
    message: "Plan a three-image campaign for a coffee mug."
  }')"
```

规则与 Krea 应用中相同：

* 每个 bot 都必须是你可以使用的，否则请求返回 `404`。
* `member_ids` 中的每个人都必须属于该工作区，否则请求返回 `400`。
* 私有 bot 只与其所有者一起工作。包含其他人的聊天需要共享给工作区的 bot，否则请求返回 `400`。

队友的用户 ID 会以 `people` 出现在你与他们共同参与的聊天中，可从 `GET /bots/chats` 和 `GET /bots/chats/{chat_id}` 获取。

### 谁来回答

`bot_ids` 中的第一个 bot 主导聊天，`lead_bot_id` 标明是哪一个。没有点名任何 bot 的消息会发给主导 bot。要和某个特定 bot 对话，请在消息中写 `@` 加上它的名字，例如 `@Thumby make the logo bigger`。

每个响应都会说明与哪个 bot 相关。每条消息带有 `author.id` 和 `author.name`，`question` 带有 `bot_id`，`working` 中的每一项也带有 `bot_id`。轮询时，`status` 会一直保持 `working`，直到聊天中的所有 bot 都停下来。

### 添加和移除 bot 与成员

`POST /bots/chats/{chat_id}/members` 接受 `bot_ids`、`member_ids` 或两者，并返回当前在聊天中的成员：`chat_id`、`title`、`kind`、`lead_bot_id`、`bots`、`people` 和 `url`。聊天中的任何人都可以添加。向私聊添加成员会把它变成群聊。已经在聊天中的 bot 和成员保持不变。

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl --fail-with-body --silent --show-error \
  "https://api.krea.ai/bots/chats/$CHAT_ID/members" \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg bot "$BOT_ID" '{bot_ids: [$bot]}')"
```

移除不需要请求体，返回 `{ "chat_id": "...", "removed": { "kind": "bot", "id": "..." }, "left": false }`：

| 请求 | 谁可以调用 |
| - | - |
| `DELETE /bots/chats/{chat_id}/bots/{bot_id}` | 发起聊天的人，或 bot 的所有者。 |
| `DELETE /bots/chats/{chat_id}/members/{member_id}` | 发起聊天的人，可移除聊天中的其他任何人。 |
| `DELETE /bots/chats/{chat_id}/members/{your_user_id}` | 除发起聊天的人以外的任何人。你会退出聊天，`left` 为 `true`。 |

其他人会收到 `403`（`forbidden`）。发起聊天的人不能退出该聊天，私聊中的 bot 也不能被移除；两种情况都返回 `400`。请改为删除聊天。移除 bot 或成员会停止该 bot 正在进行的工作，或 bot 为该成员进行的工作。

### 删除聊天

`DELETE /bots/chats/{chat_id}` 为所有成员删除私聊或群聊，并返回 `{ "chat_id": "...", "deleted": true }`。只有发起聊天的人或工作区管理员可以删除；聊天中的其他人会收到 `403`（`forbidden`）。聊天中所有正在进行的 bot 轮次和助手都会停止。此后已删除的聊天会返回 `404`，再次与同一 bot 开启私聊会创建一个新聊天。

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl --fail-with-body --silent --show-error -X DELETE \
  "https://api.krea.ai/bots/chats/$CHAT_ID" \
  -H "Authorization: Bearer $KREA_API_KEY"
```

## 停止一轮

`POST /bots/chats/{chat_id}/stop` 会停止聊天中所有正在工作的 bot 及其助手。两个请求体字段都是可选的：

| 字段 | 行为 |
| - | - |
| `bot_id` | 只停止这个 bot。在群聊中，其他 bot 会继续工作，在此期间响应仍为 `status: "working"`。 |
| `cursor` | 开始读取的 cursor，与轮询时相同。 |

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl --fail-with-body --silent --show-error \
  "https://api.krea.ai/bots/chats/$CHAT_ID/stop" \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg cursor "$CURSOR" '{cursor: $cursor}')"
```

响应是与轮询格式相同的聊天状态，通常为 `status: "stopped"` 和 `finished: true`。

## 计算单位用完与用量上限

即使工作区没有剩余计算单位，或用量上限已用尽，发送也会返回 `202`。该轮不会运行。读取聊天时会看到暂停状态：

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "status": "failed",
  "finished": true,
  "error": { "code": "out_of_compute", "message": "..." },
  "out_of_compute_bot_ids": ["3f0c8a52-1d7e-4c3b-9a65-2b8e4f1d7c90"]
}
```

| `error.code` | 含义 |
| - | - |
| `out_of_compute` | 工作区计算单位已用完。被暂停的 bot 列在 `out_of_compute_bot_ids` 中。 |
| `bot_usage_limit` | bot 已达到其用量上限。 |
| `chat_usage_limit` | 聊天已达到其用量上限。 |

这三种是计费暂停，不是故障。其他代码表示某一轮失败：`refused`、`busy`、`timeout`、`provider`、`server`、`context`、`claude_billing` 和 `unknown`。

添加计算单位后，调用 `POST /bots/chats/{chat_id}/retry` 恢复被暂停的 bot，或发送一条新消息。retry 不需要请求体，有 bot 恢复时返回 `{ "retried": true, "out_of_compute": false }`。余额仍为空时，它不执行任何操作，返回 `{ "retried": false, "out_of_compute": true }`。retry 之后请再次轮询。

## 错误

端点错误使用 `{ "error": "...", "code": "..." }`。只有 `error` 是必需的。发送被接受后失败的轮次，会在成功的读取中显示为 `status: "failed"`。

| HTTP 状态 | 含义 |
| - | - |
| `400` | JSON 请求体格式错误，或聊天拒绝的请求（`bad_request`），例如聊天未返回过的 cursor，或与问题不匹配的回答。 |
| `401` | 缺少认证或认证无效。 |
| `403` | 工作区套餐不包含 Bots（`entitlement_denied`，附带 `required_plan`），或该账号尚未开放 Bots（`bots_unavailable`）。或者你无权对聊天做此更改（`forbidden`），例如移除一个既不属于你、也不是你拉进你所发起聊天的 bot。 |
| `404` | bot、聊天或问题不存在或无权访问（`not_found`），包括你不在其中的聊天。或者 Krea 文件附件不存在或无权访问（`attachment_not_found`）。 |
| `409` | 请求期间聊天发生了变化，或停止操作尚未完成（`conflict`）。请稍后重试。 |
| `422` | 输入无效：`{ "error": "Validation failed", "details": [...] }`。未知的请求体字段会被拒绝。 |
| `429` | 请求过多（`rate_limited`）。 |

`429` 限制仅用于防范失控的客户端：每位用户每分钟 60 次写入和 600 次读取。写入包括开始、发送、回答、停止、重试、删除，以及添加或移除 bot 和成员。使用 `wait=30` 的长轮询远低于读取上限。

## 此版本不包含

* 创建、编辑或删除 bot，以及 bot 设置。请在 Krea 应用中管理 bot。
* vault。
* Webhook 和流式传输。请改用 `wait` 轮询。
* 重命名或归档聊天。请在 Krea 应用中操作。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.