Kaleso API documentation

Place phone calls from your own programs over your own SIP trunk: text to speech, AI agents and more. Everything is plain JSON over HTTPS, authenticated with an API key.

Base URL: https://api.kaleso.cloud

Quickstart

  1. Sign up and wait for your account to be activated. See pricing for plans.
  2. Under Settings, add a SIP connection (your trunk's username, password and domain) and your OpenAI API key. Both are stored encrypted and never shown again.
  3. Under Settings → API keys, create a key. It is shown once, so copy it now.
  4. Place a call:
curl -X POST https://api.kaleso.cloud/calls \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"phoneNumber":"+15551234567","sipConnection":"My trunk","target":"Open AI Agent"}'

A successful response looks like this. The call is now dialing; the AI agent talks as soon as it is answered.

{
  "success": true,
  "message": "Call initiated successfully to +15551234567",
  "callId": "6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10",
  "webrtcUrl": null,
  "error": null
}

Use the returned callId to follow the call or end it.

Authentication

Send your key in the Authorization header of every request:

Authorization: Bearer kal_<prefix>_<secret>

A missing, malformed, unknown or revoked key answers 401:

{"message":"Invalid or revoked API key"}

Errors

Failures to place a call return the same body as a success, with success: false, a human-readable message and a machine-readable error code to act on:

{
  "success": false,
  "message": "Failed to initiate call: Your account is waiting to be activated",
  "callId": null,
  "webrtcUrl": null,
  "error": "NOT_ENTITLED"
}
HTTPerrorMeaning
400INVALID_REQUESTThe request is wrong: no SIP connection chosen when the account has several (or none), an unknown connection, no OpenAI key saved for the AI agent, and similar. Read message.
403NOT_ENTITLEDThe account can't place calls: pending activation, suspended, cancelled, subscription lapsed, or over its plan limits.
429CONCURRENT_LIMITThe account (or the server) already has as many calls in progress as allowed. Retry when one ends.
503NO_CAPACITYNo ports are free for another call. Retry shortly.
502CALL_FAILEDThe call couldn't be placed, for example no public address for its audio.

Other errors:

HTTPWhenBody
400Settings and SIP connection requests that fail validation{"message":"..."}
400Malformed JSONStandard Spring error body
401Missing, invalid or revoked API key{"message":"Invalid or revoked API key"}
401An endpoint a key can't use, such as /api-keysEmpty
404Unknown call, or SIP connection not foundEmpty for calls; {"message":"..."} for SIP connections

Endpoints

All request bodies are JSON (Content-Type: application/json); timestamps are ISO-8601 UTC; ids are UUIDs.

POST/calls

Places a call to phoneNumber through one of your SIP connections.

Request body

FieldTypeDescription
phoneNumberstring, requiredThe number to call, as your SIP provider expects it, e.g. +15551234567.
sipConnectionstring, optionalWhich SIP connection to use, by id or name. Optional if the account has exactly one. (provider is the old name for this field and is still accepted.)
targetstring, default "Open AI Agent""Open AI Agent" connects the call to your AI voice agent; "Echo Test" echoes the audio back, handy for testing your trunk. "Text to Speech" reads text out, in the voice speechEngine picks, then hangs up. "WebRTC Demo" is for the browser dialer only. "IVR Flow" and "IVR Webhook" run IVR calls, with ivr below. Unrecognised values fall back to "Open AI Agent".
ivrobject, required for the IVR targetsFor "IVR Flow": flowId of a saved flow, or flow with the flow itself. For "IVR Webhook": webhookUrl. Both take variables, an object that {{name}} in the prompts is filled from.
textstring, required for "Text to Speech"What to read out, up to 1000 characters.
repeatinteger, default 1For "Text to Speech": how many times to read the text, from 1 to 3, with a short pause before each reading. The call hangs up after the last one.
speechEnginestring, default "openai"For "Text to Speech": "openai" reads the text in the OpenAI voice in your Settings, with your OpenAI key; for English, if that audio isn't ready when the person answers, the built-in voice reads it instead. "local" uses the built-in voice only: free, and no OpenAI key needed. The built-in voice reads English only for now: a text with non-Latin letters (Greek, Arabic, ...) is refused with 400.

Example

curl -X POST https://api.kaleso.cloud/calls \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "phoneNumber": "+15551234567",
    "sipConnection": "My trunk",
    "target": "Open AI Agent"
  }'

