# Twigg: overview Twigg is the AI piece of your stack: a hosted HTTP API that stores each conversation and builds every model call for you. Your code creates a chat once, then sends only the new input of each turn (a prompt, or a tool result) with the model to use. Twigg stores every part, assembles the context for that model's window from your budgets and retention policies, summarises old history when it no longer fits, translates the call for the provider, streams the answer back as server-sent events, and records what it sent and what it cost. Your application keeps the agent loop and executes the tools. Practical advice for building on Twigg is in [Tips](https://twigg.ai/tips.txt). For system prompts, saved tools, context budgets and retention settings, see [Context control](https://twigg.ai/docs/context#configure-prompts-tools-and-context). ## What it is The AI layer of an application: a conversation store, a context engine, a model router and a visibility suite (usage and cost per response, in the console) in one. What it replaces: - The table you were going to design for messages, tool calls and their results. - The code that decides what to drop when the transcript outgrows the window. - The per-provider translation layer, and the replay artifacts it has to preserve. - The token accounting behind whatever you bill for. What it leaves you: - The agent loop. Twigg lets you focus on the logic of your application, not the mechanics of managing context. It never executes a tool; it tells you one was called. - The implementation of your tools, and what they do. - The choice of model you wish to use, from our catalogue. - Your chat permission management. Twigg lets you submit chats under namespaces and tag on any `user_metadata`; you decide how those namespaces are structured. A provider's stateful API stores your conversation inside the thing that generated it, so the stored thread is also the reason you cannot leave. Twigg stores it beside the models. `model` is a per-request choice, not a property of the chat, and nothing in the ledger is written in any one provider's dialect. A chat generated with one model can be continued with another simply by changing the `model` field on the next request. Scope: conversational turns with tools, across every model in the catalogue. Not embeddings, image generation, batch or fine-tuning, and never executing a tool. ## Three things to learn - **Chat** (`chat_id`). A handle to the conversation you are working with, and what the context is associated to. `POST /api/v1/chats` returns one; every submission to `/responses` carries it, and the event is appended to that chat's context. If you already have an id per conversation, such as a phone number, give the chat that `external_id` instead and address it by your id; `POST /api/v1/chats/external/{external_id}/responses` even creates the chat on first use. - **Namespace** (`user_83022938/project_1234`). A logical grouping of chats, so you can organise conversations in a structured way: each user in your application might have their own. API calls can be filtered by namespace, and each namespace carries its own rules and configuration. - **Run** (`run_id`). A single interaction with the responses API. It may span several parts: a reasoning block, a text block, a tool call. It records what was assembled, which model served it, and what it cost, and is the id you use for auditing requests and usage. ## Namespaces A namespace is a path you choose, such as `acme/proj-7/8f2c…a91`, set on a chat at creation and immutable after. It groups chats for listing, and it is the scope key that decides which instructions, tools, retention policy and context budget every turn on that chat receives. Resolution walks up the path. Configuration published at `acme` applies to everything beneath it. Instructions and tool bundles combine down the path, each level choosing `append` or `replace`. Retention policies and context budgets do not combine: the nearest configured level is used whole. There is nothing to provision. Creating a chat is how a namespace comes into existence; it leaves the listing when its last chat is deleted. That is why a typo is not an error: a mistyped namespace quietly resolves to the organisation-wide defaults. `GET /api/v1/namespaces` lists what your chats are actually in, so `acme/prdo` shows up next to `acme/prod`. Shape rules: - Segments of `a-z 0-9 _ -`, joined by `/`. No empty segment. - 255 bytes for the whole path, 64 for any one segment. - Uppercase is rejected with a 422, not folded. Folding would merge two of your end users into one scope. - For a per-user leaf, use an opaque lowercase id. A namespace is not a security boundary. Tenancy is enforced by the organisation behind your API key and nothing else. ## Authentication One API key, sent as `Authorization: Bearer tw_live_…`, authenticates the customer operations listed below. Discovery, version information, and the public updates feed do not require a key. The console's own routes under `/v1` run on a session cookie instead, with the public ones excepted: the catalogue linked at the foot of this page needs no credential at all. Neither credential substitutes for the other. An API key opens nothing in the console, and a session cookie opens none of the authenticated customer operations. Every error uses one envelope: ```json { "error": { "code": "chat_busy", "message": "this chat already has a turn in progress; retry once it finishes", "details": { "retry_after_secs": 2 } } } ``` A failure after the response has opened arrives as a terminal `error` event carrying the same `code`. ## The loop Once: 1. `POST /api/v1/chats` creates the chat and returns its id. Then, every turn. Steps 2 to 4 repeat for the life of the conversation, and 2 and 4 are the same endpoint: 2. `POST /api/v1/chats/{chat_id}/responses` sends what just happened: a prompt and the model. Not the transcript. 3. Read the `text/event-stream`. If `done.pending_tool_calls` is non-empty, the chat is waiting on you. 4. `POST /api/v1/chats/{chat_id}/responses` again, the same endpoint, with a `tool_result` instead of a prompt. Name a different model here if you want one. If a process dies mid-conversation, the next one picks it up from the chat id alone. ## Billing Twigg is prepaid. Your organisation holds a credit balance in USD; every run is checked against it before it opens and charged against it once it closes. There is no end-of-month invoice to reconcile. - **Before the run.** Pre-flight checks the balance covers the input plus the most the output could cost, at your billed rates, and caps `max_tokens` against what is left. A 402 means the balance cannot cover the input alone. - **After the run.** Settlement charges what was actually used, at the rates frozen when the run opened, so a catalogue price change is never retroactive. Compaction is charged as its own line, because it is its own model call. Concurrent runs can drive a balance slightly negative. - **If you abort.** An aborted run is charged for its input and for the output generated before it stopped, using the provider's counts where it gave them and estimates where it did not. An abort that lands before the request reaches the model costs nothing. Summaries the turn had already generated are kept and charged as their own lines. **Your own provider keys.** An admin can store your organisation's own provider key in Console → API keys and choose the models it serves, for the whole organisation or for a namespace and everything below it; the nearest namespace with a key wins. Turns on those models call the provider with your key, your provider bills you for the tokens, and Twigg charges only its margin. Compaction still runs on Twigg's keys and is charged as usual. For Google models, bring a Gemini API key from Google AI Studio, from a project with billing enabled: on the free tier Google may use your prompts to improve its products. Twigg sends your key to the Gemini API and runs its own Gemini traffic on Vertex AI, and Gemini's reasoning signatures only work on the endpoint that produced them. When a Gemini chat moves between your key and Twigg's (a pause, a fallback, a key added or revoked), its text and tool calls carry over, but the earlier turns' hidden reasoning does not, and the turn reports a `foreign_artifacts_stripped` translation warning. The same happens when a chat changes model family. - **If your key is refused** (revoked, out of quota, rate-limited), the turn fails with `provider_key_error`. Turn on fallback to Twigg for a model and the turn moves to Twigg's key instead, billed at the full rate, with a `provider_key_fell_through` warning before any content. Fallback only happens before the first token, and only if your balance covers the full rate. - **A paused key** keeps its settings but is not used. Turns on models with fallback to Twigg on run on Twigg's key at the full rate, with a `provider_key_paused` warning. Turns on models with it off are refused with a `provider_key_paused` error, so pausing never moves traffic onto Twigg's key unless you allowed it. - **Revoking** deletes the stored key at once. Keys are encrypted at rest and are never shown again after you save them, and no API endpoint can read them. If a provider reports cache-write tokens but the run has no configured cache-write rate, those tokens are charged at the applicable input rate. This applies to both chat and compaction runs. Usage still records them as cache writes; an explicit cache-write rate, including zero, takes precedence. Add funds from Console → Billing, from $5 up. The charge goes to the card on file and the credit is applied when the payment settles, a moment later rather than immediately. Every attempt, manual or automatic, is listed with its outcome. Cards are held by Stripe and managed through their portal; Twigg never sees a card number. **Auto top-up.** Set a threshold and an amount: when the balance falls below the threshold, the card on file is charged that amount, behind whichever request crossed the line, so a conversation does not stop while it runs. The amount must be larger than the threshold, or a top-up would land the balance still under the line and fire again on the next turn. The rule can be saved before a card is on file; it simply will not fire until there is one. **You may have to approve the first charge.** Auto top-ups are charged off-session, with nobody at a keyboard, and a bank can refuse to authorise a card that way until it has been charged once with the cardholder present. If your first automatic top-up is declined for authentication, add funds manually once from the console, approving it with your bank if asked. Later top-ups then run unattended on the same card. ## Endpoints | Method | Path | Authentication | Purpose | |---|---|---|---| | DELETE | `/api/v1/chats` | API key | Delete chats under a namespace prefix | | GET | `/api/v1/chats` | API key | List chats | | POST | `/api/v1/chats` | API key | Create a chat | | DELETE | `/api/v1/chats/external/{external_id}` | API key | Delete a chat by external id | | GET | `/api/v1/chats/external/{external_id}` | API key | Get a chat by external id | | PATCH | `/api/v1/chats/external/{external_id}` | API key | Update a chat by external id | | PUT | `/api/v1/chats/external/{external_id}` | API key | Create or get a chat by external id | | POST | `/api/v1/chats/external/{external_id}/abort` | API key | Abort the turn in progress by external id | | GET | `/api/v1/chats/external/{external_id}/history` | API key | Read chat history by external id | | POST | `/api/v1/chats/external/{external_id}/import` | API key | Import a conversation by external id | | POST | `/api/v1/chats/external/{external_id}/responses` | API key | Submit a turn by external id | | GET | `/api/v1/chats/external/{external_id}/runs` | API key | List a chat's runs by external id | | DELETE | `/api/v1/chats/{chat_id}` | API key | Delete a chat | | GET | `/api/v1/chats/{chat_id}` | API key | Get a chat | | PATCH | `/api/v1/chats/{chat_id}` | API key | Update a chat | | POST | `/api/v1/chats/{chat_id}/abort` | API key | Abort the turn in progress | | GET | `/api/v1/chats/{chat_id}/history` | API key | Read chat history | | POST | `/api/v1/chats/{chat_id}/responses` | API key | Submit a turn and get the answer | | GET | `/api/v1/chats/{chat_id}/runs` | API key | List a chat's runs | | DELETE | `/api/v1/config` | API key | Delete configuration under a namespace prefix | | GET | `/api/v1/config/budgets` | API key | List active context budgets | | POST | `/api/v1/config/budgets` | API key | Publish context budgets | | DELETE | `/api/v1/config/budgets/active` | API key | Withdraw context budget | | GET | `/api/v1/config/budgets/versions` | API key | List context budget versions | | POST | `/api/v1/config/budgets/{id}/activate` | API key | Restore Budget | | GET | `/api/v1/config/defaults` | API key | Read default policies | | GET | `/api/v1/config/instructions` | API key | List Instruction Versions | | POST | `/api/v1/config/instructions` | API key | Publish system instructions | | DELETE | `/api/v1/config/instructions/active` | API key | Withdraw Instructions | | GET | `/api/v1/config/instructions/{id}` | API key | Read instruction version | | POST | `/api/v1/config/instructions/{id}/activate` | API key | Restore Instructions | | GET | `/api/v1/config/namespaces` | API key | List namespaces used by chats or configuration | | GET | `/api/v1/config/resolved` | API key | Resolve effective configuration | | GET | `/api/v1/config/resolved-budget` | API key | Resolve effective context budget | | GET | `/api/v1/config/retention` | API key | List Retention Versions | | POST | `/api/v1/config/retention` | API key | Publish retention policy | | DELETE | `/api/v1/config/retention/active` | API key | Withdraw Retention | | POST | `/api/v1/config/retention/{id}/activate` | API key | Restore Retention | | GET | `/api/v1/config/tools` | API key | List Tool Versions | | POST | `/api/v1/config/tools` | API key | Publish saved tools | | DELETE | `/api/v1/config/tools/active` | API key | Withdraw Tools | | GET | `/api/v1/config/tools/{id}` | API key | Read tool version | | POST | `/api/v1/config/tools/{id}/activate` | API key | Restore Tools | | GET | `/api/v1/models` | API key | List available models | | GET | `/api/v1/namespaces` | API key | List namespaces in use | | GET | `/api/v1/runs/{run_id}` | API key | Inspect a run | | GET | `/api/v1/updates` | None | List published updates | | GET | `/api/v1/usage` | API key | Query organisation or namespace usage | | GET | `/v1/catalogue` | None | List public model prices | | GET | `/v1/catalogue/models.md` | None | Read model prices as Markdown | | GET | `/v1/catalogue/{name}` | None | Get public model prices | Prices for every model, including any applicable markup, are at https://api.twigg.ai/v1/catalogue/models.md. The live catalogue states the current environment’s margin; JSON `markup_percent: "0"` means provider cost. Prices already include that markup, so do not add it again. ## Catalogue performance The catalogue's `uptime` field reports the observed success rate of completed provider requests over the last 24 hours, after automatic retries. It is refreshed every 15 minutes and ranges from `0` to `1`; `null` means there are no eligible results. Both chat and compaction requests contribute. Local validation errors, interrupted runs and historical failures without a provider classification are excluded. This is a traffic-based measure, not continuous monitoring or an uptime SLA; a lightly used model may have very few observations. `avg_time_to_first_token_ms` is the mean time in milliseconds from starting a provider request to its first nonempty output delta, across successful requests completed in the last 24 hours. It includes automatic retry waits and counts streamed text, reasoning, refusals and tool arguments; headers and empty block starts do not count. Hidden reasoning cannot be measured until output arrives. Historical runs without timing and responses with no output deltas are excluded; `null` means no timing samples are available. Context preparation and compaction before a customer provider call are not part of that call's timing. Both measurements are refreshed in the background every 15 minutes. Catalogue requests read the stored results without scanning request history. Figures depend on the workload (including prompt size and reasoning settings), and may remain at their last measured values if a refresh fails.