NEUBusiness

Developer docs

Connect your systems to NEU phone agents: API keys, calls, the WebSocket audio protocol, tools, webhooks and SIP.

Quick start

  1. Create an agent on the dashboard: its instructions, greeting, voice, tools and webhook.
  2. Add balance and try the agent with a test call from your browser.
  3. Connect it: route calls to its SIP address from your call centre, or create an API key and start calls from your server.
  4. Receive the result of every call at your webhook.

Start a call from your server

Request

curl -s https://api.neu.com.pk/v1/biz/calls \
  -H "Authorization: Bearer $NEU_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "<agent id>", "external_ref": "A-1001", "context": {"customer_name": "Ali", "order_id": "A-1001"}}'

# 201
{"call_id": "...", "ws_url": "wss://...", "token": "...", "expires_at": "...", "max_seconds": 600, "cents_per_min": <price>, "voice": "voice11"}

Open the WebSocket at ws_url with ?token=<token> within 120 seconds. The call then lasts up to max_seconds.

Node.js example (playPcm and nextMicFrame are yours)

// Node 22, npm install ws. Opens the call and sends 80 ms frames of 24 kHz mono PCM16.
const WebSocket = require("ws");

async function run() {
  const r = await fetch("https://api.neu.com.pk/v1/biz/calls", {
    method: "POST",
    headers: { Authorization: "Bearer " + process.env.NEU_API_KEY, "Content-Type": "application/json" },
    body: JSON.stringify({ agent_id: process.env.NEU_AGENT_ID, server_vad: true }),
  });
  const call = await r.json();
  if (r.status !== 201) throw new Error(call.error);

  const ws = new WebSocket(call.ws_url + "?token=" + encodeURIComponent(call.token)); // open within 120 s
  ws.binaryType = "nodebuffer";
  let ready = false;
  ws.on("message", data => {
    const kind = data[0], body = data.subarray(1);
    if (kind === 0x00) ready = true;                                   // ready: start sending audio
    else if (kind === 0x04) playPcm(body);                              // agent audio, PCM16 24 kHz mono
    else if (kind === 0x02) console.log("agent:", body.toString("utf8"));
    else if (kind === 0x07) console.log("event:", JSON.parse(body.toString("utf8")));
  });
  // Send audio all the time, silence too: 1 + 3,840 bytes per frame, every 80 ms.
  setInterval(() => {
    if (ws.readyState !== WebSocket.OPEN) return;
    const frame = Buffer.alloc(1 + 3840); frame[0] = 0x03;
    nextMicFrame().copy(frame, 1);                                      // 1,920 samples, int16 little-endian
    ws.send(frame);
  }, 80);
}

API keys

Create keys on the API keys page. A key looks like neu_live_ followed by 32 letters and digits. It is shown once.

Send it as Authorization: Bearer neu_live_.... Keys are for servers only: browsers on other sites cannot use them. Keys cannot create or revoke keys.

  • A revoked or unknown key gets 401 {"error":"invalid_key"}.
  • Up to 120 requests per minute per key (429 {"error":"rate_limited"}).
  • Up to 20 active keys per organisation.

API reference

Base URL https://api.neu.com.pk. JSON bodies. "Key" routes accept an API key; the others are for the dashboard.

MethodPathBody or queryAnswer
POST/v1/biz/calls{agent_id, context?, external_ref?, voice?, server_vad?}201 {call_id, ws_url, token, expires_at, max_seconds, cents_per_min, voice}
POST/v1/biz/calls/outbound{agent_id, to, context?, external_ref?, ring_seconds?}202 {call_id, status:"queued"}
GET/v1/biz/calls?limit=1-100 (50)&before=<ISO>&agent_id={calls:[call summary]} newest first
GET/v1/biz/calls/:id{call} with transcript (if kept)
GET/v1/biz/calls/:id/recordingaudio/wav, stereo 16 kHz PCM16 (left caller, right agent). 404 not_found, 410 gone
GET/v1/biz/usage?from=YYYY-MM-DD&to=YYYY-MM-DD (UTC, max 92 days, default last 30){from, to, totals:{calls, seconds, billed_seconds, cost_cents, call_fee_cents}, by_day:[...], by_agent:[...]}
GET/v1/biz/usage/exportsame querytext/csv, one row per call
GET/v1/biz/agents{agents:[agent]}
POST/v1/biz/agentsagent fields201 {agent, webhook_secret}
GET/v1/biz/agents/:id{agent}
POST/v1/biz/agents/:idany agent fields (partial update){agent}
POST/v1/biz/agents/:id/delete204
GET/v1/biz/org{org, role:"key"}
GET/v1/biz/balance{balance_cents, reserved_cents, available_cents, currency, cents_per_min, call_fee_cents, min_billed_seconds, dial_attempt_cents, minutes_left, ...}
GET/v1/biz/pricing(no key needed){cents_per_min, call_fee_cents, min_billed_seconds, dial_attempt_cents, reserved:{...}, currency:"usd"}