To read a message out twice, then hang up:

curl -X POST https://api.kaleso.cloud/calls \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "phoneNumber": "+15551234567",
    "target": "Text to Speech",
    "text": "Your order has shipped and arrives tomorrow.",
    "repeat": 2
  }'

Add "speechEngine": "local" for the built-in English voice, without an OpenAI key.

Response 200

{
  "success": true,
  "message": "Call initiated successfully to +15551234567",
  "callId": "6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10",
  "webrtcUrl": null,
  "error": null
}

Failures use the codes in Errors, e.g. 429:

{
  "success": false,
  "message": "Failed to initiate call: ...",
  "callId": null,
  "webrtcUrl": null,
  "error": "CONCURRENT_LIMIT"
}

A successful response means the call is on its way, not that it was answered. Check the call's status for the outcome.

GET/calls

The account's calls in progress.

curl https://api.kaleso.cloud/calls \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"

Response 200

[
  {
    "callId": "6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10",
    "destination": "+15551234567",
    "startedAt": "2025-01-15T10:30:00Z",
    "connectedAt": "2025-01-15T10:30:07Z"
  }
]

connectedAt is null until the call is answered. The list is empty ([]) when nothing is in progress.

DELETE/calls/{callId}

Ends one call: cancels it if it is still ringing, hangs up if it is connected.

curl -X DELETE https://api.kaleso.cloud/calls/6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10 \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"

Returns 204 No Content, or 404 if there is no such call in progress on your account.

POST/calls/reset

Ends all of the account's calls in progress and frees their ports. No request body.

curl -X POST https://api.kaleso.cloud/calls/reset \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"

Response 200

{
  "success": true,
  "message": "Reset: any active call was ended",
  "callId": null,
  "webrtcUrl": null,
  "error": null
}

GET/calls/history

A page of the account's calls, newest first, including refused attempts and calls in progress.

QueryDefaultDescription
page0Zero-based page number.
size25Items per page, from 1 to 100.
curl "https://api.kaleso.cloud/calls/history?page=0&size=25" \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"

Response 200

{
  "items": [
    {
      "callId": "6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10",
      "destination": "+15551234567",
      "mode": "AI_AGENT",
      "source": "API",
      "placedBy": "[email protected]",
      "apiKey": "kal_ab12cd",
      "sipConnection": "My trunk",
      "sipDomain": "sip.example-trunk.com",
      "sipUsername": "myuser",
      "aiModel": "gpt-realtime-mini",
      "aiVoice": "marin",
      "status": "COMPLETED",
      "live": false,
      "endReason": "REMOTE_HANGUP",
      "error": null,
      "message": null,
      "sipCallId": "[email protected]",
      "sipStatusCode": 200,
      "sipReasonPhrase": "OK",
      "sipPort": 5062,
      "rtpPort": 10010,
      "publicRtpAddress": "203.0.113.7:10010",
      "remoteRtpAddress": "198.51.100.20:30456",
      "rtpPacketsSent": 1840,
      "rtpPacketsReceived": 1822,
      "createdAt": "2025-01-15T10:30:00Z",
      "ringingAt": "2025-01-15T10:30:03Z",
      "connectedAt": "2025-01-15T10:30:07Z",
      "endedAt": "2025-01-15T10:30:44Z",
      "setupSeconds": 7,
      "talkSeconds": 37,
      "hasRecording": true,
      "hasTranscript": true
    }
  ],
  "page": 0,
  "size": 25,
  "total": 1,
  "totalPages": 1
}

