> ## 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 のボットとやり取りします。ボットの一覧表示、チャットの開始、メッセージの送信、返信のポーリング、質問への回答、ターンの停止や再試行。

Bots API を使うと、独自のアプリケーションから Krea のボットを操作できます。API キーは、ボットチャットでその持ち主ができることと同じことができます。API から送信したメッセージは、Krea アプリから送信したメッセージと同じボットのターンを開始し、同じチャットに表示されます。リクエストとレスポンスでは snake\_case の JSON フィールドを使います。

| エンドポイント | 用途 |
| - | - |
| [`GET /bots`](https://www.krea.ai/docs/api-reference/bots/list-bots) | 利用できるボットを一覧表示します。 |
| [`GET /bots/{bot_id}`](https://www.krea.ai/docs/api-reference/bots/get-bot) | 1 つのボットを読み取ります。 |
| [`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) | ボットとのダイレクトチャット、または複数のボットやチームメイトとのグループチャットを開きます。 |
| [`GET /bots/chats/{chat_id}`](https://www.krea.ai/docs/api-reference/bots/get-bot-chat) | チャットとそのメッセージの 1 ページを読み取ります。 |
| [`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) | チャットにボットとチームメイトを追加します。 |
| [`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) | グループチャットからボットを削除します。 |
| [`POST /bots/chats/{chat_id}/questions/{question_id}/answer`](https://www.krea.ai/docs/api-reference/bots/answer-bot-question) | ボットが待っている質問に回答します。 |
| [`POST /bots/chats/{chat_id}/stop`](https://www.krea.ai/docs/api-reference/bots/stop-bot-chat) | チャットで作業中のボットを停止します。 |
| [`POST /bots/chats/{chat_id}/retry`](https://www.krea.ai/docs/api-reference/bots/retry-bot-chat) | ワークスペースのコンピュートユニットが不足して保留されたボットを再開します。 |

ボットはバックグラウンドで作業します。送信すると、すぐに `cursor` が返ります。その後、ボットが完了する、質問する、失敗する、または停止されるまで、その cursor でチャットをポーリングします。ストリーミングや Webhook はありません。

## 認証とアクセス

`https://api.krea.ai` へのすべてのリクエストで `Authorization: Bearer KREA_API_KEY` を送信します。Bots API は、他の[公開 API](https://www.krea.ai/docs/ja/developers/api-keys-and-billing.md) と同じキーを使います。

キーのワークスペースとユーザーによって、表示できる内容が決まります。

* **ボット:** 自分のボットと、ワークスペースで共有されているボット。
* **チャット:** 自分が参加しているチャットのみ。参加していないチャットは、同じワークスペースのチームメイトであっても `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 はプランを理由に拒否されることはないため、実行中の作業は常に停止できます。

すべてのチャットレスポンスには、Krea アプリでチャットを開く `url` が含まれます。API から送信したメッセージは Krea アプリで **via API** と表示され、読み返すと `"via": "API"` が付いています。

## 請求

> [!NOTE]
>
> ボットのターンは、Krea アプリのターンとまったく同じく、ワークスペースのコンピュートユニット残高を使用します。API 残高は**使用しません**。ボットやチャットに設定された使用量上限も適用されます。

ワークスペースのコンピュートユニットがなくなっていても、送信は受け付けられます。保留はチャットを読み取ったときにわかります。[コンピュートユニット不足と使用量上限](#out-of-compute-units-and-usage-limits)を参照してください。

## メッセージを送信して返信をポーリングする

まず環境に `KREA_API_KEY` を設定します。`curl` と `jq` を使う Bash、`requests` を使う Python、組み込みの `fetch` を使う Node.js から選びます。ボットが少なくとも 1 つ必要です。ボットは Krea アプリで作成してください。API ではボットを作成できません。

**1. ボットを一覧表示する**

`GET /bots` は利用できるボットを返します。ボットの `id` を 1 つ選びます。

**2. チャットを開始する**

`bot_id`、`title`、`message` を指定して `POST /bots/chats` を呼び出します。返された `chat_id` と `cursor` を保存します。

**3. 返信をポーリングする**

`cursor` と `wait=30` を指定して `GET /bots/chats/{chat_id}/messages` を呼び出します。`status` が `working` でなくなるまで、各レスポンスの新しい `cursor` で繰り返します。

```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` として保存します。

これらの例は 1 つのメッセージを送信し、最大 5 分間ポーリングします。HTTP エラーで停止し、チャットが `done` 以外のステータスで終わった場合はエラーで終了します。送信を自動で再試行することはありません。送信リクエストがタイムアウトした場合、最初のリクエストでメッセージが投稿されている可能性があります。同じ `idempotency_key` で繰り返すか、再送信する前にチャットを読み取ってください。

待機時間の上限に達しても、ボットは作業を続けます。チャット ID と cursor を保存しておくと、後でポーリングを再開できます。

### チャットを開始する

`POST /bots/chats` は、`chat_id`、`title`、`message_id`、`cursor`、`bots`、`url` とともに `201` を返します。

| フィールド | 動作 |
| - | - |
| `bot_id` | `GET /bots` で取得したボットの UUID。`bot_id`、`bot_ids`、またはその両方を渡します。 |
| `bot_ids` | グループチャット用のボット UUID (最大 20 個)。[グループチャット](#group-chats)を参照してください。 |
| `member_ids` | 任意。ワークスペースのチームメイトのユーザー ID (最大 50 個)。[グループチャット](#group-chats)を参照してください。 |
| `title` | 任意。最大 80 文字。タイトルを指定すると、リクエストは独立した新しいチャットを開きます。ボットが 1 つで、メンバーとタイトルがない場合は、そのボットとのダイレクトチャットを開き、すでに存在する場合はそれを再利用します。 |
| `message` | 任意の最初のメッセージ。最大 8,000 文字。ボットの最初のターンを開始します。 |
| `attachments` | 任意。最大 10 個。ここでは添付ファイルに `message` が必要です。[添付ファイル](#attachments)を参照してください。 |
| `idempotency_key` | 任意。最大 200 文字。[送信を安全に再試行する](#retry-a-send-safely)を参照してください。 |

`message` なしで新しいチャットを開くと、ボットがあいさつします。このあいさつはボットのターンであり、ターンとして課金されます。既存のダイレクトチャットを開くと、そのチャットが返ります。`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`、1 つ以上の添付ファイル、またはその両方を送信します。

### 送信を安全に再試行する

送信すると課金対象のボットのターンが始まるため、誤って 2 回送信すると 2 回分のコストがかかります。`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" }
```

リクエストがタイムアウトした場合やレスポンスが失われた場合は、同じキーで繰り返します。API は再送信せずに、最初のチャットとメッセージを返します。キーのスコープはユーザーごとです。送信したいメッセージごとに、同じテキストであっても新しいキーを使ってください。

### 新しいメッセージをポーリングする

`GET /bots/chats/{chat_id}/messages` は 2 つのクエリパラメータを受け付けます。

| パラメータ | 動作 |
| - | - |
| `cursor` | 前のレスポンスの `cursor`。これ以降に起きたことだけが返ります。指定しない場合、読み取りは自分の最新メッセージの後から始まります。 |
| `wait` | ボットが完了するか何かを質問するまでリクエストを保持する秒数 (`0` から `30`)。デフォルトは `0` で、すぐに応答します。 |

HTTP クライアントのタイムアウトは `wait` より長くしてください。レスポンスは `cursor` 以降のチャットを表します。

| フィールド | 意味 |
| - | - |
| `status` | ボットがターンの途中なら `working`、ボットが `question` への回答を待っていれば `needs_input`、その後は `done`、`failed`、`stopped` のいずれか。 |
| `finished` | `status` が `done`、`failed`、`stopped` になると `true`。 |
| `timed_out` | ボットがまだ作業中に `wait` が終了した場合、または 1 回のレスポンスに収まらない未読がある場合に `true`。`cursor` で再度読み取ります。 |
| `messages` | 新しく表示されたメッセージ (古い順)。それぞれ `id`、`created_at`、`author`、`text`、`attachments` を持ち、Krea 以外で書かれた場合は `via` も持ちます。 |
| `text` | ボットの新しいメッセージのテキストを連結したもの。 |
| `media` | ボットが投稿した画像、動画、音声。各項目には `url` があり、`uri`、`name`、`mime_type`、`width`、`height` を含む場合があります。Krea のファイルは署名付きリンクで届きます。 |
| `files` | ボットが投稿したその他のファイル。形式は `media` と同じです。 |
| `question` | ボットが回答を待っているときに存在します。[質問カード](#question-cards)を参照してください。 |
| `error` | `{ code, message }`。`status` が `failed` のときに存在します。 |
| `out_of_compute_bot_ids` | ワークスペースのコンピュートユニット不足により、このチャットで保留されているボット。 |
| `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` は、1 メッセージあたり最大 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` には、[`POST /assets`](https://www.krea.ai/docs/api-reference/assets/upload-an-asset) が返すアセット URL などの `http(s)` URL、またはアクセス可能な Krea Files の URI `file:<uuid>` を指定できます。`name` と `content_type` は最大 255 文字の任意の文字列です。存在しない、またはアクセスできない Krea ファイルは、`code: "attachment_not_found"` 付きの `404` を返します。

## 質問カード

ボットは続行する前に止まって質問することがあります。その場合、読み取りは `question` とともに `status: "needs_input"` を返します。

```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` のいずれかをそのまま送信します。ボットが複数の質問を一度にした場合、`text` に番号が振られ、`options` は空になります。それぞれへの回答を順番に入れた `{ "answers": [...] }` を送信します (最大 10 個)。 |
| `approval` | `Go ahead` または `Not now`。それ以外のテキストは承認になりません。フィードバックとしてボットに届きます。 |
| `permission`, `cost_confirm` | `Allow once`、`Always allow`、`Don't allow` のいずれか。それ以外のテキストは `400` を返します。 |
| その他の種類 | `answerable` は `false` です。回答できるのは Krea アプリのチャットだけです。チャットの `url` を開いてください。 |

すでに回答済みの質問に回答すると `404` が返ります。

## グループチャット

複数のボット、チームメイト、またはタイトルがあるチャットはグループチャットです。`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 アプリと同じです。

* すべてのボットが利用可能なものである必要があります。そうでない場合、リクエストは `404` を返します。
* `member_ids` のすべての人がワークスペースに所属している必要があります。そうでない場合、リクエストは `400` を返します。
* 非公開ボットはオーナーとしか作業しません。他の人がいるチャットには、ワークスペースで共有されているボットが必要です。そうでない場合、リクエストは `400` を返します。

チームメイトのユーザー ID は、共有しているチャットの `people` として、`GET /bots/chats` と `GET /bots/chats/{chat_id}` に表示されます。

### 誰が回答するか

`bot_ids` の最初のボットがチャットをリードし、`lead_bot_id` がそのボットを示します。どのボットも指名していないメッセージはリードボットに届きます。特定のボットに話しかけるには、メッセージに `@` とボット名を書きます。例: `@Thumby make the logo bigger`。

すべてのレスポンスで、どのボットに関するものかがわかります。各メッセージには `author.id` と `author.name`、`question` には `bot_id`、`working` の各エントリには `bot_id` が含まれます。ポーリングでは、チャット内のすべてのボットが待機状態になるまで `status` は `working` のままです。

### ボットと人を追加・削除する

`POST /bots/chats/{chat_id}/members` は `bot_ids`、`member_ids`、またはその両方を受け取り、現在チャットにいるメンバー (`chat_id`、`title`、`kind`、`lead_bot_id`、`bots`、`people`、`url`) を返します。チャットの誰でも追加できます。ダイレクトチャットに追加すると、グループチャットになります。すでにチャットにいるボットや人はそのままです。

```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}` | チャットを開始した人、またはボットのオーナー。 |
| `DELETE /bots/chats/{chat_id}/members/{member_id}` | チャットを開始した人 (チャット内の他の人に対して)。 |
| `DELETE /bots/chats/{chat_id}/members/{your_user_id}` | チャットを開始した人以外の誰でも。チャットから退出し、`left` は `true` になります。 |

それ以外の人には `403` (`forbidden`) が返ります。チャットを開始した人はそのチャットから退出できず、ダイレクトチャットのボットは削除できません。どちらも `400` を返します。代わりにチャットを削除してください。ボットや人を削除すると、そのボットが行っていた作業、またはボットがその人のために行っていた作業が停止します。

### チャットを削除する

`DELETE /bots/chats/{chat_id}` は、ダイレクトチャットまたはグループチャットを参加者全員から削除し、`{ "chat_id": "...", "deleted": true }` を返します。削除できるのは、チャットを開始した人またはワークスペース管理者だけです。チャット内のそれ以外の人には `403` (`forbidden`) が返ります。チャットで作業中のすべてのボットのターンとヘルパーが停止します。以降、削除されたチャットは `404` を返し、同じボットとのダイレクトチャットを再び開くと新しいチャットが始まります。

```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` は、チャットで作業中のすべてのボットとそのヘルパーを停止します。ボディの 2 つのフィールドはどちらも任意です。

| フィールド | 動作 |
| - | - |
| `bot_id` | このボットだけを停止します。グループチャットでは他のボットは作業を続け、その間レスポンスは `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` | ワークスペースのコンピュートユニットが不足しました。保留されたボットは `out_of_compute_bot_ids` に一覧表示されます。 |
| `bot_usage_limit` | ボットが使用量上限に達しました。 |
| `chat_usage_limit` | チャットが使用量上限に達しました。 |

この 3 つは請求による保留であり、障害ではありません。その他のコードはターンの失敗を示します: `refused`、`busy`、`timeout`、`provider`、`server`、`context`、`claude_billing`、`unknown`。

コンピュートユニットを追加したら、`POST /bots/chats/{chat_id}/retry` を呼び出して保留中のボットを再開するか、新しいメッセージを送信します。retry はボディなしで呼び出し、ボットが再開すると `{ "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_unavailable`)。または、チャットに対するこの変更が許可されていない (`forbidden`)。たとえば、自分が所有しておらず、自分が開始したチャットに自分で追加したわけでもないボットを削除する場合です。 |
| `404` | ボット、チャット、質問が存在しないかアクセスできない (`not_found`)。参加していないチャットも含みます。または Krea のファイル添付が存在しないかアクセスできない (`attachment_not_found`)。 |
| `409` | リクエスト中にチャットが変更された、または停止がまだ完了していない (`conflict`)。少し待ってから再試行してください。 |
| `422` | 無効な入力: `{ "error": "Validation failed", "details": [...] }`。不明なボディフィールドは拒否されます。 |
| `429` | リクエストが多すぎます (`rate_limited`)。 |

`429` の制限は暴走したクライアントを防ぐためだけのもので、ユーザーあたり 1 分間に書き込み 60 回、読み取り 600 回です。書き込みとは、開始、送信、回答、停止、再試行、削除、ボットや人の追加・削除です。`wait=30` でのロングポーリングは、読み取り制限を大きく下回ります。

## このバージョンに含まれないもの

* ボットの作成、編集、削除、およびボットの設定。ボットは Krea アプリで管理してください。
* vault。
* Webhook とストリーミング。代わりに `wait` でポーリングしてください。
* チャットの名前変更やアーカイブ。Krea アプリで行ってください。


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