Call body rules

  • context: a JSON object, at most 4 KB as JSON (order details, customer name). The agent sees it, every tool request carries it, and it is deleted with the transcript.
  • external_ref: your own id for the call, at most 100 characters.
  • voice: overrides the agent's voice. An unknown voice becomes the default.
  • server_vad: true: the server detects speech for clients that cannot send 0x06 frames.
  • to: E.164, for example +923001234567. ring_seconds: 10 to 60, default 30.

Call summary and call

Shapes

call summary = {id, agent_id, channel, direction:"inbound"|"outbound"|null, status, from, to, external_ref,
  created_at, started_at, answered_at, ended_at, seconds, billed_seconds, cost_cents, call_fee_cents, ended_reason, outcome}

call = call summary + {context, handover:{requested, reason, at_s, result?} | null, tools:[{name, ok, ms}],
  transcript:[{t, who:"caller"|"agent", text, typed?}] | null, recording_available,
  webhook:{status:"pending"|"delivered"|"failed", attempts, last_code, delivered_at} | null}

cost_cents is the whole charge for the call and includes call_fee_cents. Times are ISO strings. seconds and billed_seconds are whole seconds.

channel: ws (API), test (dashboard), sip_in, sip_out. ended_reason: hangup, max_duration, error, disconnect, handover, agent_end, and for calls that never started abandoned, lost, not_dialed, ready_timeout, dial_failed.

CSV columns: call_id,created_at,agent_id,agent_name,channel,from,to,external_ref,seconds,billed_seconds,cost_cents,ended_reason,outcome_status,call_fee_cents. Numbers are empty after their retention.

Agent fields

Agent (what you send; GET also returns id, status, sip, created_at, updated_at)