Call fields

FieldDescription
modeAI_AGENT, ECHO or WEBRTC.
sourceHow the call was asked for: API, WEB or WEBRTC.
placedBy, apiKeyThe user's email, and the key's public prefix when the call came through an API key.
statusREFUSED (never went out), DIALING, RINGING, CONNECTED, COMPLETED, NO_ANSWER, CANCELLED, REJECTED or FAILED.
livetrue while status is DIALING, RINGING or CONNECTED.
endReasonLOCAL_HANGUP, REMOTE_HANGUP, REJECTED, AUTH_FAILED, TIMEOUT, NO_MEDIA, FAILED, MAX_DURATION or SHUTDOWN; null while live.
error, messageFor refused or failed attempts: one of the error codes and a description.
sipStatusCode, sipReasonPhraseThe final SIP response to the INVITE, e.g. 486 Busy Here.
setupSeconds, talkSecondsSeconds from placing the call until it was answered or given up on, and seconds it was connected. null when not applicable.
hasRecording, hasTranscriptWhether the call's recording and transcript are still kept: see recordings.
other fieldsSIP and RTP details (ports, addresses, packet counts) and timestamps (createdAt, ringingAt, connectedAt, endedAt), null when unknown.

GET/calls/history/{callId}

One call with every SIP step it went through, in order, and what was said: its recording and, for AI agent calls, the transcript. Poll this after placing a call to follow its outcome.

curl https://api.kaleso.cloud/calls/history/6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10 \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"

Response 200

{
  "call": {
    "callId": "6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10",
    "destination": "+15551234567",
    "mode": "AI_AGENT",
    "status": "COMPLETED",
    "...": "same fields as a history item"
  },
  "events": [
    {
      "at": "2025-01-15T10:30:00Z",
      "direction": "OUT",
      "method": "INVITE",
      "statusCode": null,
      "reasonPhrase": null,
      "detail": null
    },
    {
      "at": "2025-01-15T10:30:03Z",
      "direction": "IN",
      "method": null,
      "statusCode": 180,
      "reasonPhrase": "Ringing",
      "detail": null
    },
    {
      "at": "2025-01-15T10:30:07Z",
      "direction": "IN",
      "method": null,
      "statusCode": 200,
      "reasonPhrase": "OK",
      "detail": null
    }
  ],
  "recording": {
    "url": "/calls/history/6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10/recording",
    "durationSeconds": 37.2,
    "sizeBytes": 1190444,
    "expiresAt": "2025-01-20T10:30:45Z"
  },
  "transcript": [
    {"speaker": "AGENT", "offsetSeconds": 0.9, "text": "Hi, this is the clinic. How can I help?"},
    {"speaker": "CALLER", "offsetSeconds": 3.4, "text": "I'd like to move my appointment to Friday."}
  ]
}

direction is OUT (we sent it), IN (the provider or other side sent it) or LOCAL (something Kaleso found or decided, such as a timeout). Returns 404 if the account has no such call.

recording is null when the call has none: it was never answered, it's still going on, or its recording was deleted. transcript holds the AI agent's conversation, line by line as OpenAI transcribed it, with speaker CALLER (the person called) or AGENT. Its offsetSeconds count from when the call was answered, the same timeline as the recording. When the caller talks over the agent, the agent's line is its whole reply, not only the part that was heard. The transcript is empty for echo and browser calls, and until OpenAI finishes transcribing each line.

GET/calls/history/{callId}/recording

