Ciabatta API
Ciabatta runs complete voice agents: speech recognition with echo cancellation, a language model with tools and memory, and a natural voice, all billed per turn. Base URL: https://api.getciabatta.com.
Quickstart
- Create an account and add credits.
- Build an agent in the dashboard (or with
POST /v1/agents) and talk to it in the playground. - Create an API key and call the agent from your server:
curl https://api.getciabatta.com/v1/agents/support/chat \
-H "Authorization: Bearer $CIABATTA_API_KEY" \
-H "Content-Type: application/json" \
-d '{"message": "Hi, where is my order?", "customer_id": "cust_123"}'
SDKs and Twilio
The JavaScript SDK (@getciabatta/sdk, Node 18+ and browsers) wraps the REST API, the session protocol (playback acks, keep-alive, automatic resume with replay dedupe) and webhook verification.
// Your server
import { Ciabatta } from "@getciabatta/sdk";
const ciabatta = new Ciabatta({ apiKey: process.env.CIABATTA_API_KEY });
const session = await ciabatta.sessions.create("support", { customer_id: "cust_123" });
// send session (ws_url, token, resume_token) to the browser
// The browser: microphone, playback, acks and barge-in handled for you
import { BrowserVoiceCall } from "@getciabatta/sdk/browser";
const call = new BrowserVoiceCall(session);
call.on("transcript", (m) => console.log("caller:", m.text));
call.on("agent_text", (m) => console.log("agent:", m.delta));
call.on("closed", (m) => console.log("ended:", m.reason));
await call.start();
On a server (or for your own audio pipeline) use new VoiceSession(session, {encoding, sampleRate}): sendAudio(bytes), played(pos), sendText(), sendToolResult(), interrupt(), end(), and events audio, transcript, end_of_turn, clear, usage, resumed, end.
Android: the Kotlin SDK (com.getciabatta:ciabatta-android, Android 7.0+) has the same pieces: AndroidVoiceCall (microphone with the platform echo canceller, playback, acks, barge-in with automatic duck/unduck, audio routing, automatic resume), VoiceSession for your own audio, plus Ciabatta and Webhooks.verify for Kotlin servers. Get the session from your backend; never put an API key in an app. Use version 0.1.1 or later for the fast barge-in (the agent lowers its volume as soon as the caller starts talking, and restores it if it was only echo).
// build.gradle.kts
dependencies { implementation("com.getciabatta:ciabatta-android:0.1.5") }
// AndroidManifest.xml (request RECORD_AUDIO at runtime before start())
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
// Your activity
val call = AndroidVoiceCall(context, SessionInfo.fromJson(sessionJson)) // session JSON from your backend
call.addListener(object : AndroidVoiceCallListener {
override fun onTranscript(msg: JSONObject) { /* msg.text, msg.final */ }
override fun onAgentText(msg: JSONObject) { /* msg.delta */ }
override fun onEnd(reason: String, error: CiabattaException?) { }
})
lifecycleScope.launch { call.start() } // throws CiabattaException on mic or connection failure
// later: call.setMuted(true), call.interrupt(), call.sendText("..."), lifecycleScope.launch { call.end() }
Calls that must survive the app going to the background should run from a foreground service of type microphone. If you drive your own audio with VoiceSession, implement onDuck / onUnduck to change your player volume and report it with vs.gain(pos, gain).
Phone calls: the Twilio Media Streams bridge example answers a Twilio number with <Connect><Stream>, forwards mu-law 8 kHz audio both ways, turns Twilio mark echoes into playback acks and forwards barge-in as Twilio clear. Use the phone profile for these agents.
Deployment profiles
Set "profile" when creating an agent to start from tuned defaults; any setting you pass overrides the profile. GET /v1/profiles returns every resolved value.
| Profile | Use it for |
|---|---|
fast | Demos and assistants: cheapest tier, quickest turn-taking, short replies (~0.9 s to first audio p50). |
support | Customer service: waits longer for unfinished sentences, concise answers, tools (~1.2 s p50). |
companion | Chat/companion: warm voice, long memory, relaxed turn-taking. |
noisy | Mobile/outdoor: noise suppression, gain control, stricter voice detection and barge-in. |
phone | Telephony bridges such as Twilio Media Streams: mu-law 8 kHz, noise suppression. |
Authentication
Send your secret key as Authorization: Bearer sk_live_... (or sk_test_...). Keys are for servers only. Browsers and phones join voice calls with a short-lived session token instead (see Voice sessions).
Agents
| Method | Path | What it does |
|---|---|---|
| GET | /v1/agents | List agents. |
| POST | /v1/agents | Create: {name, description?, profile?, ...settings}. |
| GET / PATCH / DELETE | /v1/agents/{id_or_name} | Read, update (settings merge; null resets a field), delete. |
| GET | /v1/agents/{id}/versions | Version history; restore with POST .../versions/{n}/restore. |
| GET | /v1/agents/schema | Every setting with its type, range and default (public). |
| GET | /v1/models | Language models with per-turn prices (public). |
Key settings: model or tier (S, M, L), system_prompt, personality_prompt, safety_prompt, voice, tts.model (speech engine), tts.speed, tools, first_message, first_speaker, memory, retention, barge_in and call limits. Prompts may use {{variables}} filled per request.
The system prompt is assembled in this order: system prompt, personality, voice rules, safety rules (stated to override everything above), then the customer's memory summary. Every new agent starts with sensible defaults for all three prompts.
Text turns
POST /v1/agents/{id_or_name}/chat
{"message": "...", "customer_id": "cust_123", "variables": {"name": "Ana"},
"conversation": "continue" | "new" | "conv_...", "stream": false}
Returns {status, reply, conversation_id, tool_calls, usage, billing, warnings}. With "stream": true the response is server-sent events: turn, text {delta}, tool_call, then done (the full turn) or error. When status is requires_action, run the client tools and send {"tool_results": [{"id", "result"}], "conversation": "conv_..."}.
Voice sessions
Your server creates a session, then hands ws_url and token to the browser or app, which connects within 5 minutes. Your API key never leaves your server.
POST /v1/agents/{id_or_name}/sessions
{"customer_id": "cust_123", "variables": {...}, "conversation": "continue",
"overrides": {"voice": "...", "system_prompt": "..."}}
-> {"id": "ses_...", "ws_url": "wss://api.getciabatta.com/v1/sessions/ses_.../stream",
"token": "st_...", "token_expires_at": 1760000000, "conversation_id": "conv_...", ...}
const ws = new WebSocket(session.ws_url, ["ciabatta", session.token]);
ws.binaryType = "arraybuffer";
ws.onopen = () => ws.send(JSON.stringify({type: "start", encoding: "pcm_s16le", sample_rate: 16000, played_acks: true}));
GET /v1/sessions/{id} returns status, turns and cost; DELETE /v1/sessions/{id} ends a live call. Each session pins the agent version and prices in force when it was created. If the connection drops, resume the same call (see Reconnects).
Session protocol
Text frames are JSON. Binary frames are audio: mic audio from you (the start encoding), agent audio to you (pcm_s16le 24 kHz, or 8 kHz mu-law/a-law when you send telephony audio).
| You send | Meaning |
|---|---|
start {encoding?, sample_rate?, played_acks?} | First message. Encodings: pcm_s16le, mulaw, alaw. |
| binary | Microphone audio, 20-100 ms per frame. |
text {content} | A typed user turn. |
tool_result {id, result} | Answer to a client tool_call (30 s timeout). |
played {pos} | Playback progress, see Playback acks. |
interrupt, end, ping {t} | Stop the agent talking, hang up, keep-alive/RTT. |
| You receive | Meaning |
|---|---|
ready {session_id, conversation_id, output} | Connected; output is the agent audio format. |
transcript {text, final} | What the caller is saying, one segment at a time. final: false is the live partial of the current segment (replace the previous one; show it lighter). final: true means that segment is finalized: append it as solid text; the partials that follow belong to the next segment. |
end_of_turn {text, committed, voice?} | The caller stopped talking (silence threshold reached). text is the whole utterance; committed is false when it was ignored (empty, or echo of the agent). The next transcript starts a new utterance. With voice insights on, voice is {speaker, speaker_state, speaker_label?, tone?}. |
turn {state} | listening, thinking, tool, speaking. |
agent_text {turn_id, delta} | The reply text as it is generated. |
audio_start {turn_id, pos}, binary, audio_end {turn_id, samples, pos} | The spoken reply. |
clear {turn_id, reason, pos} | Barge-in: stop playback immediately and drop queued audio. |
duck {gain?}, unduck | The caller may be talking over the agent: set the agent volume to gain (default 0.3), or back to full. Reply gain {pos, gain} with the playback position where it took effect so echo cancellation matches. |
tool_call {id, name, arguments} | Run a client tool and reply with tool_result. |
usage {turn_id, billing, session_cost_usd, ...} | Per-turn tokens, characters and cost. |
warning {code, message}, error {code, message} | Non-fatal notice / failure. |
closed {reason} | The call ended (client_end, end_call, max_duration, idle_hangup, insufficient_balance, ...). |
Playback acks
Echo cancellation and barge-in work best when Ciabatta knows what the caller actually heard. Positions (pos) count agent output samples sent since the session started. Send start {played_acks: true}, then about every 100 ms send played {pos} with the number of samples your speaker has played. On clear, stop playback and jump your counter to clear.pos. Interrupted replies are then saved to history cut to what was heard. Without acks Ciabatta estimates playback from arrival time and sends warning played_acks_missing; if acks stop for 2 s it falls back and sends played_acks_stopped.
Reconnects
If the socket drops, the call stays alive for the agent's call.reconnect_grace_s (default 30 s, up to 120). The agent finishes its reply and Ciabatta buffers what you missed. Every JSON event carries a seq; ready carries a single-use resume_token (rt_...), replaced on every ready.
- Reconnect to the same
ws_urlwith the latestresume_tokeninstead of the session token. - Send
resume {last_seq, last_pos}: the highestseqyou received and the agent audio position you received up to. - You get
ready {resumed: true}, then every missed event and audio frame in order, then the live call. Ignore any event with aseqyou already have.
Speech recognition pauses while you are away and is not billed. If the grace window passes, the call ends with closed {reason: "disconnect_timeout"}; start a new session with "conversation": "conv_..." to continue the conversation. To fetch one reply's audio over HTTP instead, call GET /v1/sessions/{id}/turns/{turn_id}/audio?token=rt_... (or with your API key) while the call is live or within its grace window. The SDKs do all of this automatically.
Tools
Add tools to an agent's tools list. Webhook tools are called by Ciabatta with a signed POST (Ciabatta-Signature: HMAC-SHA256 of "<t>.<body>" with the agent's webhook_secret). Client tools are sent to your app (tool_call) to run locally. Built-ins: end_call and wait. max_tool_rounds caps tool calls per turn.
Customers and memory
Pass a stable, opaque customer_id (never an email or phone number). With "conversation": "continue" the customer's latest conversation continues; "new" starts fresh. Turn on memory.summary to keep a rolling per-customer summary that is added to the prompt. Transcript retention defaults to 7 days (up to 90, or none); zero data retention keys and accounts store nothing.
Conversations: GET /v1/conversations?agent=&customer_id=, GET /v1/conversations/{id}, DELETE /v1/conversations/{id}. Erase everything stored for one end user (conversations, transcripts, summaries, remembered voices) with DELETE /v1/customers/{customer_id}; it takes effect immediately. Deleting an agent deletes its conversations and remembered voices too.
Voice insights (preview)
Free during the preview. Set voice_analysis.speakers to tell voices apart within a call (the agent sees "Speaker 1", "Speaker 2" and whether a voice is new or returning) and voice_analysis.tone to give it relative pace, pitch and energy. These are hints for the conversation: never use them to authenticate anyone or to infer emotions. When a caller says their name, the agent can call the built-in label_speaker tool.
With voice_analysis.remember (needs speakers and a customer_id) a voice is remembered for that customer only after the speaker agrees and the agent labels it, kept for retention.speakers (default 1 year). Only a mathematical voice signature is stored, never audio, and it is never returned by the API. Zero data retention keys store nothing (warning zdr_no_speaker_memory). Manage remembered voices with GET/DELETE /v1/agents/{agent}/customers/{customer_id}/speakers and PATCH {label?, is_owner?}/DELETE .../speakers/{id}.
Webhooks
Set an agent's webhook.url to receive session.started and session.ended (with usage, cost, end reason and the transcript, trimmed to 256 KB). Each POST has headers Ciabatta-Event, Ciabatta-Delivery (event id, use it to dedupe), Ciabatta-Attempt and Ciabatta-Signature: t=<unix>,v1=<hex>, an HMAC-SHA256 of "<t>.<raw body>" with the agent's webhook_secret (rotate it with POST /v1/agents/{id}/webhook_secret/rotate). Reply 2xx within 8 s. Failures are retried after 10 s, 1 min, 5 min and 30 min.
import { verifyWebhook } from "@getciabatta/sdk";
const event = await verifyWebhook(secret, req.headers["ciabatta-signature"], rawBody); // throws if invalid or older than 5 min
Voices
GET /v1/voices lists stock voices and your clones. Clone voices in the dashboard. Pick the speech engine per agent with tts.model:
bread-1(default): every stock voice and your clones. Included in the turn price up to the per-turn speech allowance.bread-premium-2: a lifelike GPU voice model. Speaks the premium stock voices and your premium-ready clones (both arepremium: trueinGET /v1/voices). A clone made while premium is available gets its premium profile from the same recording; older clones are standard-only until you add a premium sample (Enable premium in the dashboard). Other voices fail validation. Every spoken character is billed at $10 per 1M characters, in place of the per-turn speech allowance and standard speech fee.bread-expressive-1: the same premium voices, performing inline tags such as[laugh],[sigh]or[whispering](tag list). Every spoken character is billed at $8 per 1M characters, in place of the per-turn speech allowance and standard speech fee. English only; see below for other languages.
Voice Design Studio. Describe a new voice instead of recording one, then give it to any agent. See Voice Design Studio for the dashboard walkthrough and the API.
Languages. bread-premium-2 speaks 30 languages and reads the language of the agent's reply: Arabic, Burmese, Chinese (incl. dialects such as Cantonese), Danish, Dutch, English, Finnish, French, German, Greek, Hebrew, Hindi, Indonesian, Italian, Japanese, Khmer, Korean, Lao, Malay, Norwegian, Polish, Portuguese, Russian, Spanish, Swahili, Swedish, Tagalog, Thai, Turkish, Vietnamese. bread-1 is English only. bread-expressive-1 speaks English and hands other languages to bread-premium-2 (details). Speech recognition (the caller side) runs Phonon-2.5, which transcribes 25 European languages; end-of-turn detection is tuned for English.
PATCH /v1/agents/support
{"tts": {"model": "bread-premium-2"}, "voice": "emily"}
PATCH /v1/agents/support
{"tts": {"model": "bread-premium-2"}, "voice": "cloned_0123456789abcdef0123456789abcdef"}
Expressive voice (bread-expressive-1)
Set tts.model to bread-expressive-1 and the agent speaks the premium voices with performed non-verbal sounds and delivery styles. The agent's LLM is automatically told it may use the tags below, sparingly, so replies like "That's hilarious [laugh] okay, let me check." laugh instead of reading the tag. Unknown tags are removed, never read aloud; bread-1 and bread-premium-2 remove these tags too.
PATCH /v1/agents/support
{"tts": {"model": "bread-expressive-1"}, "voice": "emily"}
| Kind | Tags | Also accepted |
|---|---|---|
| Sounds | [laugh] [chuckle] [sigh] [gasp] [cough] [clear throat] [sniff] [groan] [shush] | [laughing] [laughs] [laughter] [chuckles] [sighs] [gasps] [coughs] [clears throat] [sniffs] [groans] [shh] |
| Delivery | [whispering] [angry] [happy] [crying] [fear] [surprised] [sarcastic] [dramatic] [narration] [advertisement] | [whisper] [whispers] |
Languages: the expressive engine speaks English. When the agent replies in another language, that reply is spoken by bread-premium-2 with the same voice automatically, still billed at the expressive rate ($8 per 1M characters). SDKs: TTS_MODELS.EXPRESSIVE and EXPRESSIVE_TAGS in @getciabatta/sdk; TtsModels.EXPRESSIVE and TtsModels.EXPRESSIVE_TAGS in the Android SDK (0.1.4+). Hear the tags on the Voices page (Hear a voice, Expressive engine).
Voice Design Studio
Create a custom voice for an agent from a written description, no recording needed. Previews are generated on the premium engine; a saved voice works on bread-1, bread-premium-2 and bread-expressive-1 and counts toward your 20 voices. With clone + adjust you start from a recording instead: the previews keep that speaker and the description changes the delivery (emotion, pace, energy), not the identity.
In the dashboard (Voices page):
- Pick Describe a voice, or Clone + adjust to start from a recording (5-60 s, one speaker, with the speaker's permission; accept the cloning terms once first).
- Describe the voice in up to 300 characters, or click the trait chips: gender, age, pitch, texture, emotion, pace, accent.
- Choose a preview language and 1-3 previews. Edit the preview sentence to sound like your agent (a greeting, a typical answer); the estimated cost is shown before you generate.
- Click Generate previews and listen. Each preview is a different take. Generate again gives new takes.
- Click Use this voice on your favorite and name it. It appears under Your voices; pick it in an agent's voice setting, or set its
cloned_...id asvoicethrough the API.
Writing a good description. Describe how the voice sounds, from broad to specific: "A calm, middle-aged man with a low, smooth voice, reassuring and patient, speaking slowly." A few clear traits work better than many; pick one emotion and one pace. Names of real people, celebrities and "sounds like" comparisons are rejected.
Over the API (same key as the rest of the API; live keys only):
| Method | Path | What it does |
|---|---|---|
| POST | /v1/voices/design | Generate 1-3 previews. JSON {description, preview_text?, language?, count?}, or multipart with file + consent=true for clone + adjust. |
| POST | /v1/voices | Save a preview as a voice: JSON {name, preview_id}. Free. |
| DELETE | /v1/voices/{id} | Delete one of your voices. |
| Field | Description |
|---|---|
description | Up to 300 characters: gender, age, pitch, texture, emotion, pace, accent. Required unless a file is sent. Descriptions that name or imitate a real person fail with description_not_allowed. |
preview_text | Up to 200 characters spoken in each preview. Defaults exist for en, es, fr, de, it, pt, nl, ja, zh and ko; send your own for other languages. |
language | BCP-47 tag (default en); picks the default preview_text. |
count | Previews to generate, 1-3 (default 3). |
curl https://api.getciabatta.com/v1/voices/design \
-H "Authorization: Bearer $CIABATTA_API_KEY" -H "Content-Type: application/json" \
-d '{"description": "A calm, middle-aged man with a low, smooth voice, reassuring and patient", "count": 3}'
-> {"object": "voice_design", "source": "design",
"previews": [{"id": "pv_9b1e...", "url": "https://api.getciabatta.com/v1/files/aud_...mp3?...", "expires_at": 1793450000, "chars": 166}, ...],
"usage": {"model": "bread-premium-2", "billed_characters": 498, "cost_usd": 0.00498, ...}}
curl https://api.getciabatta.com/v1/voices \
-H "Authorization: Bearer $CIABATTA_API_KEY" -H "Content-Type: application/json" \
-d '{"name": "Front desk", "preview_id": "pv_9b1e..."}'
-> {"id": "cloned_3f9c...", "object": "voice", "name": "Front desk", "type": "clone", "premium": true, ...}
PATCH /v1/agents/support
{"voice": "cloned_3f9c..."}
Billing and limits: previews are billed at the premium rate ($10 per 1M characters) for preview_text length x previews generated, from the same balance; failed previews are refunded. Saving is free. Preview links expire after 15 minutes and preview ids after 24 hours. Up to 30 preview batches per hour and 2 at a time per account (429 rate_limited).
Pricing and budgets
Prepaid credits, billed per turn by model tier (see GET /v1/models for exact prices and per-turn allowances). Each turn includes generous prompt, reply and speech allowances; usage past them adds small surcharges. Connected time beyond the per-turn allowance is billed at a low hourly idle rate. Nothing is charged for failed turns.
Spending limits: call.spend_cap_usd_per_session ends a single call, and daily_spend_cap_usd caps an agent's spend per UTC day across all keys (new sessions get 402 daily_budget_reached). When a call runs out of balance or hits a cap, the agent speaks call.out_of_credits_message (free) and hangs up. When a call reaches call.max_call_seconds, the agent stops its reply, speaks call.time_up_message (free; empty = end silently) and the session closes with max_duration.
Errors
Errors return JSON {"error": {"code", "message", "param", "request_id"}} with a matching HTTP status. Common codes: invalid_request, invalid_agent_config (with errors[]), agent_not_found, insufficient_balance (402), rate_limited (429), monthly_cap_reached, upstream_unavailable (retry with backoff). Include request_id when contacting .
Limits
- Session tokens: one connection, connect within 5 minutes.
- Call length: the agent's
call.max_call_seconds(default 30 minutes; 2 minutes on test keys). - Client tool results: 30 seconds.
- Keys: up to 120 requests per minute by default; set per-key caps in the dashboard.