> ## 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.

# API Bots

> Parla con i tuoi bot Krea via HTTP: elenca i bot, avvia una chat, invia messaggi, controlla le risposte, rispondi alle domande e ferma o riprova un turno.

Usa l'API Bots per lavorare con i tuoi bot Krea dalla tua applicazione. Una chiave API fa ciò che fa la sua persona in una chat con un bot: un messaggio inviato tramite l'API avvia lo stesso turno del bot e compare nella stessa chat di uno inviato dall'app Krea. Richieste e risposte usano campi JSON in snake\_case.

| Endpoint | Scopo |
| - | - |
| [`GET /bots`](https://www.krea.ai/docs/api-reference/bots/list-bots) | Elenca i bot che puoi usare. |
| [`GET /bots/{bot_id}`](https://www.krea.ai/docs/api-reference/bots/get-bot) | Legge un bot. |
| [`GET /bots/chats`](https://www.krea.ai/docs/api-reference/bots/list-bot-chats) | Elenca le chat di cui fai parte, dalla più recente. |
| [`POST /bots/chats`](https://www.krea.ai/docs/api-reference/bots/start-bot-chat) | Apre una chat diretta con un bot, o una chat di gruppo con più bot e colleghi. |
| [`GET /bots/chats/{chat_id}`](https://www.krea.ai/docs/api-reference/bots/get-bot-chat) | Legge una chat con una pagina dei suoi messaggi. |
| [`DELETE /bots/chats/{chat_id}`](https://www.krea.ai/docs/api-reference/bots/delete-bot-chat) | Elimina una chat per tutti i partecipanti. |
| [`GET /bots/chats/{chat_id}/messages`](https://www.krea.ai/docs/api-reference/bots/read-new-bot-chat-messages) | Controlla i nuovi messaggi e lo stato della chat. |
| [`POST /bots/chats/{chat_id}/messages`](https://www.krea.ai/docs/api-reference/bots/send-bot-chat-message) | Invia un messaggio in una chat. |
| [`POST /bots/chats/{chat_id}/members`](https://www.krea.ai/docs/api-reference/bots/add-bot-chat-members) | Aggiunge bot e colleghi a una chat. |
| [`DELETE /bots/chats/{chat_id}/members/{member_id}`](https://www.krea.ai/docs/api-reference/bots/remove-bot-chat-member) | Rimuove una persona da una chat di gruppo, o la abbandona. |
| [`DELETE /bots/chats/{chat_id}/bots/{bot_id}`](https://www.krea.ai/docs/api-reference/bots/remove-bot-from-chat) | Rimuove un bot da una chat di gruppo. |
| [`POST /bots/chats/{chat_id}/questions/{question_id}/answer`](https://www.krea.ai/docs/api-reference/bots/answer-bot-question) | Risponde a una domanda in attesa di un bot. |
| [`POST /bots/chats/{chat_id}/stop`](https://www.krea.ai/docs/api-reference/bots/stop-bot-chat) | Ferma i bot che lavorano in una chat. |
| [`POST /bots/chats/{chat_id}/retry`](https://www.krea.ai/docs/api-reference/bots/retry-bot-chat) | Riprende i bot bloccati perché il workspace ha esaurito le unità di calcolo. |

I bot lavorano in background. Un invio risponde subito con un `cursor`. Poi interroghi la chat con quel cursor finché i bot non finiscono, fanno una domanda, falliscono o vengono fermati. Non ci sono streaming né webhook.

## Autenticazione e accesso

Invia `Authorization: Bearer KREA_API_KEY` con ogni richiesta a `https://api.krea.ai`. L'API Bots usa le stesse chiavi del resto dell'[API pubblica](https://www.krea.ai/docs/it/developers/api-keys-and-billing.md).

Il workspace e la persona della chiave determinano ciò che puoi vedere:

* **Bot:** i tuoi bot e i bot condivisi con il workspace.
* **Chat:** solo le chat di cui fai parte. Una chat di cui non fai parte restituisce `404`, anche per i colleghi dello stesso workspace.

Bots richiede un piano Max o superiore, oppure un invito a Bots. Senza, ogni endpoint tranne stop restituisce `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"
}
```

Un account per cui Bots non è ancora disponibile riceve `403` con `code: "bots_unavailable"`. Stop non viene mai rifiutato per il piano, quindi il lavoro in corso si può sempre fermare.

Ogni risposta relativa a una chat include un `url` che apre la chat nell'app Krea. I messaggi inviati tramite l'API sono contrassegnati lì con **via API**, e riportano `"via": "API"` quando li rileggi.

## Fatturazione

> [!NOTE]
>
> I turni dei bot usano il saldo di unità di calcolo del workspace, esattamente come i turni nell'app Krea. **Non** usano il saldo API. Si applicano anche i limiti di utilizzo impostati su un bot o su una chat.

Un invio viene accettato anche quando il workspace ha esaurito le unità di calcolo. Il blocco compare quando leggi la chat. Consulta [Unità di calcolo esaurite e limiti di utilizzo](#out-of-compute-units-and-usage-limits).

## Invia un messaggio e attendi la risposta

Imposta prima `KREA_API_KEY` nel tuo ambiente. Scegli Bash con `curl` e `jq`, Python con `requests` o Node.js con `fetch` integrato. Ti serve almeno un bot. Crea i bot nell'app Krea; l'API non li crea.

**1. Elenca i tuoi bot**

`GET /bots` restituisce i bot che puoi usare. Scegli l'`id` di un bot.

**2. Avvia una chat**

`POST /bots/chats` con `bot_id`, un `title` e un `message`. Salva il `chat_id` e il `cursor` restituiti.

**3. Attendi la risposta**

Chiama `GET /bots/chats/{chat_id}/messages` con `cursor` e `wait=30`. Ripeti con il nuovo `cursor` di ogni risposta finché `status` non è più `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}`);
```

Per Python, installa `requests` con `pip install requests`. Per Node.js, usa Node.js 22+ e salva l'esempio come `example.mjs`.

Questi esempi inviano un messaggio e controllano per un massimo di cinque minuti. Si fermano in caso di errori HTTP ed escono con un errore quando la chat termina con uno stato diverso da `done`. Non ripetono mai un invio automaticamente. Se una richiesta di invio va in timeout, la prima richiesta potrebbe aver pubblicato il messaggio. Ripetila con la stessa `idempotency_key`, oppure leggi la chat prima di inviare di nuovo.

Quando il tempo di attesa si esaurisce, il bot continua a lavorare. Salva l'ID della chat e il cursor per riprendere il controllo in seguito.

### Avviare una chat

`POST /bots/chats` restituisce `201` con `chat_id`, `title`, `message_id`, `cursor`, `bots` e `url`.

| Campo | Comportamento |
| - | - |
| `bot_id` | UUID di un bot da `GET /bots`. Passa `bot_id`, `bot_ids` o entrambi. |
| `bot_ids` | Fino a 20 UUID di bot, per una chat di gruppo. Consulta [Chat di gruppo](#group-chats). |
| `member_ids` | Facoltativo, fino a 50 ID utente di colleghi del workspace. Consulta [Chat di gruppo](#group-chats). |
| `title` | Facoltativo, fino a 80 caratteri. Con un titolo, la richiesta apre una nuova chat a sé. Con un solo bot, nessun membro e nessun titolo, apre la tua chat diretta con il bot e la riutilizza se esiste già. |
| `message` | Primo messaggio facoltativo, fino a 8.000 caratteri. Avvia il primo turno del bot. |
| `attachments` | Facoltativo, fino a 10. Qui gli allegati richiedono un `message`. Consulta [Allegati](#attachments). |
| `idempotency_key` | Facoltativo, fino a 200 caratteri. Consulta [Ripetere un invio in sicurezza](#retry-a-send-safely). |

Una nuova chat aperta senza `message` fa salutare il bot. Quel saluto è un turno del bot e viene fatturato come tale. Aprire una chat diretta che esiste già restituisce quella chat. Senza `message`, `message_id` è `null`.

### Inviare un messaggio successivo

`POST /bots/chats/{chat_id}/messages` pubblica un messaggio in una chat esistente e restituisce `202` con un nuovo `cursor`:

```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` accetta fino a 8.000 caratteri. Invia `text`, almeno un allegato o entrambi.

### Ripetere un invio in sicurezza

Un invio avvia un turno del bot a pagamento, quindi inviare due volte per errore costa il doppio. `POST /bots/chats` e `POST /bots/chats/{chat_id}/messages` accettano una `idempotency_key` facoltativa, una stringa scelta da te che identifica la richiesta:

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

Se una richiesta va in timeout o la risposta si perde, ripetila con la stessa chiave. L'API restituisce la prima chat e il primo messaggio invece di inviare di nuovo. Le chiavi sono legate a te. Usa una chiave nuova per ogni messaggio che intendi inviare, anche se ha lo stesso testo.

### Controllare i nuovi messaggi

`GET /bots/chats/{chat_id}/messages` accetta due parametri di query:

| Parametro | Comportamento |
| - | - |
| `cursor` | Il `cursor` della risposta precedente, così viene restituito solo ciò che è successo da allora. Senza, la lettura parte dopo il tuo messaggio più recente. |
| `wait` | Secondi per cui trattenere la richiesta finché i bot non finiscono o chiedono qualcosa, da `0` a `30`. Il valore predefinito è `0`, che risponde subito. |

Mantieni il timeout del tuo client HTTP più lungo di `wait`. La risposta descrive la chat a partire da `cursor`:

| Campo | Significato |
| - | - |
| `status` | `working` mentre un bot è a metà turno, `needs_input` quando un bot attende una risposta a `question`, poi `done`, `failed` o `stopped`. |
| `finished` | `true` quando `status` è `done`, `failed` o `stopped`. |
| `timed_out` | `true` quando `wait` è scaduto mentre un bot stava ancora lavorando, o quando c'è più contenuto non letto di quanto ne contenga una risposta. Leggi di nuovo con `cursor`. |
| `messages` | Nuovi messaggi visibili, dal più vecchio. Ognuno ha `id`, `created_at`, `author`, `text`, `attachments` e `via` quando non è stato scritto in Krea. |
| `text` | Il testo dei nuovi messaggi dei bot, unito. |
| `media` | Immagini, video e audio pubblicati dai bot. Ogni elemento ha un `url` e può includere `uri`, `name`, `mime_type`, `width` e `height`. I file Krea arrivano come link firmato. |
| `files` | Altri file pubblicati dai bot, con la stessa struttura di `media`. |
| `question` | Presente quando un bot attende una risposta. Consulta [Schede domanda](#question-cards). |
| `error` | `{ code, message }`, presente quando `status` è `failed`. |
| `out_of_compute_bot_ids` | Bot bloccati in questa chat perché il workspace ha esaurito le unità di calcolo. |
| `working`, `progress` | I turni in corso e i loro nuovi passaggi. |
| `cursor` | Passalo alla lettura successiva. |
| `url` | Link alla chat nell'app Krea. |

Ogni risposta contiene solo ciò che è nuovo rispetto a `cursor`. Raccogli `text`, `media` e `files` tra le letture se ti serve la risposta completa.

Per leggere invece la cronologia di una chat, usa `GET /bots/chats/{chat_id}`. Restituisce una pagina di messaggi, a partire dalla più recente, con `limit` da `1` a `100` (predefinito `30`). Passa il valore `before` restituito come `before` per tornare indietro di pagina.

## Allegati

`POST /bots/chats` e `POST /bots/chats/{chat_id}/messages` accettano fino a 10 allegati per messaggio. Ognuno è `{ 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` accetta un URL `http(s)`, come l'URL dell'asset restituito da [`POST /assets`](https://www.krea.ai/docs/api-reference/assets/upload-an-asset), o un URI Krea Files `file:<uuid>` a cui hai accesso. `name` e `content_type` sono stringhe facoltative di massimo 255 caratteri. Un file Krea mancante o non accessibile restituisce `404` con `code: "attachment_not_found"`.

## Schede domanda

Un bot può fermarsi e chiedere prima di continuare. La lettura restituisce allora `status: "needs_input"` con una `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
  }
}
```

Rispondi con `POST /bots/chats/{chat_id}/questions/{question_id}/answer`, poi controlla di nuovo con il `cursor` restituito dalla risposta:

```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"}'
```

Cosa inviare dipende da `kind`:

| `kind` | Risposta |
| - | - |
| `question` | Testo libero, o una delle `options` inviata esattamente. Quando il bot ha posto più domande insieme, `text` le numera e `options` è vuoto. Invia `{ "answers": [...] }` con una risposta per ciascuna, in ordine, fino a 10. |
| `approval` | `Go ahead` o `Not now`. Qualsiasi altro testo non approva. Arriva al bot come feedback. |
| `permission`, `cost_confirm` | `Allow once`, `Always allow` o `Don't allow`. Altro testo restituisce `400`. |
| Altri tipi | `answerable` è `false`. Si può rispondere solo dalla chat nell'app Krea. Apri l'`url` della chat. |

Rispondere a una domanda a cui è già stata data risposta restituisce `404`.

## Chat di gruppo

Una chat con più bot, con colleghi o con un titolo è una chat di gruppo. Avviane una con `bot_ids` e, facoltativamente, `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."
  }')"
```

Le regole sono quelle applicate dall'app Krea:

* Ogni bot deve essere uno che puoi usare, altrimenti la richiesta restituisce `404`.
* Ogni persona in `member_ids` deve far parte del workspace, altrimenti la richiesta restituisce `400`.
* Un bot privato funziona solo con il suo proprietario. Una chat con altre persone richiede bot condivisi con il workspace, altrimenti la richiesta restituisce `400`.

Gli ID utente dei colleghi compaiono come `people` nelle chat che condividi con loro, in `GET /bots/chats` e `GET /bots/chats/{chat_id}`.

### Chi risponde

Il primo bot in `bot_ids` guida la chat, e `lead_bot_id` lo indica. Un messaggio che non nomina alcun bot va al bot guida. Per rivolgerti a un bot specifico, scrivi `@` e il suo nome nel messaggio, ad esempio `@Thumby make the logo bigger`.

Ogni risposta indica a quale bot si riferisce. Ogni messaggio riporta `author.id` e `author.name`, una `question` riporta `bot_id`, e ogni voce in `working` riporta `bot_id`. Durante il polling, `status` resta `working` finché tutti i bot della chat non sono a riposo.

### Aggiungere e rimuovere bot e persone

`POST /bots/chats/{chat_id}/members` accetta `bot_ids`, `member_ids` o entrambi, e restituisce chi è ora nella chat: `chat_id`, `title`, `kind`, `lead_bot_id`, `bots`, `people` e `url`. Chiunque nella chat può aggiungere. Aggiungere a una chat diretta la trasforma in una chat di gruppo. Bot e persone già presenti restano come sono.

```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]}')"
```

La rimozione non richiede corpo e restituisce `{ "chat_id": "...", "removed": { "kind": "bot", "id": "..." }, "left": false }`:

| Richiesta | Chi può chiamarla |
| - | - |
| `DELETE /bots/chats/{chat_id}/bots/{bot_id}` | La persona che ha avviato la chat, o il proprietario del bot. |
| `DELETE /bots/chats/{chat_id}/members/{member_id}` | La persona che ha avviato la chat, per chiunque altro vi partecipi. |
| `DELETE /bots/chats/{chat_id}/members/{your_user_id}` | Chiunque tranne la persona che ha avviato la chat. Abbandoni la chat, e `left` è `true`. |

Chiunque altro riceve `403` (`forbidden`). La persona che ha avviato una chat non può abbandonarla, e il bot di una chat diretta non può essere rimosso; entrambi i casi restituiscono `400`. Elimina invece la chat. Rimuovere un bot o una persona ferma il lavoro che il bot stava facendo, o il lavoro che i bot facevano per quella persona.

### Eliminare una chat

`DELETE /bots/chats/{chat_id}` elimina una chat diretta o di gruppo per tutti i partecipanti e restituisce `{ "chat_id": "...", "deleted": true }`. Solo la persona che ha avviato la chat o un amministratore del workspace può eliminarla; chiunque altro nella chat riceve `403` (`forbidden`). Ogni turno di bot e ogni helper in corso nella chat si ferma. Da quel momento una chat eliminata restituisce `404`, e riaprire una chat diretta con lo stesso bot ne avvia una nuova.

```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"
```

## Fermare un turno

`POST /bots/chats/{chat_id}/stop` ferma tutti i bot che lavorano nella chat e i loro helper. Entrambi i campi del corpo sono facoltativi:

| Campo | Comportamento |
| - | - |
| `bot_id` | Ferma solo questo bot. In una chat di gruppo gli altri bot continuano a lavorare, e la risposta mantiene `status: "working"` finché lo fanno. |
| `cursor` | Il cursor da cui leggere, come in un polling. |

```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}')"
```

La risposta è lo stato della chat con la stessa struttura di un polling, di solito con `status: "stopped"` e `finished: true`.

## Unità di calcolo esaurite e limiti di utilizzo

Un invio restituisce `202` anche quando il workspace non ha più unità di calcolo, o quando un limite di utilizzo è esaurito. Il turno non viene eseguito. Il blocco compare quando leggi la chat:

```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` | Significato |
| - | - |
| `out_of_compute` | Il workspace ha esaurito le unità di calcolo. I bot bloccati sono elencati in `out_of_compute_bot_ids`. |
| `bot_usage_limit` | Il bot ha raggiunto il suo limite di utilizzo. |
| `chat_usage_limit` | La chat ha raggiunto il suo limite di utilizzo. |

Questi tre sono blocchi di fatturazione, non guasti. Altri codici indicano un turno non riuscito: `refused`, `busy`, `timeout`, `provider`, `server`, `context`, `claude_billing` e `unknown`.

Dopo aver aggiunto unità di calcolo, chiama `POST /bots/chats/{chat_id}/retry` per riprendere i bot bloccati, oppure invia un nuovo messaggio. Retry non richiede corpo e restituisce `{ "retried": true, "out_of_compute": false }` quando un bot riprende. Finché il saldo resta a zero non fa nulla e restituisce `{ "retried": false, "out_of_compute": true }`. Controlla di nuovo dopo un retry.

## Errori

Gli errori degli endpoint usano `{ "error": "...", "code": "..." }`. Solo `error` è obbligatorio. Un turno che fallisce dopo che l'invio è stato accettato compare invece come `status: "failed"` in una lettura riuscita.

| Stato HTTP | Significato |
| - | - |
| `400` | Corpo JSON non valido, o una richiesta che la chat rifiuta (`bad_request`), come un cursor non restituito dalla chat o una risposta non adatta alla domanda. |
| `401` | Autenticazione mancante o non valida. |
| `403` | Bots non è incluso nel piano del workspace (`entitlement_denied`, con `required_plan`), o non è disponibile per questo account (`bots_unavailable`). Oppure non puoi apportare questa modifica alla chat (`forbidden`), come rimuovere un bot che non possiedi né hai aggiunto a una chat che hai avviato. |
| `404` | Bot, chat o domanda mancante o non accessibile (`not_found`), incluse le chat di cui non fai parte. Oppure un allegato file Krea mancante o non accessibile (`attachment_not_found`). |
| `409` | La chat è cambiata durante la richiesta, o un arresto non si è ancora concluso (`conflict`). Riprova tra un momento. |
| `422` | Input non valido: `{ "error": "Validation failed", "details": [...] }`. I campi sconosciuti nel corpo vengono rifiutati. |
| `429` | Troppe richieste (`rate_limited`). |

Il limite `429` serve solo a proteggere da client fuori controllo: 60 scritture e 600 letture al minuto per utente. Le scritture sono avvio, invio, risposta, stop, retry, eliminazione e aggiunta o rimozione di bot e persone. Il long polling con `wait=30` resta ben al di sotto del limite di lettura.

## Non inclusi in questa versione

* Creare, modificare o eliminare bot, e le impostazioni dei bot. Gestisci i bot nell'app Krea.
* Il vault.
* Webhook e streaming. Usa invece il polling con `wait`.
* Rinominare o archiviare una chat. Fallo nell'app Krea.


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