The call's recording as a WAV file: 16-bit stereo at 8 kHz, with the person called on the left channel and Kaleso's side (the AI agent, the echo or your browser) on the right. Calls are recorded only if your account turns recording on in Settings (it's off by default: whether you may record depends on your compliance requirements). Recordings and transcripts are deleted after the period your account chooses, 1, 5, 30 or 90 days. The call itself stays in the history, with the keys pressed in its SIP timeline, whether or not it was recorded.

The response is a 302 redirect to a download link that works for 5 minutes. Most clients follow it themselves (with curl, pass -L). Returns 404 if the account has no such call, or the call has no recording.

curl -L -o call.wav https://api.kaleso.cloud/calls/history/6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10/recording \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"

Calls are recorded so you can review them. Where the law asks for it, tell the people you call that the call is recorded, for example in your AI agent's instructions.

GET/me

The user the key belongs to, their account, and whether the account can place calls right now. Useful as a check that your key works.

curl https://api.kaleso.cloud/me \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"

Response 200

{
  "email": "[email protected]",
  "displayName": "Ada Lovelace",
  "admin": false,
  "account": {
    "id": "0b3a1c52-8f0e-4f4c-9c53-1d2a7b9e6a44",
    "name": "Ada's account",
    "status": "ACTIVE",
    "activeUntil": "2025-02-15T00:00:00Z",
    "maxConcurrentCalls": 3,
    "billingProvider": "manual",
    "plan": "BASIC",
    "monthlyCallLimit": 1000,
    "createdAt": "2025-01-02T09:00:00Z",
    "members": []
  },
  "canCall": true,
  "entitlement": "ALLOWED",
  "entitlementMessage": "Your subscription is active",
  "plan": "BASIC",
  "monthlyCallLimit": 1000,
  "callsThisMonth": 128,
  "usageThisMonth": {"calls": 97, "billableMinutes": 212, "estimatedAmountUsd": null}
}

account.status is PENDING, ACTIVE, SUSPENDED or CANCELLED. entitlement is ALLOWED, ACCOUNT_PENDING, ACCOUNT_SUSPENDED, ACCOUNT_CANCELLED or ACTIVE_PERIOD_ENDED; when it isn't ALLOWED, calls fail with NOT_ENTITLED. account.activeUntil is when the account stops being able to call, on any plan. plan is BASIC or ENTERPRISE (null only before the account is first activated); monthlyCallLimit is null when there is no monthly cap. callsThisMonth counts calls placed this calendar month (UTC); once it reaches the limit, new calls fail with 403 NOT_ENTITLED until the 1st. usageThisMonth counts the calls answered this month and their minutes, each call rounded up to the minute; on Enterprise, which is pay as you go, estimatedAmountUsd is what that comes to at provisional rates (the monthly invoice is what counts), and it is null on other plans. See pricing.

SIP connections

The SIP trunks your account calls through. Passwords are write-only: they are never returned.

GET/sip-connections

curl https://api.kaleso.cloud/sip-connections \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"
[
  {
    "id": "c2d7f0a4-5e1b-4a8e-b0a6-0f3d9d1e2b77",
    "name": "My trunk",
    "username": "myuser",
    "domain": "sip.example-trunk.com",
    "port": null,
    "codecs": ["PCMU"],
    "transport": "UDP",
    "authUsername": null,
    "fromUser": null,
    "fromDisplayName": null,
    "outboundProxy": null,
    "register": true,
    "createdAt": "2025-01-02T09:05:00Z",
    "updatedAt": "2025-01-02T09:05:00Z"
  }
]

POST/sip-connections

FieldTypeDescription
namestring, requiredUp to 60 characters, unique in your account.
usernamestring, requiredYour SIP username.
passwordstring, required on createYour SIP password.
domainstring, requiredA public SIP server, e.g. sip.example-trunk.com. Private and local addresses are refused.
portinteger, optionalSIP port, 1–65535. Leave out for the default, 5060. Give the port here or in domain (host:port), not both.
codecsarray, optionalAudio codecs to offer, most preferred first: PCMU (G.711 µ-law, common in North America) and/or PCMA (G.711 A-law, common in Europe). Default ["PCMU"].
transportstring, optionalUDP (default) or TCP.
authUsernamestring, optionalThe username for digest authentication, when your provider's differs from username.
fromUserstring, optionalCaller ID: the user part of the From header, when it differs from username (e.g. +302101234567).
fromDisplayNamestring, optionalThe display name sent with the caller ID. Up to 64 characters, no quotes or angle brackets.
outboundProxystring, optionalhost[:port] that every SIP request is sent through, while addresses still name domain.
registerboolean, optionalWhether to REGISTER before calling. Default true; set false for IP-authenticated trunks.
curl -X POST https://api.kaleso.cloud/sip-connections \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"name":"My trunk","username":"myuser","password":"s3cret","domain":"sip.example-trunk.com",
       "codecs":["PCMA","PCMU"],"fromUser":"+302101234567"}'