{
  "name": "Order desk",
  "language": "mix",
  "voice": "voice11",
  "instructions": "You confirm cash-on-delivery orders for Example Store ...",
  "greeting": "Assalam o alaikum, main Example Store se Ayesha bol rahi hoon.",
  "tools": [{
    "name": "lookup_order",
    "description": "Find an order by its number",
    "url": "https://example.pk/ai/lookup",
    "parameters": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
    "headers": {"Authorization": "Bearer <your token>"},
    "timeout_ms": 4000
  }],
  "outcome_schema": {"type": "object", "properties": {"status": {"type": "string", "enum": ["confirmed", "cancelled", "callback"]},
                     "notes": {"type": "string"}}, "required": ["status"]},
  "handover": {"enabled": true, "method": "refer", "target": "8001", "say": "Main aap ko apne saathi se mila rahi hoon.",
               "when": "The caller asks for a person, is angry, or asks about refunds."},
  "fallback": "busy",
  "max_call_seconds": 600, "record_audio": false, "audio_days": 30, "transcript_days": 30,
  "webhook_url": "https://example.pk/ai/webhook"
}
  • name 1 to 80 characters. status active or paused (a paused agent refuses calls: 409 agent_paused).
  • language: ur (Urdu), en (English), mix (the caller's language). Default mix.
  • instructions up to 6,000 characters. greeting up to 300 (empty: the agent waits for the caller to speak first).
  • tools: at most 8. name matches ^[a-z][a-z0-9_]{1,39}$, unique, not transfer_to_human, end_call or set_outcome. description 1 to 500. parameters a JSON Schema with type:"object", at most 4 KB and 3 levels deep, using only type, properties, required, enum, items, description, minimum, maximum, minLength, maxLength. url https only, port 443 or 1024 to 65535, a public host. headers at most 5 (not Host, Content-Length or X-Neu-*), values up to 500 characters, stored encrypted; GET shows each value as "set", and sending "set" back keeps it. timeout_ms 1000 to 8000, default 4000.
  • outcome_schema: null or a JSON Schema object (same limits).
  • handover: null or {enabled, method:"refer"|"bridge", target, say, when}. target is an extension (^[0-9*#+]{1,32}$) or sip:<user>@<host>[:port]. bridge needs your outbound trunk.
  • fallback: busy (SIP 486) or handover (redirect to the handover target), used when the agent cannot answer in time or is out of balance or lines.
  • max_call_seconds 60 to 1800, default 600. record_audio default false. audio_days 1 to 90 (default 30). transcript_days 0 to 365 (default 30; 0 = the transcript is only sent in the webhook).
  • webhook_url: null or https (same host rules as tools). The webhook secret (whsec_ + 32 letters and digits) is in the create answer and from the rotate route only.
  • sip.ext: 10 digits starting with 7, made for you, never changes.

With record_audio on, the agent starts by saying "Yeh call record ho sakti hai." (ur and mix) or "This call may be recorded." (en), unless the greeting already says so.

Validation errors: 400 {"error":"invalid_agent", "field", "reason"}.

WebSocket audio protocol

Open <ws_url>?token=<token> within 120 seconds of creating the call. Every frame is binary. The first byte is the kind.

You send

KindBodyMeaning
0x03int16 little-endian PCM, 24 kHz mono, exactly 1,920 samples (3,840 bytes)Caller audio, one 80 ms frame. Send all the time, silence too.
0x06one byte: 0x01 or 0x00The caller started or stopped talking. Send it before the audio frame it belongs to. Not needed with server_vad.
0x08UTF-8 text, 1 to 1,000 bytes after trimmingA typed turn. It interrupts any reply. At most one per second; empty frames are ignored.

Frames of any other audio size are refused. A connection that sends nothing for 30 seconds is closed. Kind 0x09 is used by our SIP bridge for outbound calls; you do not need it.

You receive

KindBodyMeaning
0x00noneReady: the agent is set up. Start sending audio. If a greeting is set, the agent says it now.
0x04int16 PCM, 24 kHz monoAgent audio. Play it in order.
0x02UTF-8One complete sentence of the agent's reply, sent when its audio starts.
0x07JSON eventSee the events below.

Events (0x07)

EventMeaning
{"heard": "..."}What the caller said, as text. Typed turns come back with "typed": true.
{"state": "thinking"} / {"state": "listening"}The agent is preparing a reply / waiting for the caller.
{"flush": true, "state": "listening"}The caller interrupted: stop playing and drop any agent audio you still have queued.
{"tool": {"name", "state": "start"|"done"|"failed"}}A tool request started or finished.
{"outcome": {...}}The agent recorded the outcome (your outcome schema).
{"handover": {"reason": "..."}}The agent asked to hand the call to a person. The call then ends.
{"ended": "max_duration"|"handover"|"agent_end"}The call is over. The server closes the socket.
{"error": "busy"|"unauthorized"|"expired"|"unavailable"}The call could not run. The server closes the socket. On expired, create a new call.

To hang up, close the socket with code 1000. Getting ready can take a while after a quiet spell; give up after 90 seconds without 0x00.

Server speech detection

With server_vad: true the server works out when the caller starts and stops talking from your 0x03 audio, and ignores any 0x06 frames you send. Use it when your client cannot detect speech. Keep sending audio continuously.

Tool calls

When the agent needs something from your system, it calls one of its tools. We send a POST to the tool's url with your headers, and use your answer.

Tool request

POST https://example.pk/ai/lookup
Content-Type: application/json
X-Neu-Call: <call_id>
X-Neu-Signature: t=1764300000,v1=<hex>
Authorization: <your header value>

{"call_id": "...", "agent_id": "...", "tool": "lookup_order", "arguments": {"order_id": "A-1001"},
 "context": {...}, "external_ref": "A-1001"}
  • Answer with a 2xx status and a JSON body, within the tool's timeout_ms. The agent reads the first 4,000 characters.
  • Any other answer, a time-out or a redirect counts as a failure; the agent is told the tool failed.
  • The signature uses the agent's webhook secret, the same way as webhooks (below).
  • At most 2 tool rounds per turn and 20 tool calls per call. A request already sent is not undone if the caller interrupts, so make tools safe to repeat.

Built-in tools

  • set_outcome: the agent records the outcome against your outcome_schema.
  • transfer_to_human: the agent hands the call over, using the agent's handover settings.
  • end_call: the agent ends the call politely when it is done.

Webhooks and signatures

  1. Call ends
  2. POST to your webhookX-Neu-Signature header
  3. You check the signatureHMAC-SHA256, 5 minute window
  4. Answer 2xxelse retried 5 times

After every call we POST the result to the agent's webhook_url, with the headers Content-Type: application/json, User-Agent: NEU-Webhooks/1, X-Neu-Event: call.finished, X-Neu-Delivery: <delivery id> and X-Neu-Signature.

Body

{"type":"call.finished","id":"<delivery id>","created_at":"<ISO>",
 "call":{"id":"...","agent_id":"...","channel":"sip_in","direction":"inbound","from":"+923001234567","to":"7012345678",
   "external_ref":"A-1001","context":{...},"started_at":"...","answered_at":"...","ended_at":"...",
   "seconds":74,"billed_seconds":74,"cost_cents":<cost>,"call_fee_cents":<fee>,"ended_reason":"handover",
   "outcome":{"status":"confirmed"},
   "handover":{"requested":true,"reason":"asked for a person","at_s":70.2,"result":"done"},
   "tools":[{"name":"lookup_order","ok":true,"ms":412}],
   "transcript":[{"t":0.4,"who":"agent","text":"..."},{"t":3.1,"who":"caller","text":"..."}],
   "recording_url":"https://api.neu.com.pk/v1/biz/calls/<id>/recording"}}
  • Any 2xx answer within 10 seconds counts as delivered. Redirects are not followed.
  • Retries after 1, 5, 15, 60 and 180 minutes, then the delivery is marked failed.
  • SIP calls are sent at least 10 seconds after the call ends, so handover results are included.
  • recording_url is null without audio. Downloading it needs your API key.

Check the signature

X-Neu-Signature: t=<unix seconds>,v1=<hex> where v1 is HMAC-SHA256 with the webhook secret (its UTF-8 bytes) as the key, over <t>.<raw body>. Compare in constant time and reject when t is more than 300 seconds from your clock.

Node.js

const crypto = require("node:crypto");

// header: the X-Neu-Signature value, "t=<unix seconds>,v1=<hex>"
// rawBody: the request body exactly as received (a string or Buffer), before any JSON parsing
// secret: the agent's webhook secret, "whsec_..."
function verifyNeuSignature(rawBody, header, secret, now = Math.floor(Date.now() / 1000)) {
  const parts = {};
  for (const piece of String(header || "").split(",")) {
    const i = piece.indexOf("=");
    if (i > 0) parts[piece.slice(0, i).trim()] = piece.slice(i + 1).trim();
  }
  const t = Number(parts.t);
  if (!Number.isInteger(t) || !/^[0-9a-f]{64}$/.test(parts.v1 || "")) return false;
  if (Math.abs(now - t) > 300) return false; // older than 5 minutes: reject
  const expected = crypto.createHmac("sha256", Buffer.from(secret, "utf8"))
    .update(t + "." + rawBody).digest("hex");
  return crypto.timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(parts.v1, "hex"));
}

module.exports = { verifyNeuSignature };

Node.js with Express

const express = require("express");
const { verifyNeuSignature } = require("./verify");

const app = express();
// Keep the raw body: the signature is over the exact bytes we sent.
app.post("/ai/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const ok = verifyNeuSignature(req.body.toString("utf8"), req.get("X-Neu-Signature"), process.env.NEU_WEBHOOK_SECRET);
  if (!ok) return res.status(400).end();
  const event = JSON.parse(req.body.toString("utf8"));
  // event.type === "call.finished"; event.id is the delivery id (use it to skip repeats)
  console.log(event.call.id, event.call.outcome);
  res.status(200).end(); // any 2xx counts as delivered
});
app.listen(3000);

Python

import hashlib
import hmac
import time


def verify_neu_signature(raw_body, header, secret, now=None):
    """header: the X-Neu-Signature value. raw_body: the request body bytes exactly as received."""
    parts = {}
    for piece in (header or "").split(","):
        key, sep, value = piece.partition("=")
        if sep:
            parts[key.strip()] = value.strip()
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if abs((int(time.time()) if now is None else now) - t) > 300:  # older than 5 minutes: reject
        return False
    signed = str(t).encode() + b"." + raw_body
    expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))

