# Twigg quickstart Twigg is the AI piece of your stack: a hosted HTTP API that stores each conversation and builds every model call for you. The whole integration is three calls: create a chat once, send each turn's new input (never the history) with the model to use, and read the answer as a stream. Your application keeps the agent loop and executes the tools; Twigg keeps the context, fits it to the model's window, translates it for the provider you name per turn, and records what it sent and what it cost. Practical advice is in [Tips](https://twigg.ai/tips.txt). Base URL: `https://api.twigg.ai`. Every endpoint below is under `/api/v1` and takes one API key as a bearer token. Keys look like `tw_live_…` and are created in the console at https://twigg.ai/dashboard/api-keys. The API is plain HTTP: a client that can read server-sent events is the whole integration, and that is what this guide uses. Official SDKs for TypeScript (`npm install @twigg/sdk`) and Python (`pip install twigg`) take care of parsing the stream, the tool loop and recovering a dropped turn; see [SDKs](https://twigg.ai/docs/sdks.md). For system prompts, saved tools, context budgets and retention settings, see [Context control](https://twigg.ai/docs/context#configure-prompts-tools-and-context). ## 1. Create a chat, once ```bash curl -X POST 'https://api.twigg.ai/api/v1/chats' \ -H "Authorization: Bearer $TWIGG_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "namespace": "acme/proj-7", "title": "Support thread" }' ``` ```json { "id": "01912d4e-9c1a-7b3f-8a21-6f1e2c3d4b5a", "namespace": "acme/proj-7", "title": "Support thread", "description": null, "external_id": null, "user_metadata": {}, "created_at": "2026-09-06T10:24:00Z" } ``` Keep `id`. Everything after this addresses it. `namespace` is a path you choose; it groups chats for listing and selects which instructions, tools and policies apply. It is immutable after creation. Omit it for the organisation-wide scope. This call happens once per conversation. Steps 2 to 4 below are the loop, and they repeat for its whole life: submit what just happened, read the stream, and where a tool was called, submit its result and read the stream again. Steps 2 and 4 are the same endpoint. ## 2. Send what just happened Send the prompt and the model. Never the transcript: Twigg has it. ```bash curl -N -X POST 'https://api.twigg.ai/api/v1/chats/01912d4e-9c1a-7b3f-8a21-6f1e2c3d4b5a/responses' \ -H "Authorization: Bearer $TWIGG_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-5", "input": [ { "type": "prompt", "text": "What changed in the billing module?" } ], "idempotency_key": "billing-turn-1" }' ``` The response is `text/event-stream` by default. Send `"stream": false` to wait for the turn and receive one JSON object instead: the ordered `content`, the reply as `text`, `pending_tool_calls` with their arguments, `stop_reason`, `usage` and `cost`. Pick any `model` from `GET /api/v1/models`; it is a per-request choice, not a property of the chat. Or name a router, such as `telluvian/auto`, and it chooses one of its candidate models for each new prompt. A turn that only returns tool results stays on the model that made the calls, and if the router cannot choose, the turn runs on its fallback model. Every routed turn carries a `model_routed` warning naming the model that ran and why. The router sees the conversation as text to make its choice. Routers and their candidates are listed under `routers` in the [model catalogue](https://api.twigg.ai/v1/catalogue/models.md). ## 3. Read the stream Events arrive in this order. Each is `event: ` followed by `data: `. | Event | Payload | Meaning | |---|---|---| | `run` | chat_id, closed_tool_calls, run_id | Always first: identifiers and tool calls closed by this submission. | | `config_warnings` | warnings | Configuration warnings; emitted second, and may repeat after compaction. | | `translation_warnings` | warnings | Model compatibility warnings before content starts. | | `compacting` | blocks, in_progress_elsewhere | Compaction work the request is waiting for. | | `block_start` | [BlockStart](#blockstart) | | | `delta` | [Delta](#delta) | | | `block_stop` | [BlockStopEventData](#blockstopeventdata) | | | `done` | compaction, cost, cost_currency, model_served, pending_tool_calls, provider_response_id, server_tools, stop_reason, usage | Terminal success. Null cost means settlement is pending; inspect the run later. | | `error` | code, details, hint, message | Terminal failure after the stream has opened. | If `done.pending_tool_calls` is non-empty, the chat is waiting for you to run those tools and send the results back. **With an SDK:** `chat.stream(...)` parses these events for you, and `final()` assembles them into one result: the text, every tool call with its parsed input, usage and cost. Dropping the connection cancels nothing. The turn completes, appends to the ledger and is billed. Read the answer from `/history` on reconnect. To stop a turn, call `POST /api/v1/chats/{chat_id}/abort` with the `run_id` from the `run` event. Naming the run means a late abort can never stop your next turn. ```bash curl -X POST 'https://api.twigg.ai/api/v1/chats/01912d4e-9c1a-7b3f-8a21-6f1e2c3d4b5a/abort?run_id=01912d4f-0a7c-7d21-9e3b-2c4d5e6f7a8b' \ -H "Authorization: Bearer $TWIGG_API_KEY" ``` The stream then ends with `done` and `stop_reason: "aborted"`, and the run reads `cancelled`. Blocks the model had finished are kept, and a text block cut off mid-way is kept where it stopped; a reasoning block or tool call still in progress is dropped. An abort that arrives as the turn is finishing can lose that race, in which case `done` carries the turn's own `stop_reason`. A 409 `no_active_turn` means nothing was running. ## 4. Run the tool, send the result back Same endpoint. A `tool_result` part instead of a `prompt`. ```json { "model": "claude-opus-5", "input": [ { "type": "tool_result", "tool_use_id": "toolu_example", "tool_name": "read_file", "text": "The billing module now records refunds.", "is_error": false, "trust": "customer_data" } ] } ``` `trust` is `trusted`, `customer_data` (default) or `untrusted`. It sets the write-time hygiene limits on the result. It is not an injection defence. Read the stream exactly as in step 3; that is where the loop closes and begins again. Twigg never executes a tool. Every open tool call is closed on your next submission: answered ones with your result, unanswered ones with a tombstone the `run` event names in `closed_tool_calls`. **With an SDK:** `chat.runTools(...)` in TypeScript or `chat.run_tools(...)` in Python runs this loop for you. It calls your tool functions and sends their results back until the model stops calling tools. ## Automation tools and chat bots n8n, Make, Zapier and plain HTTP clients usually want one JSON body per call and already have an id for each conversation, such as a phone number or a Telegram chat id. Address the chat by that id, and you never handle a Twigg chat id at all. ### One call per incoming message `POST /api/v1/chats/external/{external_id}/responses` creates the chat on the first message and reuses it after that. `chat` describes the chat to create; later calls can leave it out. `"stream": false` waits for the turn and returns one JSON object. ```bash curl -N -X POST 'https://api.twigg.ai/api/v1/chats/external/support%3A%2B447700900123/responses' \ -H "Authorization: Bearer $TWIGG_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-5", "input": [ { "type": "prompt", "text": "Where is my order 1042?" } ], "stream": false, "system": "The customer is messaging on WhatsApp. Keep replies short.", "tools": [ { "name": "get_order_status", "description": "Look up an order by number", "input_schema": { "type": "object", "properties": { "order_id": { "type": "string" } }, "required": [ "order_id" ], "additionalProperties": false } } ], "wait_for_pending_tool_calls": 60, "idempotency_key": "n8n-exec-8812", "chat": { "namespace": "acme/support-bot" } }' ``` ```json { "run_id": "01912d51-4e7c-7a90-b3d2-8c5f1a0e6742", "chat_id": "01912d4e-9c1a-7b3f-8a21-6f1e2c3d4b5a", "content": [ { "type": "text", "text": "Let me check that for you." }, { "type": "tool_call", "tool_use_id": "toolu_01ORDER", "name": "get_order_status", "arguments": { "order_id": "1042" } } ], "text": "Let me check that for you.", "pending_tool_calls": [ { "tool_use_id": "toolu_01ORDER", "name": "get_order_status", "arguments": { "order_id": "1042" } } ], "closed_tool_calls": [], "stop_reason": "tool_use", "usage": { "input_tokens": 412, "output_tokens": 58, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0 }, "cost": "0.00211300", "cost_currency": "USD", "model_served": "claude-opus-5", "provider_response_id": null, "server_tools": null, "compaction": null, "config_warnings": [], "translation_warnings": [], "replayed": false } ``` - `text` is the reply, ready to send back to the user. - `pending_tool_calls` lists the tools the model wants run, with their arguments. Run them and send the results the same way: ```json { "model": "claude-opus-5", "input": [ { "type": "tool_result", "tool_use_id": "toolu_01ORDER", "tool_name": "get_order_status", "text": "{\"status\":\"shipped\",\"eta\":\"2026-09-08\"}" } ], "stream": false, "system": "The customer is messaging on WhatsApp. Keep replies short.", "wait_for_pending_tool_calls": 60, "idempotency_key": "n8n-exec-8812-tool-1" } ``` ### External ids - Unique per organisation and case-sensitive. Printable ASCII without spaces, up to 255 characters. `%`, `/`, `\`, `?` and `#` are not allowed, and an id cannot start with `.`: each changes what a URL means, and a client that encodes one imperfectly would address a different chat. - Percent-encode the id in the path: `+447700900123` is `%2B447700900123`. - When two bots can see the same end users, prefix the id (`support:+447700900123`, `sales:+447700900123`). Sending a `namespace` that differs from the existing chat's returns `409 external_id_namespace_mismatch` rather than mixing the two conversations. Leave `namespace` out to skip the check. - **External ids appear in logs.** In the database Twigg keeps only a keyed hash for lookups and a sealed copy to show back to you, but the id travels in URL paths, so it is recorded in request logs. Those logs are not public, but if the id identifies a person (a phone number, an email address) and that matters to you, do not send it raw: send a hash of it, or another opaque value you can map back yourself, such as `wa:` followed by an HMAC of the number. - The same id addresses history, abort, get and delete under `/api/v1/chats/external/{external_id}`. Deleting the chat removes the external id from it straight away and frees the id for a fresh conversation. To create or fetch the chat without sending a message, use `PUT /api/v1/chats/external/{external_id}`. It returns `201` when it created the chat and `200` when it already existed. On an existing chat the body is ignored, so it does not change the title or metadata; only a `namespace` you send is checked. ```bash curl -X PUT 'https://api.twigg.ai/api/v1/chats/external/support%3A%2B447700900123' \ -H "Authorization: Bearer $TWIGG_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "namespace": "acme/support-bot", "title": "WhatsApp +44 7700 900123" }' ``` You can also set `external_id` on `POST /api/v1/chats`. Existing chats cannot be given one later. ### Safe retries and overlapping messages - **Retries.** Send an `idempotency_key` per incoming message, such as the message id from the platform it came from. With `"stream": false`, retrying a request whose turn finished returns the same result again, marked `replayed: true`, instead of running the turn twice. A key is tied to its message: the same key with different `input` gets `409 idempotency_key_reused` rather than an old reply, so a key expression that does not change per message fails loudly. Keys allow letters, digits and `-._~` only, so an external id like `support:+4477…` cannot be used as one as it is. - **Always send a key with `"stream": false`.** A turn that outlasts the request (about 280 seconds) returns `504 response_timeout` but keeps running and is billed. With a key, retrying fetches the result. Without one, an automatic retry would send the message again, so turn retries off for unkeyed requests. - **A second message while a turn runs** gets `409 chat_busy` with a `Retry-After` header. Wait and resend. - **A second message while your tool is still running.** By default it closes the open tool call as abandoned. Set `wait_for_pending_tool_calls` (seconds) to get `409 tool_calls_pending` with `Retry-After` instead, until the result arrives or the call is older than the window. - **A per-request `system` prompt** is appended after your configured instructions and not stored, so send it on every call. It adds to the configured instructions but cannot be stopped from contradicting them: any API key in the organisation can send one, so configured instructions are not a security boundary against your own keys. ## Errors Before the first byte, an ordinary HTTP status with one envelope: ```json { "error": { "code": "payment_required", "message": "…" } } ``` | status | code | when | |---|---|---| | 400 | `bad_request` | Malformed request, including an invalid UUID in a path. | | 401 | `unauthorized` | Missing or invalid key. | | 402 | `payment_required` | The balance cannot cover the turn's input. Top up in the console. | | 404 | `not_found` | Unknown route, chat, run or model. Includes `hint: "https://api.twigg.ai/"` for discovery. | | 409 | `chat_busy` | A run is already open on this chat. Retry after the `Retry-After` header, also in `details.retry_after_secs`. | | 409 | `idempotency_key_reused` | The idempotency key belongs to an earlier run, named in `details.run_id`. With `"stream": false` and the same `input`, a finished run's result is returned instead, with `replayed: true`. | | 409 | `tool_calls_pending` | With `wait_for_pending_tool_calls` set, the submission would close a recent unanswered tool call. Answer it, or retry after `Retry-After`. `details.pending_tool_calls` lists the calls. | | 409 | `external_id_taken` | Creating a chat with an `external_id` another live chat already holds. | | 409 | `external_id_namespace_mismatch` | You sent a `namespace` (or `null`) that differs from the existing chat's. Leaving `namespace` out skips this check. Prefix ids to keep separate bots apart. | | 409 | `provider_key_paused` | Your own provider key for this model is paused and fallback to Twigg is off. `details` names the key. Resume it, or turn on fallback to Twigg for the model, in the console. | | 413 | `payload_too_large` | The body is over the size limit. | | 422 | `validation_error` | A field failed validation, including tools the model cannot take. | | 429 | `rate_limited` | Slow down. | | 500 | `internal_error` | A fault on our side. | | 502 | `external_service_error` | The upstream provider failed. | | 502 | `provider_key_error` | Your own provider key was refused. `details.kind` says why (`auth`, `rate_limited`, …) and `details.key_last4` which key. Fix it, or turn on fallback to Twigg for the model, in the console. | | 503 | `unavailable` | Temporarily out of service. Retry. | | 504 | `response_timeout` | With `"stream": false`, the turn outlasted the request. It continues and is billed. If you sent an `idempotency_key`, retry with it to receive the result; without one, do not resend, because that runs the message again. | The `done.model_served` field is the provider-reported identifier, which can differ from the request's catalogue name: `gpt-5-6-luna` may be served as `gpt-5.6-luna`. Always select request models from the live catalogue's `name` field; do not copy `model_served` into a future request. ### Retrying after a dropped connection **With an SDK:** this is handled for you. Every submission carries an idempotency key, and if the connection drops, `final()` waits for the run to finish and rebuilds its result from the chat's history. Provider rate limits and overloads are retried up to three times before any model stream event is forwarded, with exponential backoff and jitter. `Retry-After` is respected; requests requiring more than 30 seconds of cumulative backoff fail without retrying early. Model-provider failures include a safe category in `error.details.kind` and a `provider_request_id` when available. Failed runs retain these diagnostics in `manifest.error`, with the provider ID also available on the run; raw provider error bodies are not returned. An `idempotency_key` prevents creating another run for the same submission; it does not replay a stream. With `"stream": false`, reusing the key of a finished run returns that run's result again, marked `replayed: true`, so automatic retries are safe. Reusing a key within its 24-hour window returns `409 idempotency_key_reused`, with the original run ID in `details.run_id`. If you received the initial `run` event, you already have that ID. Use `GET /api/v1/runs/{run_id}` to inspect the original run, and `GET /api/v1/chats/{chat_id}/history` to retrieve persisted output. If it is still running, check again later. Reuse the same key when the outcome of submission is uncertain; changing the key can create a second run and another charge. ### Retrying a confirmed failed run A failed run retains submitted input without appending partial assistant output; retry the latest failed run with `POST /api/v1/chats/{chat_id}/responses`, setting `input: []`, `retry_of` to its run ID, and a new `idempotency_key`. Supply the model, any request-level tools and any request `system` prompt again (these can change); the retry creates a separately billed run using the existing history and current configuration. If it fails, use the new run ID for the next retry, and discard partial streamed tool arguments after an `error` event. An API key never earns a 403: a key that may not reach something is refused as a 401. The console's own routes add `forbidden` and `forbidden_requires_admin` for permission failures, which is a session's concern, not a key's. A `validation_error` may carry a `details` object beside `code` and `message`. Its `reason` can be `fixed_content_exceeds_budget` (with `fixed_tokens`, `budget_tokens`), `current_turn_exceeds_capacity` (with `current_turn_tokens`, `capacity_tokens`), or `checkpoint_exceeds_capacity` (with `required_tokens`, `capacity_tokens`). These describe protected content that cannot fit in the available input budget. After the first byte, the same `code` and `message` arrive as the terminal `error` event, since the HTTP status has already been sent. ## Reading back ``` GET /api/v1/chats/{chat_id}/history?after_ordinal=40&include=stubs GET /api/v1/runs/{run_id} GET /api/v1/chats?namespace=acme/proj-7&limit=20 GET /api/v1/namespaces ``` History is oldest first within a page and paged by `ordinal`, the ledger's total order. A call with no cursor opens at the newest end: it returns the last `limit` parts, and you page back with `before_ordinal`. Ordinals are never renumbered and deletes leave gaps: page with the `first_ordinal` and `last_ordinal` you were given, never by arithmetic. `include` is `stubs` (default: attachment descriptors), `full` (base64 bytes, page capped at 20 parts) or `none`. ## What you must not assume - No transcript is ever sent by you. Sending prior messages as new prompts duplicates them in the ledger. - A namespace is a scope, not a permission. Tenancy is your organisation behind the key; separating your own customers is your application's job. - Uppercase in a namespace is a 422, not folded. Use lowercase opaque ids for per-user leaves. - `model` is the catalogue name from `/api/v1/models`, never the provider's own wire string. ## Further reading - Overview and concepts: https://twigg.ai/docs/overview.md - Context control (budgets, retention, compaction): https://twigg.ai/docs/context.md - Full API reference: https://twigg.ai/docs/api.md - SDKs and the configuration CLI: https://twigg.ai/docs/sdks.md - Model catalogue with prices: https://api.twigg.ai/v1/catalogue/models.md ## Sending attachments Use the selected model's `media.user` or `media.tool_result` capability from `GET /api/v1/models` to check formats and limits. Send attachments inline: ```json {"type":"prompt","text":"Describe this image","media":[{"mime":"image/png","data_base64":"","filename":"image.png"}]} ``` Place this part in the response request's `input` array. Do not prefix the base64 with a data URI. Unsupported new media on configured models returns HTTP 422 without appending the turn. When switching models, retained historical media may instead be omitted with translation warnings; see [context](context.md).