Returns 201 Created with the connection (same shape as in the list). Validation failures return 400 with {"message":"..."}, for example an unknown codec, a bad port, or a private proxy address:

{"message":"You already have a SIP connection called \"My trunk\""}

PUT/sip-connections/{id}

Same body as create. Leave out password to keep the current one; any other setting you leave out also keeps its current value. Send an empty string to clear a text setting, or "port": 0 to clear the port. Returns 200 with the updated connection, 400 on validation errors, or 404 with {"message":"..."} if there is no such connection.

curl -X PUT https://api.kaleso.cloud/sip-connections/c2d7f0a4-5e1b-4a8e-b0a6-0f3d9d1e2b77 \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"name":"My trunk","username":"myuser","domain":"sip.example-trunk.com"}'

DELETE/sip-connections/{id}

curl -X DELETE https://api.kaleso.cloud/sip-connections/c2d7f0a4-5e1b-4a8e-b0a6-0f3d9d1e2b77 \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"

Returns 204 No Content, or 404 with {"message":"..."} if there is no such connection.

OpenAI settings

The OpenAI key and the voice agent's configuration. The key is stored encrypted and never returned in full.

GET/settings/openai

curl https://api.kaleso.cloud/settings/openai \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET"
{
  "hasApiKey": true,
  "apiKeyHint": "sk-…Ab3d",
  "model": "gpt-realtime-mini",
  "voice": "marin",
  "instructions": "You are a friendly receptionist for Acme Dental. Keep answers short.",
  "models": ["gpt-realtime-mini", "gpt-realtime"],
  "voices": ["alloy", "ash", "ballad", "cedar", "coral", "echo", "marin", "sage", "shimmer", "verse"]
}

apiKeyHint is null when no key is stored. instructions is null when you use the default. models and voices list the accepted values.

PUT/settings/openai

FieldTypeDescription
apiKeystring, optionalA new OpenAI key (starts with sk-). Leave out to keep the stored key.
clearApiKeyboolean, default falseRemove the stored key (ignored if apiKey is given).
modelstring, optionalOne of the values in models.
voicestring, optionalOne of the values in voices.
instructionsstring, optionalThe agent's system prompt, up to 4000 characters.
curl -X PUT https://api.kaleso.cloud/settings/openai \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "apiKey": "sk-YOUR_OPENAI_KEY",
    "model": "gpt-realtime-mini",
    "voice": "marin",
    "instructions": "You are a friendly receptionist for Acme Dental. Keep answers short."
  }'

Returns 200 with the settings in the same shape as GET. Invalid values return 400:

{"message":"That doesn't look like an OpenAI API key"}

IVR calls

An IVR call reads a prompt out, collects the keys the person presses, and goes on to the next step. There are two ways to run one, and both use the same step format:

The step format