Python with Flask

from flask import Flask, request, abort
import os

app = Flask(__name__)

@app.post("/ai/webhook")
def webhook():
    if not verify_neu_signature(request.get_data(), request.headers.get("X-Neu-Signature", ""), os.environ["NEU_WEBHOOK_SECRET"]):
        abort(400)
    event = request.get_json()
    print(event["call"]["id"], event["call"].get("outcome"))
    return "", 200

SIP setup

  1. Caller
  2. Your PBXVicidial, Asterisk, ZIWO, Genesys
  3. NEU agentsip:<extension>@sip.neu.com.pk
  4. Back to your teamtransfer (REFER) on handover

Each agent has its own address: sip:<extension>@sip.neu.com.pk. The extension is 10 digits and starts with 7. It never changes.

  • Port 5060, UDP or TCP. Encryption (TLS and SRTP) is not available yet.
  • Audio (RTP) comes from our UDP ports 10000 to 10999. Allow them in your firewall.
  • Codecs: G.711 a-law (PCMA, preferred) and u-law (PCMU), 20 ms packets.
  • Key presses (DTMF) are ignored.
  • Sign-in: your organisation's IP allow-list, or a SIP password per agent (user name = the extension, realm sip.neu.com.pk). Calls with neither are refused.
  • The caller hears ringing until the agent is ready, for up to 20 seconds. Set your ring timeout to at least 25 seconds.
  • If the agent cannot answer in time, or the balance or lines run out, it follows its fallback: busy (SIP 486, so your queue moves on) or a redirect (SIP 302) to the handover target.
  • Handover sends a transfer (SIP REFER) back to your system. If your system refuses it and you have added an outbound trunk, the agent connects the caller through the trunk instead.

