Conversations guide
This guide walks through a complete chat with the Conversations API, then a web voice call. Every endpoint is listed in the Conversations API reference.
Base URL: https://api.nuacem.dev/voice-gw
Before you start
Section titled “Before you start”You need:
- A live agent (
agt_xxxx) with Web chat switched on, or a use case (uc_xxxx) whose entry agent has it. For web calls the agent needs Web calls switched on. - An API key. The examples use a secret key from a server. From a web page, use a publishable key instead; the calls are the same. See Authentication.
If you build for a browser, the Node / browser SDK or the web widget does all of this for you.
How a chat works
Section titled “How a chat works”POST /public/v1/text/sessionswith your key. You get asessionIdand a sessiontoken.POST /public/v1/text/sessions/{sessionId}/messageswithAuthorization: Bearer <token>. The reply streams back as server-sent events.- Repeat step 2 for each message. Send one message at a time.
- Optionally rate the chat, then
DELETE /public/v1/text/sessions/{sessionId}to end it.
Step 1: Start a chat
Section titled “Step 1: Start a chat”curl -X POST "https://api.nuacem.dev/voice-gw/public/v1/text/sessions" \ -H "X-VoiceCX-Key: $NUACEMONE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"agentId": "agt_xxxx", "userId": "cust-42", "language": "en"}'const BASE = 'https://api.nuacem.dev/voice-gw/public/v1';const KEY = process.env.NUACEMONE_SECRET_KEY;
async function startChat(agentId, userId) { const res = await fetch(`${BASE}/text/sessions`, { method: 'POST', headers: { 'X-VoiceCX-Key': KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ agentId, userId }), }); if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`); return res.json();}
const session = await startChat('agt_xxxx', 'cust-42');import jsonimport os
import httpx
BASE = "https://api.nuacem.dev/voice-gw/public/v1"KEY = os.environ["NUACEMONE_SECRET_KEY"]
def start_chat(agent_id: str, user_id: str) -> dict: r = httpx.post(f"{BASE}/text/sessions", headers={"X-VoiceCX-Key": KEY}, json={"agentId": agent_id, "userId": user_id}, timeout=30) r.raise_for_status() return r.json()
session = start_chat("agt_xxxx", "cust-42")To reach a use case, send "useCaseId": "uc_xxxx" instead of agentId. Send one or the other, never both.
Request fields
Section titled “Request fields”| Field | Required | Notes |
|---|---|---|
agentId or useCaseId |
Yes, one of them | The live agent, or the use case whose entry agent answers. |
language |
No | For example en or hi. A language the agent does not speak falls back to its default language. |
visitorId |
No | Your stable anonymous id for this visitor: 8 to 80 letters, digits, - or _. Reuse it for the same person so limits and history follow them. If you leave it out, one is created and returned. |
userId |
No | Your id for a signed-in user (up to 200 characters). Accepted alone with a secret key; with a publishable key it needs userHash. See Signed users. |
userHash |
No | hex(HMAC-SHA256(identity secret, userId)), computed on your server. |
profile |
No | Up to 10 answers from your own pre-chat form, such as {"name": "Asha", "city": "Pune"}. Keys are 1 to 32 lower-case letters, digits or _, starting with a letter. Values are up to 200 characters. name becomes the contact’s display name. Nothing here verifies who the user is. |
Response (201)
Section titled “Response (201)”{ "sessionId": "5f0c2a8e-3b1d-4c55-9e0a-7d2f1b6c9a10", "token": "eyJzaWQiOi...b3Jn.Xq9...", "visitorId": "vis_0f3c...", "language": "en", "greeting": "Hello! How can I help you today?", "expiresIn": 7200, "maxMessageChars": 4000, "voiceNotes": false, "attachmentMode": "always", "replies": false, "richMessages": false, "replyDelivery": "stream"}| Field | Meaning |
|---|---|
sessionId, token |
Use these for every later call in this chat. |
greeting |
The agent’s opening message, or null. Show it before the visitor types. |
expiresIn |
Seconds until the token expires (the chat’s maximum length). |
maxMessageChars |
The longest message the chat accepts. |
voiceNotes |
true when you may send voice notes. |
attachmentMode |
When to offer file sharing: always, never, or llm (only after the agent asks for a file). |
replies |
true when a message may reply to an earlier one (replyTo). |
richMessages |
true when replies may carry a rich block. |
replyDelivery |
stream (replies arrive piece by piece) or complete (the reply arrives once it is finished). |
Step 2: Send a message and stream the reply
Section titled “Step 2: Send a message and stream the reply”Send the message with the session token. The response is a text/event-stream. Each event has a name and a JSON data line:
event: statusdata: {"kind": "search"}
event: deltadata: {"text": "Your EMI of ₹12,400 "}
event: deltadata: {"text": "is due on 5 December."}
event: messagedata: {"text": "Your EMI of ₹12,400 is due on 5 December."}
event: donedata: {"turns": 1}curl -N -X POST "https://api.nuacem.dev/voice-gw/public/v1/text/sessions/$SESSION_ID/messages" \ -H "Authorization: Bearer $SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{"text": "When is my EMI due?"}'-N turns off buffering so you see events as they arrive.
// Node 18+ (fetch is built in). Calls onEvent(name, data) for each server-sent event.async function send(session, text, onEvent) { const res = await fetch(`${BASE}/text/sessions/${session.sessionId}/messages`, { method: 'POST', headers: { Authorization: `Bearer ${session.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ text }), }); if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`); const decoder = new TextDecoder(); let buffer = ''; for await (const chunk of res.body) { buffer += decoder.decode(chunk, { stream: true }); let end; while ((end = buffer.indexOf('\n\n')) !== -1) { const block = buffer.slice(0, end); buffer = buffer.slice(end + 2); let event = ''; let data = ''; for (const line of block.split('\n')) { if (line.startsWith('event: ')) event = line.slice(7); else if (line.startsWith('data: ')) data += line.slice(6); } if (event && data) onEvent(event, JSON.parse(data)); } }}
let reply = '';await send(session, 'When is my EMI due?', (event, data) => { if (event === 'delta') process.stdout.write(data.text); if (event === 'message') reply = data.text; if (event === 'error') console.error(data.code, data.message);});def send(session: dict, text: str): """Yields (event, data) pairs as the reply streams.""" url = f"{BASE}/text/sessions/{session['sessionId']}/messages" headers = {"Authorization": f"Bearer {session['token']}"} with httpx.stream("POST", url, headers=headers, json={"text": text}, timeout=180) as r: r.raise_for_status() event = None for line in r.iter_lines(): if line.startswith("event: "): event = line[7:] elif line.startswith("data: ") and event: yield event, json.loads(line[6:]) event = None
reply = ""for event, data in send(session, "When is my EMI due?"): if event == "delta": print(data["text"], end="", flush=True) elif event == "message": reply = data["text"] elif event == "error": print(data["code"], data["message"])Message body
Section titled “Message body”| Field | Notes |
|---|---|
text |
The visitor’s message, up to maxMessageChars. May be empty only when fileIds or postback is sent. |
fileIds |
Accepted files to send with this message. See Files. |
replyTo |
{"role": "assistant" or "user", "text": "..."}: the earlier message this one answers, when replies is true. The quote is used only if it matches a message in this chat; otherwise it is dropped and the message goes on as typed. |
postback |
{"blockId": "...", "value": "..."}: a tap on a rich block, when richMessages is true. See Rich messages. |
Stream events
Section titled “Stream events”| Event | Data | What to do |
|---|---|---|
delta |
{"text"} |
The next piece of the reply. Append it to what you show. |
status |
{"kind"} |
What the agent is doing: tool, search, consult, workflow or handoff. Show a hint such as “Looking that up”. No details are sent. With kind: "live_agent" it also carries state and text (see Live agent handoff). |
preparing |
{"kind": "rich"} |
A rich block is likely. No more delta events will come for this reply; show a placeholder until message. |
message |
{"text", ...} |
The full, final reply. Replace the streamed text with text. It may also carry language (the chat switched language), requestFile and fileHint (the agent asked for a file), and block with blockText (a rich block). |
step_complete |
{"outcome"} |
The conversation finished a workflow step with this outcome. Most clients ignore it. |
done |
{"turns"} |
The turn is over. turns is the number of visitor messages so far. |
error |
{"code", "message"} |
The turn failed. The stream ends. message is safe to show. See Errors. |
Every stream ends with either done or error. Treat message as the source of truth for the reply text; delta events are only for showing progress. Ignore event names you do not know.
When replyDelivery is complete, no delta arrives until the reply is finished; then one delta with the whole text, then message. A reply to a message with files also arrives in one piece.
One message at a time
Section titled “One message at a time”Wait for done or error before you send the next message. A message sent while a reply is still streaming gets 409 turn_in_progress. A chat accepts a fixed number of visitor messages (60 by default); after that, messages get 409 chat_limit_reached and you should start a new chat.
Rich messages
Section titled “Rich messages”When the start response has richMessages: true, a message event may carry a block: cards, a carousel, a list, a table, a summary, buttons, quick replies or a slot picker. blockText is the text to show above it, and text is still the full reply, so a client that draws no blocks can show text and ignore block.
Each block has an id. When the visitor taps an option, send it as the next message:
{ "text": "Dr. Rao", "postback": { "blockId": "blk_xxxx", "value": "102" } }text is optional with a postback; the server knows the option’s label. An option that is no longer valid answers 409 postback_unknown: ask the visitor to type their answer instead. Block text is plain text; never insert it into a page as HTML. In a browser, the Node / browser SDK can load the same renderer the web widget uses.
When attachmentMode is always, or llm after a message event with requestFile: true, the visitor can share a file. Accepted types are PDF, Word (.docx), Excel (.xlsx), CSV and plain text. By default a chat takes 5 files of up to 10 MB each; your organisation may have different limits.
-
Upload the file’s bytes as the request body, with its name in the query string:
Terminal window curl -X POST "https://api.nuacem.dev/voice-gw/public/v1/text/sessions/$SESSION_ID/files?name=statement.pdf" \-H "Authorization: Bearer $SESSION_TOKEN" \-H "Content-Type: application/octet-stream" \--data-binary @statement.pdf -
Read the answer (201). Every file is checked, scanned for malware and read before it is accepted:
{"fileId": "fil_xxxx", "name": "statement.pdf", "kind": "pdf", "sizeBytes": 482113,"status": "accepted", "code": null, "message": null, "pages": 3, "truncated": false, "filesLeft": 4}A blocked file also answers 201, with
status: "blocked", acode(malicious,type_not_allowed,unreadable,no_textortoo_large) and amessageto show the visitor. Do not send a blocked file. -
Send accepted files with the next message.
textmay be empty:{ "text": "Summarise this statement", "fileIds": ["fil_xxxx"] }
At most 5 files go with one message. A file can be sent once. Programs, scripts and files with macros are always refused. With attachmentMode: "never" uploads answer 403 files_disabled.
Voice notes
Section titled “Voice notes”When the start response has voiceNotes: true, the visitor can record a voice note instead of typing. Send the recording as the body, with the browser’s audio type:
curl -X POST "https://api.nuacem.dev/voice-gw/public/v1/text/sessions/$SESSION_ID/voice-notes" \ -H "Authorization: Bearer $SESSION_TOKEN" \ -H "Content-Type: audio/webm" \ --data-binary @note.webmAccepted types include audio/webm, audio/ogg, audio/mp4, audio/mpeg, audio/aac and audio/wav. Keep notes under 2 minutes. The answer is the text:
{ "text": "I want to change my delivery address" }The audio is not kept. Show the text to the visitor and send it as the next message. An unclear recording answers 422 voice_note_unclear with a message to show; ask the visitor to try again or type.
Feedback
Section titled “Feedback”The visitor can rate the chat once, from 1 to 5, with an optional comment of up to 1,000 characters:
curl -X POST "https://api.nuacem.dev/voice-gw/public/v1/text/sessions/$SESSION_ID/feedback" \ -H "Authorization: Bearer $SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{"rating": 5, "comment": "Quick and clear"}'The answer is 204 No Content. A second rating answers 409 feedback_given. Rate before you end the chat.
End the chat
Section titled “End the chat”curl -X DELETE "https://api.nuacem.dev/voice-gw/public/v1/text/sessions/$SESSION_ID" \ -H "Authorization: Bearer $SESSION_TOKEN"The answer is 204 No Content, also when the chat had already ended. Ending a chat frees one of the visitor’s open-chat places (see Rate limits). A chat you do not end closes by itself after it has been idle for a while.
Live agent handoff
Section titled “Live agent handoff”If your organisation hands chats to people on a live agent platform, a reply may end with a status event of kind live_agent:
{ "kind": "live_agent", "state": "pending", "text": "Connecting you to a member of our team..." }From then on the agent stays silent. The visitor’s messages go to the person, and each send answers only a status event and done. To show the person’s replies, poll the events endpoint with the same session token:
curl "https://api.nuacem.dev/voice-gw/public/v1/text/sessions/$SESSION_ID/events?after=0" \ -H "Authorization: Bearer $SESSION_TOKEN"{ "events": [ { "type": "status", "state": "active", "name": "Priya", "id": "1732350001234-0" }, { "type": "message", "name": "Priya", "text": "Hi, I can help with that.", "id": "1732350004567-0" } ], "cursor": "1732350004567-0"}- Send the last
cursorasafteron the next call;0returns everything. - The call waits up to 20 seconds for something new before it answers with an empty list (a long poll). Pass
wait(0 to 25 seconds) to change that. stateispending(waiting for a person),active(a person has joined),closed(the person left and the agent takes over again) orended(the chat is over).- The endpoint answers
404 not_enabledwhen live agent handoff is not set up for your organisation.
Web voice calls
Section titled “Web voice calls”A web call connects the visitor’s microphone to a live voice agent over WebRTC, using LiveKit.
-
Start the call with your key. The body takes the same
agentIdoruseCaseId,language,visitorId,userIdanduserHashfields as a chat:Terminal window curl -X POST "https://api.nuacem.dev/voice-gw/public/v1/voice/sessions" \-H "X-VoiceCX-Key: $NUACEMONE_PUBLISHABLE_KEY" \-H "Content-Type: application/json" \-H "Origin: https://www.example.com" \-d '{"agentId": "agt_xxxx"}'{"sessionId": "8c1d...", "livekitUrl": "wss://...", "token": "eyJhbGciOi...","visitorId": "vis_...", "language": "en", "maxDurationSeconds": 900,"silenceCheckSeconds": 15, "silenceEndSeconds": 15, "callToken": "eyJzaWQiOi..."} -
Join the room with a LiveKit client SDK and turn on the microphone. In a browser:
import { Room, RoomEvent } from 'livekit-client';const room = new Room();room.on(RoomEvent.TrackSubscribed, (track) => {if (track.kind === 'audio') document.body.appendChild(track.attach());});await room.connect(call.livekitUrl, call.token);await room.localParticipant.setMicrophoneEnabled(true);// Hang up: leaving the room ends the call.await room.disconnect();
The call ends when the visitor leaves the room, at your organisation’s maximum call length (maxDurationSeconds, null when there is none), or after a stretch of silence: after silenceCheckSeconds the agent asks if the caller is still there, and after a further silenceEndSeconds it says goodbye and hangs up.
A web call uses one of your organisation’s concurrent call places, shared with phone calls. When all are in use, the start answers 429 lines_busy.
After the call, use callToken to rate it or read a short summary:
curl -X POST "https://api.nuacem.dev/voice-gw/public/v1/voice/sessions/$CALL_ID/feedback" \ -H "Authorization: Bearer $CALL_TOKEN" -H "Content-Type: application/json" \ -d '{"rating": 4}'
curl "https://api.nuacem.dev/voice-gw/public/v1/voice/sessions/$CALL_ID/summary" \ -H "Authorization: Bearer $CALL_TOKEN"The summary answers {"status": ...}: off (summaries are not enabled), pending (being written; ask again in a few seconds), ready with points, none or failed.
Calls that continue a chat
Section titled “Calls that continue a chat”To start a call from an open chat, so the call’s turns are added to the same conversation, send the chat’s sessionId as chatSessionId and its token as chatToken when you start the call. A token that does not match answers 403 chat_link_refused.