{
  "say": "Enter your 4 digit PIN, then hash.",
  "gather": { "maxDigits": 4, "finishOnKey": "#", "timeoutSeconds": 8, "interDigitTimeoutSeconds": 3, "bargeIn": true },
  "end": { "result": "confirmed" }
}
FieldDescription
sayWhat to read out, up to 1000 characters. {{name}} is replaced by the call's variable of that name; one that isn't set reads as nothing.
gatherOptional. Collect keys once the prompt is read out.
gather.maxDigitsHow many keys to expect, 1 to 32, default 1. Collection stops as soon as that many are in.
gather.finishOnKeyOne key (0-9, * or #) that also stops collection. It isn't part of the digits.
gather.timeoutSecondsHow long to wait for the first key, 1 to 60, default 5.
gather.interDigitTimeoutSecondsHow long to wait between keys, 1 to 30, default 3.
gather.bargeInDefault true: a key pressed during the prompt stops it and counts as input.
endOptional. Makes this the last step: Kaleso reads say, records end.result (up to 100 characters, e.g. "confirmed"), carries out end.action, and hangs up. A step can't have both gather and end.
routesFlows only. Maps the keys typed to a step id, e.g. {"1": "pin", "2": "cancel"}, plus "timeout" (no key in time) and "default" (any other keys). Needs gather.
nextFlows only. Always go to this step. Use either routes or next.
idWebhook replies only, optional. A label for the step in the call history and in the gather requests.
variablesWebhook replies only, optional. Variables to set from now on, for later prompts.

Variant 1: flows

A flow has a name, an optional webhookUrl for the completed event, the start step, and its steps by id (letters, digits, - and _, up to 40 characters; at most 100 steps). Loops are fine: that is how re-prompts work. Every start, next and routes target must exist.

{
  "name": "Order confirmation",
  "webhookUrl": "https://client.example/kaleso",
  "start": "welcome",
  "steps": {
    "welcome": {
      "say": "Hi {{name}}. Press 1 to confirm order {{orderId}}, or 2 to cancel.",
      "gather": { "maxDigits": 1, "timeoutSeconds": 6 },
      "routes": { "1": "pin", "2": "cancel", "0": "agent", "timeout": "welcome", "default": "invalid" }
    },
    "invalid": { "say": "Sorry, that's not an option.", "next": "welcome" },
    "pin": {
      "say": "Enter your 4 digit PIN, then hash.",
      "gather": { "maxDigits": 4, "finishOnKey": "#", "timeoutSeconds": 8 },
      "next": "done"
    },
    "done": { "say": "Thank you. Goodbye.", "end": { "result": "confirmed" } },
    "agent": {
      "say": "Connecting you to an agent.",
      "end": { "result": "needs_agent", "action": { "type": "transfer", "to": "+35722000000" } }
    },
    "cancel": { "say": "Your order is cancelled. Goodbye.", "end": { "result": "cancelled" } }
  }
}

Save it with POST /ivr-flows (the body is the flow itself), or build it in the dashboard. A flow that doesn't validate is refused with 400 and says what is wrong where:

{
  "message": "steps.welcome.gather.maxDigits: From 1 to 32",
  "problems": [ { "path": "steps.welcome.gather.maxDigits", "message": "From 1 to 32" } ]
}

The other endpoints are GET /ivr-flows, GET, PUT and DELETE /ivr-flows/{id}, and POST /ivr-flows/validate, which answers {"valid": true, "problems": []} without saving. A flow comes back as {"id", "name", "definition", "createdAt", "updatedAt"}.

Then place calls that run it. Send flowId, or the whole flow as flow to run it without saving:

curl -X POST https://api.kaleso.cloud/calls \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "phoneNumber": "+15551234567",
    "target": "IVR Flow",
    "speechEngine": "openai",
    "ivr": {
      "flowId": "3b1f6a52-8c1e-4d0e-9a7b-2f5c0d9e41aa",
      "variables": { "name": "Maria", "orderId": "A-1042" }
    }
  }'

speechEngine works as for "Text to Speech". The response is the same as for any call.

Variant 2: webhooks

Place the call with your webhook URL (https, on the public internet):

curl -X POST https://api.kaleso.cloud/calls \
  -H "Authorization: Bearer kal_ab12cd_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "phoneNumber": "+15551234567",
    "target": "IVR Webhook",
    "ivr": { "webhookUrl": "https://client.example/kaleso", "variables": { "name": "Maria" } }
  }'