Vicidial and Asterisk

  1. Add your call centre's public SIP address to the allow-list on the SIP page, or set a SIP password for the agent.
  2. Create a SIP peer or trunk to sip.neu.com.pk, port 5060, UDP or TCP. Codecs: G.711 a-law (alaw, preferred) and u-law (ulaw), 20 ms packets.
  3. Route calls to the agent's extension on that trunk: from a queue, an extension, an IVR choice, or a Vicidial campaign or in-group ("transfer to closer" or "route to").
  4. Set your ring timeout to the agent to at least 25 seconds. The agent can take up to 20 seconds to get ready while the caller hears ringing.
  5. For handover, allow transfers (SIP REFER) from our address, and set the agent's handover target to an extension or queue on your system.

Example for Asterisk with PJSIP. Adapt the names to your setup.

pjsip.conf

; pjsip.conf: a trunk to the NEU agent (IP allow-list sign-in)
[neu]
type=endpoint
transport=transport-udp
context=from-neu
disallow=all
allow=alaw,ulaw
aors=neu
direct_media=no

[neu]
type=aor
contact=sip:sip.neu.com.pk:5060

[neu]
type=identify
endpoint=neu
match=sip.neu.com.pk

; With a SIP password instead: one endpoint per agent, dialled as PJSIP/7012345678@neu-7012345678
[neu-7012345678]
type=endpoint
transport=transport-udp
context=from-neu
disallow=all
allow=alaw,ulaw
aors=neu
direct_media=no
from_user=7012345678
outbound_auth=neu-7012345678-auth

[neu-7012345678-auth]
type=auth
auth_type=userpass
username=7012345678
realm=sip.neu.com.pk
password=<the SIP password from the dashboard>

extensions.conf

; extensions.conf: send queue overflow or an IVR choice to the agent (extension 7012345678)
[from-internal]
exten => 8500,1,Dial(PJSIP/7012345678@neu,30)
 same => n,Hangup()

