Introduction
One REST API for the whole platform — send an SMS, place a call, verify a phone number, deliver an email, or run an AI agent, all with the same authentication, conventions, and webhooks.
The API is organized around predictable, resource-oriented URLs. It accepts JSON request bodies, returns JSON responses, and uses standard HTTP verbs, status codes, and authentication. Every response includes a request ID so support can trace exactly what happened. If you can make an HTTPS request, you can use AQUAVIA — the official SDKs are thin wrappers over the same endpoints documented here.
Base URL & versioning
All requests go to a single base URL over HTTPS. Plain HTTP is not supported.
https://api.aquavia.ai/v1The API is versioned in the path (/v1). We add fields and endpoints without bumping the version; those are considered backward-compatible and your integration should ignore unknown fields. Breaking changes ship under a new version with advance notice and an overlap period. We recommend pinning to /v1 and reading the conventions below so additive changes never break you.
Authentication
Authenticate every request with an API key sent as a bearer token in the Authorization header. You create and rotate keys in the AQUAVIA console under Settings → API keys.
Authorization: Bearer sk_live_3f9c...your_keyKeys come in two flavors, distinguished by prefix:
sk_test_...— test keys. Requests are fully processed by the API but nothing is actually sent to a carrier or inbox, and you aren't billed. Use these in development and CI.sk_live_...— live keys. Real messages, real calls, real charges.
Keep secret keys secret. A key grants full access to your account. Never embed one in client-side code, a mobile app, or a public repo. If a key leaks, revoke it in the console — revocation takes effect immediately. Scope keys per environment and per service where possible.
Requests without a valid key return 401 Unauthorized. See Errors & limits for the full list.
Quickstart: send your first message
The fastest way to see the API work is to send an SMS with a test key. Replace the key and the to number, then run it.
curl https://api.aquavia.ai/v1/messages \
-H "Authorization: Bearer sk_test_your_key" \
-H "Content-Type: application/json" \
-d '{
"to": "+14155550123",
"from": "AQUAVIA",
"channel": "sms",
"body": "Your AQUAVIA code is 481920"
}'const res = await fetch("https://api.aquavia.ai/v1/messages", {
method: "POST",
headers: {
"Authorization": "Bearer sk_test_your_key",
"Content-Type": "application/json"
},
body: JSON.stringify({
to: "+14155550123",
from: "AQUAVIA",
channel: "sms",
body: "Your AQUAVIA code is 481920"
})
});
const message = await res.json();
console.log(message.id, message.status);import requests
res = requests.post(
"https://api.aquavia.ai/v1/messages",
headers={"Authorization": "Bearer sk_test_your_key"},
json={
"to": "+14155550123",
"from": "AQUAVIA",
"channel": "sms",
"body": "Your AQUAVIA code is 481920",
},
)
print(res.json()["id"], res.json()["status"])The response
A successful call returns 201 Created with the message resource. The message starts as queued; its final state arrives later by webhook or by polling the message.
{
"id": "msg_01HN9K7QophZ8",
"object": "message",
"channel": "sms",
"to": "+14155550123",
"from": "AQUAVIA",
"status": "queued",
"segments": 1,
"created_at": "2026-07-07T12:00:00Z"
}From here, head to the Messaging reference for every field, or explore Voice, Verification, Email, and AI agents.
Conventions
These rules hold across every endpoint, so once you learn them for messaging they apply everywhere.
Requests & responses
- Send JSON bodies with
Content-Type: application/json. Responses are always JSON. - Every response carries an
X-Request-Idheader. Include it when you contact support — it lets us find the exact call in seconds. - Resource IDs are prefixed by type (
msg_,call_,vrf_,eml_,cnv_) so an ID is always self-describing in logs.
Timestamps
All timestamps are UTC, formatted as RFC 3339 / ISO 8601 (for example 2026-07-07T12:00:00Z). Send timestamps in the same format.
Phone numbers
Phone numbers are always in E.164 format — a leading +, country code, then the national number, no spaces or dashes (for example +14155550123). Numbers in other formats are rejected with a 422.
Idempotency
Write requests (anything that creates a resource) accept an Idempotency-Key header. Send a unique key per logical operation; if the same key is replayed within 24 hours — say, after a network timeout and retry — the API returns the original result instead of creating a duplicate. Use a UUID per attempt.
Idempotency-Key: 5f2b9c1e-9d3a-4b8e-8a1c-2f6d0e4a7b31Pagination
List endpoints are cursor-paginated. Pass limit (1–100, default 25) and, to page forward, starting_after set to the last ID you saw. Responses include has_more and the data array.
GET /v1/messages?limit=50&starting_after=msg_01HZ...
{
"object": "list",
"data": [ { "id": "msg_01J0...", "object": "message" } ],
"has_more": true
}Errors & rate limits
Errors use standard HTTP status codes and a consistent JSON body with a machine-readable code. Requests are rate limited per key, with limits returned in response headers. Both are documented in full on Errors & limits.
Messaging (SMS)
Send one-off and high-volume SMS, receive replies, and track delivery per message. Messages route across multiple carriers automatically, so a degraded route doesn't cost you a delivery.
The message object
idmsg_.statusto / frombodysegmentsdirectionoutbound or inbound.priceprice_currency.error_codecreated_atSend a message
/v1/messagestostringREQUIREDfromstringREQUIREDbodystringREQUIREDchannelstringOPTIONALsms.typestringOPTIONALtransactional (default) or promotional. Affects routing and quiet-hours handling.status_callbackstringOPTIONALreferencestringOPTIONALsend_atstringOPTIONALRequest
curl https://api.aquavia.ai/v1/messages \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 5f2b9c1e-9d3a-4b8e-8a1c-2f6d0e4a7b31" \
-d '{
"to": "+14155550123",
"from": "AQUAVIA",
"type": "transactional",
"body": "Your code is 481920. It expires in 10 minutes.",
"status_callback": "https://example.com/hooks/aquavia"
}'Response 201 Created
{
"id": "msg_01HN9K7QophZ8",
"object": "message",
"channel": "sms",
"direction": "outbound",
"to": "+14155550123",
"from": "AQUAVIA",
"body": "Your code is 481920. It expires in 10 minutes.",
"status": "queued",
"segments": 1,
"reference": null,
"created_at": "2026-07-07T12:00:00Z"
}Retrieve a message
/v1/messages/{id}Fetch the current state of a message, including its latest status, price, and any error_code.
curl https://api.aquavia.ai/v1/messages/msg_01HN9K7QophZ8 \
-H "Authorization: Bearer sk_live_your_key"List messages
/v1/messagesReturns messages in reverse-chronological order. Cursor-paginated (see conventions). Filter with the parameters below.
toOPTIONALstatusOPTIONALdirectionOPTIONALinbound or outbound.created_after / created_beforeOPTIONALlimit / starting_afterOPTIONALReceive inbound messages
When someone replies to one of your numbers, AQUAVIA delivers a message.received event to your configured webhook endpoint. Use it to power two-way conversations, keyword handling (STOP, HELP), or to hand the thread to an AI agent.
{
"id": "evt_01HN9M...",
"type": "message.received",
"created_at": "2026-07-07T12:03:10Z",
"data": {
"id": "msg_01HN9M2R...",
"object": "message",
"direction": "inbound",
"from": "+14155550123",
"to": "AQUAVIA",
"body": "STOP"
}
}Opt-outs are handled for you. Standard keywords like STOP and START update the recipient's consent state automatically and are enforced on future sends. You still receive the event so you can update your own records.
Answer with an AI agent
SMS becomes two-way the moment you put an AI agent behind a number. The agent reads each inbound message, looks things up with your tools, and replies over SMS automatically — no polling, no reply loop to build. There are two ways to wire it up.
Option A — attach an agent to a number
Assign a live agent to one of your numbers in the console. Every inbound message to that number opens (or continues) a conversation and triggers an agent run; the reply is sent back over SMS for you. No extra code — you just keep receiving message.received and run.completed events for your records.
Option B — drive it from the API
For full control, open a conversation on the sms channel and post the inbound text as a customer message. Because the channel is sms, the agent's reply is delivered over Messaging automatically — the same segmentation, routing, and delivery receipts as any other send.
// 1. On message.received, start (or reuse) an SMS conversation:
POST /v1/conversations
{ "agent_id": "agt_support_en", "channel": "sms",
"customer": { "phone": "+14155550123" } }
// 2. Forward the customer's text — the agent replies over SMS itself:
POST /v1/conversations/cnv_01HN9V.../messages
{ "role": "customer", "content": "Where is my order 10842?" }Outbound that can hold a conversation. Send a campaign or reminder with Send a message, then attach an agent to the sending number so any reply is understood and handled — a reschedule, a question, an opt-out — instead of landing in a dead inbox.
Delivery status
An outbound message moves through a predictable set of states. The final state is reported to your status_callback (or account webhook) as a message.updated event, and is always readable by retrieving the message.
queuedsendingsentdeliveredundeliverederror_code.failedNot every carrier returns handset-level receipts; where they don't, sent is the terminal success state. See Errors & limits for error_code values.
Voice calls
Place outbound calls and answer inbound ones, then drive what happens on the call with a small set of instructions — speak text, play audio, collect keypad input, record, or transfer.
The call object
idcall_.statusqueued, ringing, in_progress, completed, busy, no_answer, failed.to / fromdirectionoutbound or inbound.answered_byhuman or machine.durationrecording_urlPlace a call
/v1/callstostringREQUIREDfromstringREQUIREDflowarrayCONDITIONALanswer_url.answer_urlstringCONDITIONALflow array. Use this for dynamic calls.machine_detectionboolOPTIONALanswered_by.recordboolOPTIONALstatus_callbackstringOPTIONALcurl https://api.aquavia.ai/v1/calls \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{
"to": "+14155550123",
"from": "+14155550999",
"machine_detection": true,
"flow": [
{ "action": "say", "text": "Hi, this is a reminder that your appointment is tomorrow at 9 AM.", "voice": "en-US" },
{ "action": "gather", "num_digits": 1, "prompt": "Press 1 to confirm, or 2 to reschedule." }
]
}'Call flow instructions
A flow is an ordered array of actions the call runs top to bottom. Return one from your answer_url to build dynamic IVR, or pass it inline for simple calls.
saytext, voice (language/voice, 90+ languages).playurl.gathernum_digits, prompt, timeout. The digits arrive at your answer_url as digits.recordmax_length, play_beep.transferto.connect_agentagent_id. The agent handles the conversation from that point.hangupAnswer with an AI voice agent
Instead of scripting every branch of an IVR, hand the call to an AI agent. It listens, transcribes speech in real time, understands intent, calls your tools to look things up or make changes, and answers in natural synthesized speech — in 90+ languages. The same agent you run on chat or SMS can take the phone call, so behavior and guardrails stay consistent across channels.
Put an agent on the call
Add a connect_agent action to a flow (or return one from your answer_url). Everything after it — turn-taking, barge-in, tool calls mid-call, and knowledge retrieval — is handled by the agent.
curl https://api.aquavia.ai/v1/calls \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{
"to": "+14155550123",
"from": "+14155550999",
"flow": [
{ "action": "say", "text": "Connecting you to our assistant.", "voice": "en-US" },
{ "action": "connect_agent", "agent_id": "agt_support_en" }
]
}'During the call the agent can invoke tools just as it does in text — checking an order, booking a slot — and speak the result back. When a case needs a person, the agent uses transfer to route the live call to the right queue and passes along a summary. Every turn is written to the conversation transcript, and if recording is enabled the recording_url is attached on completion.
Inbound works the same way. Point an inbound number's answer_url at a flow that returns connect_agent, or attach an agent to the number in the console, and inbound callers reach the voice agent directly.
Retrieve & list calls
/v1/calls/{id}/v1/callsRetrieve a single call for its final status, duration, answered_by, and recording_url; or list calls with the same cursor pagination and time filters as messages.
Call events
Calls emit lifecycle events to your status_callback or account webhook: call.initiated, call.ringing, call.answered, call.completed, and call.recording.ready. Each carries the current call object.
{
"type": "call.completed",
"created_at": "2026-07-07T12:07:41Z",
"data": {
"id": "call_01HN9P...",
"status": "completed",
"answered_by": "human",
"duration": 34
}
}Verification (OTP)
Send a one-time passcode and check it back with two calls. AQUAVIA generates and stores the code, delivers it over the fastest healthy channel, falls back automatically, and enforces expiry, retries, and rate limits — so you never store or compare raw codes yourself.
Start a verification
/v1/verificationstostringREQUIREDchannelstringOPTIONALsms (default) or voice.fallbackstringOPTIONALvoice after sms.code_lengthintegerOPTIONALexpires_inintegerOPTIONALlocalestringOPTIONALen, ja, es.curl https://api.aquavia.ai/v1/verifications \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{
"to": "+14155550123",
"channel": "sms",
"fallback": "voice",
"code_length": 6,
"expires_in": 600
}'Response 201 Created
{
"id": "vrf_01HN9R4T...",
"object": "verification",
"to": "+14155550123",
"channel": "sms",
"status": "pending",
"expires_at": "2026-07-07T12:10:00Z"
}The code never leaves the platform. You don't receive the passcode in the response, and you never store it. That's the point — it removes an entire class of bugs and breaches from your side.
Check a code
/v1/verifications/checktostringREQUIREDverification_id).codestringREQUIREDcurl https://api.aquavia.ai/v1/verifications/check \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{ "to": "+14155550123", "code": "481920" }'Response
{
"id": "vrf_01HN9R4T...",
"object": "verification",
"status": "approved"
}A correct, unexpired code returns status: "approved". A wrong code returns status: "pending" (so the user can retry) and increments the attempt counter. Once the maximum attempts or the expiry is reached, the status becomes expired and you must start a new verification.
Statuses
pendingapprovedexpiredFraud & rate controls
Verification applies velocity limits per destination number and detects patterns associated with SMS pumping and toll fraud. If a request is throttled or blocked you'll receive a 429 or a 422 with a specific error code. Tune limits and allow/deny rules in the console.
Step-up verification inside an agent
Verification is also how an AI agent proves who it's talking to before it does something sensitive. Expose verification to the agent as an approval guardrail or a tool: when a customer asks to change an address or move money, the agent starts a verification, waits for the customer to read the code back in the same SMS, voice, or chat thread, checks it, and only then calls the tool that makes the change.
// The agent starts a verification as a tool call mid-conversation:
POST /v1/verifications
{ "to": "+14155550123", "channel": "sms" }
// After the customer replies with the code, the agent checks it,
// then proceeds with the guarded action only on "approved":
POST /v1/verifications/check
{ "to": "+14155550123", "code": "481920" }Because the code never reaches the agent's reasoning or the transcript, step-up stays secure even inside an automated conversation. See agent guardrails.
Send transactional and marketing email over authenticated, reputation-managed infrastructure. Send raw HTML or reference a stored template, then track delivery and engagement as events.
Set up your domain first. Before sending on a live key, verify your sending domain and its SPF, DKIM, and DMARC records in the console. Unverified domains can only send from the AQUAVIA shared sandbox domain, for testing.
Send an email
/v1/emailstostring | arrayREQUIREDfromstringREQUIREDSupport <support@yourco.com>.subjectstringREQUIREDhtml / textstringCONDITIONALtemplate_id.template_idstringCONDITIONALvariables.variablesobjectOPTIONALreply_tostringOPTIONALcc / bccarrayOPTIONALattachmentsarrayOPTIONALfilename and base64 content.tagsarrayOPTIONALcurl https://api.aquavia.ai/v1/emails \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{
"to": "customer@example.com",
"from": "Orders <orders@yourco.com>",
"subject": "Your order #10842 has shipped",
"template_id": "tmpl_shipping_update",
"variables": { "name": "Jordan", "tracking": "1Z999AA10123456784" },
"tags": ["transactional", "shipping"]
}'Response 201 Created
{
"id": "eml_01HN9T6V...",
"object": "email",
"to": ["customer@example.com"],
"subject": "Your order #10842 has shipped",
"status": "queued",
"created_at": "2026-07-07T12:00:00Z"
}Delivery & engagement events
Email results arrive as webhooks, not in the send response. Subscribe to the events you care about:
email.deliveredemail.openedemail.clickedemail.bouncedemail.complainedSuppression & hygiene
AQUAVIA maintains a per-account suppression list. Addresses that hard-bounce or file a complaint are added automatically and skipped on future sends, which protects your sender reputation. Query and manage the list from the console or the /v1/suppressions endpoint.
Reply & triage with an AI agent
Email isn't only outbound. Route replies to a support or sales address into an AI agent and it reads the thread, classifies intent, drafts a grounded answer, and sends it back over Email — keeping the subject and threading intact. High-risk or low-confidence messages are handed to a person with a summary instead of answered.
Inbound email to an agent
Configure an inbound route (a full address or a subdomain like reply.yourco.com) to a live agent in the console. Each inbound email opens or continues a conversation on the email channel; the agent's reply is delivered over the same reputation-managed Email infrastructure described above.
// Start an email conversation from an inbound message:
POST /v1/conversations
{ "agent_id": "agt_support_en", "channel": "email",
"customer": { "email": "customer@example.com" } }
// The agent's reply is sent as a threaded email automatically:
POST /v1/conversations/cnv_01HNA1.../messages
{ "role": "customer", "content": "Can I change the address on order 10842?" }AI agents
Run an AI agent inside a conversation. The agent reads the customer's messages, retrieves knowledge you've approved, calls tools you define to act in your systems, and either replies or hands off to a person — all while you just exchange messages over the API. The same agent works across SMS, chat, email, and voice, and every run is logged so you can see exactly what it read, decided, and did.
How a turn works
Each time a customer message arrives, the agent performs a run. A run is a short, auditable loop:
- 1. Understand — interpret the message in the context of the full conversation and any customer details you've attached.
- 2. Retrieve — pull relevant passages from the agent's knowledge sources when an answer needs grounding.
- 3. Act — call one or more tools to look things up or make changes in your systems. Tool calls can chain: the result of one can inform the next.
- 4. Respond or hand off — produce a grounded reply, or, when a guardrail or low confidence is hit, return a handoff to a human with a summary.
You never orchestrate these steps yourself. You post a message and read back a completed run; AQUAVIA runs the loop, enforces the guardrails, and delivers the reply on the conversation's channel.
Concepts & object IDs
agt_agent_id.cnv_msg_customer, the agent, or a human.run_The agent object
Agents are authored and versioned in the console; the API exposes them read-only so your code can discover which agents exist and what they're capable of before starting a conversation.
/v1/agents/v1/agents/{id}{
"id": "agt_support_en",
"name": "Support — English",
"status": "live",
"channels": ["sms", "chat", "email"],
"locales": ["en", "es", "fr"],
"knowledge_sources": ["kb_help_center", "kb_shipping_policy"],
"tools": ["get_order", "cancel_order", "issue_refund"],
"guardrails": {
"requires_approval": ["issue_refund"],
"restricted_topics": ["legal_advice"]
},
"handoff": { "default_queue": "support", "on_low_confidence": true },
"version": 7,
"updated_at": "2026-06-30T12:04:11Z"
}An agent must be live to start a conversation. A draft agent returns 422 agent_not_live. Publish from the console when you're ready.
Create a conversation
/v1/conversationsagent_idstringREQUIREDlive.channelstringOPTIONALsms, chat, email, or voice. Determines how replies are delivered. Defaults to chat (reply returned in the API response only).customerobjectOPTIONALid, name, phone, email, locale.contextobjectOPTIONAL{ "plan": "pro", "account_status": "active" }. The agent may use these without a tool call.tagsarrayOPTIONAL["billing", "vip"].metadataobjectOPTIONALcurl https://api.aquavia.ai/v1/conversations \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "agt_support_en",
"channel": "chat",
"customer": { "id": "cus_8842", "name": "Jordan", "locale": "en" },
"context": { "plan": "pro", "account_status": "active" },
"tags": ["support"]
}'Retrieve & list conversations
/v1/conversations/{id}/v1/conversationsList supports filtering by agent_id, status (active, handed_off, closed), channel, tag, and a created range, plus cursor pagination.
GET /v1/conversations?agent_id=agt_support_en&status=handed_off&limit=20Send a message & get a run
/v1/conversations/{id}/messagesPost the customer's message. The response includes the agent's run — the reply it generated and any tools it called. If the conversation is on a live channel like SMS or voice, the reply is also delivered on that channel automatically.
rolestringREQUIREDcustomer for an inbound message. Use human to inject an agent-desk reply into the transcript without triggering a run.contentstringREQUIREDattachments.attachmentsarrayOPTIONALtrigger_runbooleanOPTIONALtrue. Set false to append a message without asking the agent to respond.curl https://api.aquavia.ai/v1/conversations/cnv_01HN9V.../messages \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{ "role": "customer", "content": "Where is my order 10842?" }'Response
{
"id": "msg_01HN9W...",
"role": "customer",
"content": "Where is my order 10842?",
"run": {
"id": "run_01HN9W...",
"status": "completed",
"confidence": 0.93,
"retrieval": [
{ "source": "kb_shipping_policy", "title": "Delivery windows", "score": 0.81 }
],
"tool_calls": [
{ "tool": "get_order", "arguments": { "order_id": "10842" }, "result_status": "ok", "latency_ms": 240 }
],
"reply": {
"role": "agent",
"content": "Your order 10842 shipped yesterday and is out for delivery today. Want the tracking link?"
},
"handoff": null,
"usage": { "input_tokens": 812, "output_tokens": 96 }
}
}List messages
/v1/conversations/{id}/messagesReturn the full transcript in order, including customer, agent, and human turns. Use this to render a live chat panel or rebuild context after a handoff. Results are cursor-paginated, oldest first by default; pass order=desc for newest first.
The run object
A run is created for you whenever a message triggers the agent, but it's also a first-class resource you can retrieve — useful for auditing, for polling an asynchronous run, or for showing "the agent is working" states in your UI.
/v1/runs/{id}statusstringconfidencenumberretrievalarraytool_callsarrayresult_status, and latency.replyobjectnull if the run ended in a handoff.handoffobjectusageobjectRun status lifecycle
queuedin_progressrequires_actioncompletedfailederror. No customer reply was sent.expiredStreaming a run
For chat UIs that show the reply as it's written, open the run as a stream of server-sent events instead of waiting for the full response. You'll receive incremental events as the agent retrieves, calls tools, and composes text.
/v1/conversations/{id}/messages?stream=trueevent: run.started
data: { "run_id": "run_01HN9W..." }
event: tool.called
data: { "tool": "get_order", "arguments": { "order_id": "10842" } }
event: reply.delta
data: { "text": "Your order 10842 shipped " }
event: reply.delta
data: { "text": "yesterday and is out for delivery today." }
event: run.completed
data: { "run_id": "run_01HN9W...", "status": "completed" }Tools
Tools are how an agent does more than talk. Each tool has a name, a description the agent uses to decide when to call it, a JSON Schema for its arguments, and an HTTPS endpoint you own. When the agent chooses a tool, AQUAVIA validates the arguments against your schema, calls your endpoint, waits for your JSON response, and lets the agent continue with the result.
Defining a tool
Tools are configured on the agent in the console. A definition looks like this:
{
"name": "get_order",
"description": "Look up the status and shipping details of an order by its ID.",
"parameters": {
"type": "object",
"properties": {
"order_id": { "type": "string", "description": "The customer's order number." }
},
"required": ["order_id"]
},
"endpoint": "https://api.yourco.com/tools/get_order",
"timeout_ms": 5000
}The call contract
AQUAVIA signs every tool request with the same HMAC signature scheme used for webhooks, so you can verify the call really came from us. Respond with 200 and a JSON body; the agent receives your body as the tool result.
// AQUAVIA calls your tool endpoint:
POST https://api.yourco.com/tools/get_order
Aquavia-Signature: t=1751894400,v1=5f1e...
{
"tool": "get_order",
"arguments": { "order_id": "10842" },
"conversation_id": "cnv_01HN9V...",
"run_id": "run_01HN9W..."
}
// Your endpoint responds:
{ "status": "shipped", "eta": "2026-07-07", "tracking": "1Z999AA10123456784" }Returning an error
If the action can't be completed, return a non-2xx status or an error object. The agent sees the failure and adapts — it might apologize, try a different path, or hand off — rather than inventing a result.
// 404 — the agent will tell the customer the order wasn't found
{ "error": { "code": "not_found", "message": "No order matches 10842." } }Timeouts & retries. If your endpoint doesn't respond within timeout_ms, the call is marked timed_out and the agent proceeds without it. We retry idempotent tool calls once on network errors; make your handlers idempotent using the run_id.
Long-running (async) tools
For actions that can't finish in a few seconds — a manual review, a batch job — respond with 202 and { "status": "pending" }. The run moves to requires_action. Submit the result later and the agent resumes:
/v1/runs/{id}/tool_results{ "tool_call_id": "call_01HN9X...", "result": { "approved": true } }Guardrails apply to actions, not just words. Which tools an agent may call, and when a human must approve, are set on the agent. A refund tool can require approval above a threshold while an order-lookup runs freely. See guardrails and Security & governance.
Knowledge & retrieval
An agent answers from the knowledge sources attached to it — your help center, policies, product data, or documents you've indexed — not from a generic guess. When retrieval is used, the passages appear in the run's retrieval array with a relevance score, so you can surface citations and audit where an answer came from.
"retrieval": [
{
"source": "kb_shipping_policy",
"title": "Delivery windows",
"snippet": "Standard orders ship within one business day...",
"score": 0.81
}
]If nothing relevant is found and the agent isn't confident, it says so or hands off rather than fabricating an answer. You manage sources and re-indexing in the console; the agent always retrieves from the latest published version.
Guardrails
Guardrails are limits set on the agent that the platform enforces on every run — you don't have to police them in your own code:
- Restricted topics — subjects the agent must decline or route to a human (e.g. legal or medical advice).
- Approval gates — tools that require a human to approve before they execute, optionally above a value threshold.
- Data redaction — patterns (card numbers, national IDs) stripped from transcripts and logs.
- Confidence floor — below a set confidence, the agent hands off instead of answering.
When a guardrail stops an action, the run records why in the handoff or a guardrail note, so nothing happens silently.
Human handoff
When the agent hits a guardrail, low confidence, or an explicit customer request, the run returns a handoff object instead of (or alongside) a reply, and a conversation.handoff webhook fires so your agent desk can pick it up with the full transcript and a written summary attached.
"handoff": {
"reason": "requires_approval",
"queue": "billing",
"summary": "Customer requests a $240 refund on order 10842 (shipped, undamaged).",
"suggested_reply": "I can request that refund for you — a specialist will confirm shortly."
}A human replies by posting a message with role: "human". To return control to the agent once the case is resolved, close the handoff:
/v1/conversations/{id}/resume{ "note": "Refund approved and processed. Agent may resume." }Channel behavior
chatsmsemailvoiceBecause context lives on the conversation, a thread can start on SMS and continue by email without the customer repeating themselves.
Events
Subscribe via Webhooks to drive your own UI and systems:
conversation.messagerun.completedrun.requires_actionconversation.handoffconversation.closedCommon errors
agent_not_live422channel_not_supported422conversation_closed409tool_result_expired409See Errors & limits for the shared error object, status codes, and rate limits.
Knowledge & RAG
Retrieval-augmented generation (RAG) is how an AQUAVIA agent answers from your content — your help center, policies, product data, and documents — instead of guessing. You ingest sources into a knowledge base, AQUAVIA indexes them, and at answer time the agent retrieves the most relevant passages and grounds its reply in them, with citations. The same knowledge base works whether the customer is on chat, SMS, a phone call, or email.
How RAG works
Every grounded answer runs through four steps. You manage the first two; the platform runs the last two on each turn.
- 1. Ingest — add sources (URLs, files, structured records, or a live API) to a knowledge base.
- 2. Index — AQUAVIA splits each source into passages, embeds them as vectors, and stores them for fast semantic search. Re-indexing keeps the base fresh as content changes.
- 3. Retrieve — at answer time, the customer's question is embedded and matched against the index; the top passages come back with a relevance score.
- 4. Ground — the agent writes its reply using only those passages, and returns the sources it used so you can show citations. If nothing relevant is found, it says so or hands off rather than inventing an answer.
Objects & IDs. A knowledge base is prefixed kb_; a source inside it is prefixed src_. A base is attached to one or more agents in the console.
Knowledge sources
A knowledge base holds any mix of source types. Each is re-crawled or re-synced on a schedule so answers track your latest content.
urldocumentrecordapiIngest & index
Create a base, then add sources to it. Ingestion is asynchronous: the source starts as indexing and becomes ready when its passages are searchable. Subscribe to knowledge.source.ready via webhooks to know when.
/v1/knowledge_bases/v1/knowledge_bases/{id}/sourcestypestringREQUIREDurl, document, record, api.urlstringCONDITIONALurl sources — the page or section to crawl.file_idstringCONDITIONALdocument sources — an uploaded file reference.recordsarrayCONDITIONALrecord sources — objects with title and content.refreshstringOPTIONALdaily, weekly, or manual. Default weekly.metadataobjectOPTIONAL{ "locale": "en", "product": "pro" }).curl https://api.aquavia.ai/v1/knowledge_bases/kb_help/sources \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{
"type": "url",
"url": "https://help.yourco.com/shipping",
"refresh": "daily",
"metadata": { "locale": "en", "topic": "shipping" }
}'Re-index on your terms. Trigger an immediate refresh with POST /v1/knowledge_bases/{id}/sources/{src}/reindex after a policy changes, instead of waiting for the schedule.
Query the knowledge base
Agents retrieve automatically, but you can also query a base directly — useful for building your own search box, testing coverage, or pre-fetching passages. Retrieval returns ranked passages with scores and source metadata; it does not generate an answer.
/v1/knowledge_bases/{id}/queryquerystringREQUIREDtop_kintegerOPTIONALfilterobjectOPTIONALmetadata matches, e.g. { "locale": "en" }.min_scorenumberOPTIONALcurl https://api.aquavia.ai/v1/knowledge_bases/kb_help/query \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{ "query": "how long does standard shipping take?", "top_k": 3 }'Response
{
"results": [
{
"source_id": "src_01HNB2...",
"title": "Delivery windows",
"snippet": "Standard orders ship within one business day and arrive in 3–5 business days.",
"url": "https://help.yourco.com/shipping",
"score": 0.86
}
]
}Grounding & citations
When an agent answers, the passages it used appear in the run's retrieval array — the same shape as the query results above. Use it to render citations, log provenance, or audit an answer. See the AI agents knowledge section for where it sits in a run.
"reply": { "role": "agent", "content": "Standard shipping takes 3–5 business days." },
"retrieval": [
{ "source_id": "src_01HNB2...", "title": "Delivery windows",
"url": "https://help.yourco.com/shipping", "score": 0.86 }
]No source, no claim. A confidence floor and a "grounded-only" setting on the agent mean that when retrieval comes back empty or weak, the agent declines or hands off instead of guessing.
RAG over SMS
An agent on an SMS number retrieves from the knowledge base on every inbound text, then answers within the constraints of the channel — concise, plain-text, and segment-aware. Long policy passages are summarized to fit, and a citation becomes a short link the customer can tap.
// Inbound SMS to an agent whose knowledge base is kb_help:
POST /v1/conversations/cnv_01HN9V.../messages
{ "role": "customer", "content": "do you ship to Canada and how long?" }
// The agent retrieves, then replies over SMS automatically:
{
"run": {
"retrieval": [ { "source_id": "src_ship_intl", "score": 0.83 } ],
"reply": {
"role": "agent",
"content": "Yes — standard shipping to Canada takes 5–8 business days. Details: help.yourco.com/intl"
}
}
}Scope retrieval per number or per customer with a filter on the agent's knowledge base — for example, only locale: "fr" sources for a French sender ID — so texts get answers in the right language and region.
RAG on a voice call
On a call handled by an AI voice agent, retrieval runs in the same turn as speech. The caller asks a question, the agent retrieves grounded passages, and the answer is spoken back with text-to-speech — no menu tree required. Because a caller can't see a link, the agent reads the essential fact aloud and can offer to send the source by SMS or email as a follow-up.
{
"action": "connect_agent",
"agent_id": "agt_support_en" // its knowledge base kb_help is retrieved on each turn
}Retrieved passages are kept short so spoken answers stay natural, and every turn — including which sources were used — is written to the call transcript for review. If the caller's question falls outside the knowledge base, the agent says it will connect a specialist and uses transfer.
RAG in email replies
When an agent handles an inbound email, it retrieves against the whole thread, not just the last line — so a reply reflects the full context. Email has room for detail, so grounded answers can include a short quote from the source and a link to the full article, with citations preserved in the run for audit.
// Inbound email conversation; agent drafts a grounded, threaded reply:
POST /v1/conversations/cnv_01HNA1.../messages
{ "role": "customer",
"content": "Your policy page is unclear — can I return an opened item?" }
// Reply is sent over Email, grounded in the returns policy source:
"reply": {
"content": "Opened items can be returned within 30 days for store credit. See: help.yourco.com/returns"
},
"retrieval": [ { "source_id": "src_returns", "score": 0.88 } ]Freshness, permissions & guardrails
- Freshness — agents always retrieve from the latest indexed version; a stale source is re-synced on its
refreshcadence or on demand. - Scoping — use
metadatafilters so an agent only retrieves the sources it should (by locale, product line, or audience). - Redaction — content matched by your guardrail patterns is stripped before it reaches a reply or a log.
- Grounded-only — with retrieval required, an agent won't answer a knowledge question it can't support with a source.
See Security & governance for data residency and access controls on knowledge bases.
Common errors
source_indexing409ready yet. Wait for knowledge.source.ready.source_unreachable422url or api source couldn't be fetched during sync. Check access.unsupported_file422See Errors & limits for the shared error object and rate limits.
Webhooks
Most of what happens on the platform happens after your API call returns — a message gets delivered, a call completes, a customer replies. Webhooks push those events to an HTTPS endpoint you own, in near real time.
Subscribe to events
Register an endpoint in the console under Settings → Webhooks, or via the API. Choose which events to receive; subscribe only to what you use.
/v1/webhook_endpointscurl https://api.aquavia.ai/v1/webhook_endpoints \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-d '{
"url": "https://api.yourco.com/hooks/aquavia",
"events": ["message.updated", "message.received", "call.completed"]
}'The response includes a signing_secret (prefixed whsec_). Store it — you'll use it to verify every delivery. You can also subscribe to * to receive all events.
Event envelope
Every webhook is an HTTP POST with a JSON body in the same envelope: a unique event id, a type, a created_at, and a data object holding the resource.
{
"id": "evt_01HN9Y3Z...",
"object": "event",
"type": "message.updated",
"created_at": "2026-07-07T12:00:05Z",
"data": {
"id": "msg_01HN9K7QophZ8",
"object": "message",
"status": "delivered"
}
}Verify the signature
Every request carries an Aquavia-Signature header so you can confirm it really came from AQUAVIA and wasn't tampered with. The header contains a timestamp and an HMAC-SHA256 signature computed over timestamp + "." + raw_request_body using your endpoint's signing secret.
Aquavia-Signature: t=1782475205,v1=4f8a1d...c9Verify it before trusting the payload. Compute the expected signature and compare in constant time; reject anything with a timestamp older than ~5 minutes to prevent replay.
import crypto from "node:crypto";
function verify(rawBody, header, secret) {
const parts = Object.fromEntries(header.split(",").map(p => p.split("=")));
const signed = `${parts.t}.${rawBody}`;
const expected = crypto.createHmac("sha256", secret).update(signed).digest("hex");
const ok = crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
return ok && fresh;
}Verify against the raw body. Compute the HMAC on the exact bytes you received, before any JSON parsing or reserialization — otherwise whitespace or key ordering will change the signature and verification will fail.
Delivery & retries
- Return a
2xxstatus quickly to acknowledge. Do the real work asynchronously — long handlers cause timeouts and retries. - If your endpoint errors or times out, AQUAVIA retries with exponential backoff for up to 24 hours.
- Delivery is at-least-once, so the same event may arrive more than once. De-duplicate on the event
idand make your handler idempotent. - Order isn't guaranteed. Use
created_atand resource status rather than assuming arrival order.
Event catalog
message.updatedmessage.receivedcall.initiated / call.ringing / call.answered / call.completedcall.recording.readyverification.approved / verification.expiredemail.delivered / email.opened / email.clicked / email.bounced / email.complainedconversation.message / run.completed / run.requires_action / conversation.handoffknowledge.source.ready / knowledge.source.failedErrors & limits
The API uses conventional HTTP status codes and returns a consistent error body with a machine-readable code, so you can branch on failures reliably instead of parsing prose.
The error object
{
"error": {
"type": "invalid_request",
"code": "invalid_phone_number",
"message": "The 'to' value is not a valid E.164 phone number.",
"param": "to",
"request_id": "req_01HN9Z..."
}
}typeinvalid_request, authentication, rate_limit, api_error.codemessageparamrequest_idX-Request-Id header. Quote it to support.HTTP status codes
200 / 201201 when a resource was created.400401403404409422param).429500 / 503Common error codes
invalid_phone_numberunsupported_routesender_not_allowedfrom isn't permitted in the destination market.recipient_opted_outdomain_not_verifiedfrom domain isn't verified for a live key.rate_limitedinsufficient_balanceRate limits
Limits are applied per API key and per endpoint group. Every response includes your current standing so you can pace yourself before hitting a wall:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1782475260Exceeding a limit returns 429 with a Retry-After header (seconds). If you expect sustained high throughput — a campaign or a seasonal peak — arrange dedicated throughput ahead of time rather than relying on burst headroom.
Retries & idempotency
- Retry
429,500, and503with exponential backoff and jitter. Don't retry400,401,403,404, or422— fix the request instead. - Always send an
Idempotency-Keyon writes so a retry after a timeout can't create a duplicate message, call, or charge. - Treat webhook delivery as at-least-once and de-duplicate on the event
id.
SDKs & libraries
Official server-side SDKs wrap the REST API in idiomatic code, handle auth and retries, and ship typed models for every resource. They're thin on purpose — anything you can do in an SDK maps directly to an endpoint in these docs.
Server-side only. SDKs use your secret key and must run on a server you control. Never ship a secret key in a browser or mobile app; for client apps, mint short-lived tokens from your backend.
Install
npm install aquaviapip install aquaviacomposer require aquavia/aquavia-phpgo get github.com/aquavia/aquavia-goimplementation "ai.aquavia:aquavia:1.x"gem install aquaviadotnet add package AQUAVIAQuick examples
import AQUAVIA from "aquavia";
const aquavia = new AQUAVIA(process.env.AQUAVIA_API_KEY);
const message = await aquavia.messages.send({
to: "+14155550123",
from: "AQUAVIA",
body: "Your code is 481920"
});
console.log(message.id, message.status);import os
from aquavia import AQUAVIA
aquavia = AQUAVIA(os.environ["AQUAVIA_API_KEY"])
verification = aquavia.verifications.start(to="+14155550123", channel="sms", fallback="voice")
print(verification.status) # "pending"client := aquavia.New(os.Getenv("AQUAVIA_API_KEY"))
call, err := client.Calls.Create(ctx, &aquavia.CallParams{
To: "+14155550123",
From: "+14155550999",
Flow: []aquavia.Action{{Action: "say", Text: "Hello from AQUAVIA."}},
})Configuration
- Read the key from an environment variable (
AQUAVIA_API_KEY); don't hard-code it. - SDKs retry idempotent failures (
429/5xx) with backoff and attach an idempotency key automatically on writes. - Each SDK exposes the raw response and
request_idfor logging. - Pin a major version and read the changelog before upgrading across majors.
Help & community
SDKs are open source on GitHub — issues and pull requests welcome. For account-specific questions or to report a security concern, email developers@aquavia.ai. For a production incident, contact support with the request_id from the affected call.