Before dialing, Kaleso POSTs the start event. Your reply is the first step, in the step format, and its audio is made before the number is dialed so there is no silence when the person answers. If this request fails, the call is refused with 502 and the number is never dialed.

POST https://client.example/kaleso
{ "event": "start", "callId": "6f1d2c1e-...", "phoneNumber": "+15551234567", "variables": { "name": "Maria" } }

200 OK
{ "say": "Hi Maria. Please enter your 4 digit PIN, then hash.", "gather": { "maxDigits": 4, "finishOnKey": "#" } }

After each step, Kaleso POSTs what it collected and your reply is the next step. A step without gather is posted right after its prompt, with endedBy "none".

POST https://client.example/kaleso
{
  "event": "gather", "step": 1, "id": null,
  "digits": "1234", "endedBy": "finishOnKey",
  "callId": "6f1d2c1e-...", "phoneNumber": "+15551234567", "variables": { "name": "Maria" }
}

200 OK
{ "say": "Thank you. Goodbye.", "end": { "result": "pin_received" } }

step counts the requests from 1; id is the label your previous reply gave, if any. endedBy is maxDigits, finishOnKey, timeout (the digits may still hold some keys) or none. The call goes on until you reply with end.

Ending actions

An end can say what should happen after its message is read out:

"end": { "result": "needs_agent", "action": { "type": "transfer", "to": "+35722000000" } }
typeFieldsMeaningToday
hangup (default)noneHang up.Carried out.
transferto (number like +35722000000, or sip:user@host), announce (optional)Connect the person to another number.Recorded only
voicemailmaxSeconds (1 to 120), beep (default true), finishOnKeyRecord a message from the person.Recorded only
callbackat (ISO 8601 time) or inMinutes, not bothCall the same number again later.Recorded only
notifychannel ("sms" or "email"), to, textSend a follow-up message.Recorded only

Only hangup is carried out for now. For the others, Kaleso checks the fields (when a flow is saved, and on webhook replies), and when the call reaches that step it records the action on the call's history (ivrEndAction with "performed": false, an IVR_ACTION event in the timeline, a line in the transcript) and in the completed event, then hangs up. This lets you design flows around them now.

The completed event

When an IVR call ends, in either variant, Kaleso POSTs a completed event to the flow's webhookUrl (flow variant) or to the call's webhook (webhook variant). It doesn't wait for a reply and retries twice in the background, after 2 and 10 seconds, if the request fails. With a webhook call it tells you how the call ended even if the person hung up before your final step.

{
  "event": "completed",
  "callId": "6f1d2c1e-3b7a-4c55-9d0e-5a2f3f6a7b10",
  "mode": "flow",
  "phoneNumber": "+15551234567",
  "status": "COMPLETED",
  "endReason": "LOCAL_HANGUP",
  "result": "needs_agent",
  "endAction": { "type": "transfer", "to": "+35722000000", "performed": false },
  "durationSeconds": 41,
  "variables": { "name": "Maria", "orderId": "A-1042" },
  "steps": [
    { "id": "welcome", "say": "Hi Maria. Press 1 to confirm order A-1042, or 2 to cancel.", "digits": "0", "endedBy": "maxDigits", "at": "2026-10-24T09:30:05Z" },
    { "id": "agent", "say": "Connecting you to an agent.", "digits": "", "endedBy": "none", "at": "2026-10-24T09:30:12Z" }
  ]
}

mode is "flow" or "webhook"; endAction is only there when the last step asked for one; endedBy can also be "hangup" when the person hung up before the step was done. The same steps and result are on the call in the history as ivrSteps, ivrResult and ivrEndAction.

Verifying the signature

Every request to your webhook carries a header made with the signing secret under Settings → Webhook signing secret:

Kaleso-Signature: t=1761298205,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e21...

v1 is the hex HMAC-SHA256, keyed with your secret, of the timestamp t (Unix seconds), a dot, and the raw request body. Compute it over the body exactly as received, compare in constant time, and turn away old timestamps to stop replays. Rotating the secret in Settings takes effect straight away.