; Handover target: calls the agent transfers back arrive at extension 8001 in this context
[from-neu]
exten => 8001,1,Queue(support)

Most Vicidial servers use chan_sip carriers. Put this in the carrier's Account Entry and Dialplan Entry. Handover targets, such as an In-Group extension, go in the trunkinbound context.

Vicidial carrier

; Vicidial carrier, Account Entry (chan_sip), IP allow-list sign-in
[neu]
type=peer
host=sip.neu.com.pk
port=5060
disallow=all
allow=alaw
allow=ulaw
insecure=port,invite
qualify=no
context=trunkinbound
; With a SIP password instead, add:
;   defaultuser=7012345678
;   fromuser=7012345678
;   fromdomain=sip.neu.com.pk
;   secret=<the SIP password from the dashboard>

; Dialplan Entry: send calls to the agent (ring for up to 30 seconds)
exten => 7012345678,1,Dial(SIP/neu/7012345678,30)
 same => n,Hangup()

ZIWO and other cloud call centres

  1. Add an external SIP endpoint, SIP trunk or "SIP URI" destination that points at the agent's address, for example sip:7012345678@sip.neu.com.pk, port 5060, UDP or TCP.
  2. Choose G.711 (PCMA or PCMU) as the codec.
  3. Ask your provider for the public IP addresses their SIP traffic comes from, and add them to the allow-list on the SIP page. If they cannot give fixed addresses, set a SIP password for the agent and enter the extension as the user name.
  4. Send calls to that destination from a queue overflow, an IVR choice or a routing rule. Keep the ring timeout at 25 seconds or more.
  5. For handover, set the agent's handover target to a queue number or extension your system accepts transfers to.

Genesys Cloud (BYOC)

  1. Create a BYOC Cloud external trunk with the SIP server sip.neu.com.pk, port 5060, protocol UDP or TCP. TLS is not available yet.
  2. Set the codecs to PCMA and PCMU.
  3. If you use a SIP password, enter the agent's extension as the user name and the password from the dashboard. Otherwise add the Genesys Cloud media and signalling addresses for your region to the allow-list on the SIP page.
  4. In Architect, transfer the call to the external number or SIP address sip:<extension>@sip.neu.com.pk over that trunk.
  5. Keep the transfer ring time at 25 seconds or more. For handover, use a queue or number your Genesys setup can take back.

Menu names differ between versions. Check your provider's documentation for where each setting lives.

Outbound calls

Outbound calls go through your own SIP trunk: we never provide phone lines. Add the trunk on the SIP page. It must accept calls from our address (the one sip.neu.com.pk points to).

The agent gets ready before the number is dialled, so the person never waits for it. The call is billed from the moment they answer, plus a fee per dial attempt.

Start one with POST /v1/biz/calls/outbound {agent_id, to, context?, external_ref?, ring_seconds?}. Outbound calls are only placed during the allowed calling hours (Pakistan time); outside them you get 409 outside_hours.

Billing

Loading prices…

Errors

Errors come as JSON {"error": "<code>"} with an HTTP status.

StatusCodeMeaning
400invalid_agentAn agent field is wrong (with field and reason), or the agent id is not valid.
400invalid_contextcontext is not a JSON object of 4 KB or less.
400invalid_numberto is not an E.164 number.
400invalid_external_refexternal_ref is not a string of 100 characters or less.
400invalid_rangeUsage dates are not YYYY-MM-DD, from is after to, or the range is over 92 days.
401invalid_keyThe API key is unknown or revoked.
402no_balanceNot enough available balance to start a call.
403org_suspendedThe organisation is suspended.
404agent_not_foundNo such agent in your organisation.
404not_foundNo such call or resource.
409agent_pausedThe agent is paused.
409no_trunkOutbound needs your SIP trunk.
409outside_hoursOutside the allowed calling hours.
410goneThe recording expired or was not made.
429org_busyYour organisation has reached its calls at the same time.
429rate_limitedToo many requests: 120 per minute per key, 60 call creations per minute per organisation.
503capacityAll shared lines are busy. Try again shortly.
503busyCalls are not available right now.
503outbound_closedOutbound calls are turned off.

Ready to try it? Create a business account.