import crypto from "node:crypto";

export function verify(header, rawBody, secret, toleranceSeconds = 300) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  if (Math.abs(Date.now() / 1000 - Number(parts.t)) > toleranceSeconds) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${parts.t}.${rawBody}`).digest("hex");
  const given = Buffer.from(parts.v1 ?? "");
  const wanted = Buffer.from(expected);
  return given.length === wanted.length && crypto.timingSafeEqual(given, wanted);
}

Failures and limits

A webhook in Node

Asks for a PIN, then ends the call. Node 18 or newer, no dependencies except the verify function above (saved as verify.js).

import http from "node:http";
import { verify } from "./verify.js";

http.createServer(async (req, res) => {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  if (!verify(req.headers["kaleso-signature"] ?? "", raw, process.env.KALESO_WEBHOOK_SECRET)) {
    res.writeHead(401).end();
    return;
  }
  const event = JSON.parse(raw);
  let step = null;
  if (event.event === "start") {
    step = { say: `Hi ${event.variables.name}. Enter your 4 digit PIN, then hash.`,
             gather: { maxDigits: 4, finishOnKey: "#", timeoutSeconds: 8 } };
  } else if (event.event === "gather") {
    step = { say: "Thank you. Goodbye.", end: { result: event.digits.length === 4 ? "pin_received" : "no_pin" } };
  } else if (event.event === "completed") {
    console.log("call over:", event.result, event.steps);
  }
  res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(step ?? {}));
}).listen(3000);

Python and Node examples

Place a call, then poll its history entry until it is no longer live.

Python

Uses only the standard library.

import json
import os
import time
import urllib.error
import urllib.request

BASE = "https://api.kaleso.cloud"
API_KEY = os.environ["KALESO_API_KEY"]  # kal_<prefix>_<secret>


def request(method, path, body=None):
    req = urllib.request.Request(
        BASE + path,
        method=method,
        data=json.dumps(body).encode() if body is not None else None,
        headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req) as res:
            return res.status, json.loads(res.read() or b"null")
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read() or b"null")


status, call = request("POST", "/calls", {
    "phoneNumber": "+15551234567",
    "sipConnection": "My trunk",
    "target": "Open AI Agent",
})
if not call["success"]:
    raise SystemExit(f"{status} {call['error']}: {call['message']}")

call_id = call["callId"]
while True:
    _, detail = request("GET", f"/calls/history/{call_id}")
    if not detail["call"]["live"]:
        break
    time.sleep(2)

print(detail["call"]["status"], detail["call"]["talkSeconds"])

Node.js

Node 18 or newer (built-in fetch), as an ES module.

const BASE = "https://api.kaleso.cloud";
const API_KEY = process.env.KALESO_API_KEY; // kal_<prefix>_<secret>

async function request(method, path, body) {
  const res = await fetch(BASE + path, {
    method,
    headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json" },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const text = await res.text();
  return { status: res.status, data: text ? JSON.parse(text) : null };
}

const { status, data: call } = await request("POST", "/calls", {
  phoneNumber: "+15551234567",
  sipConnection: "My trunk",
  target: "Open AI Agent",
});
if (!call.success) throw new Error(`${status} ${call.error}: ${call.message}`);

let detail;
do {
  await new Promise((r) => setTimeout(r, 2000));
  ({ data: detail } = await request("GET", `/calls/history/${call.callId}`));
} while (detail.call.live);

console.log(detail.call.status, detail.call.talkSeconds);

Plan limits

Your plan sets how many calls can run at once, how many you can place per month, and how long each call may last once answered (5 minutes on Basic); a call that reaches its limit is hung up with endReason MAX_DURATION. Going over the concurrency limit returns 429 CONCURRENT_LIMIT; other account limits return 403 NOT_ENTITLED. See pricing for what each plan includes.

Need help? Contact us.