Native apps
Run a conversation from an iOS, Android, Flutter, React Native, Unity or Rust app, with LiveKit's library for your platform and the API's calls.
A conversation's audio, video and events travel through a room: a live call hosted by LiveKit on Nuance's servers. In a web page, the JavaScript SDK joins the room and makes the API calls for you. In a native app (iOS, Android, Flutter, React Native, Unity or Rust), your app does this itself, with LiveKit's library for its platform and the API calls on this page.
Your app joins Nuance's room like any other LiveKit room, even if you run your own LiveKit server for other calls.
How a conversation runs
- Your server gets a session token from Nuance with your API key (Configure the conversation) and gives it to the app. Never put the API key in the app itself, where anyone can read it out.
- Your app creates the conversation with the token, then waits for Nuance to say the room is ready.
- Your app joins the room with LiveKit's library and sends the user's microphone.
- The conversation starts. Your app and the persona send each other events as messages over the room's data channel, LiveKit's way of sending small messages inside a call (Direct the persona live, Follow the conversation).
- Either side ends the conversation, and your app leaves the room.
Create the conversation
POST /conversation creates the conversation, with the session token as a bearer token:
curl -X POST https://api.nuancelabs.ai/conversation \
-H "Authorization: Bearer $SESSION_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "timezone": "Europe/London", "max_session_seconds": 300 }'The token can't start another conversation after this, but keep sending it with every later request about this conversation.
timezone is the user's IANA time zone, so the persona knows their local date and time (UTC if you leave it out). max_session_seconds is optional (Time limit). The response's id is the conversation's id, which the requests below use.
A conversation starts within a few seconds or is turned away. Handle 409 concurrency_limit, 429 credits_spent, 429 capacity_unavailable and 503 busy at least; Errors lists every response and what to do.
Poll for events
Nuance tells your app when the room is ready, and later when the conversation has ended, through GET /conversation/{id}/events. This route uses long polling: Nuance holds each request open until it has new events, or for up to 20 seconds, and then responds. It also keeps the conversation alive: if your app stops polling, Nuance ends the conversation (Keeping a conversation alive). So keep polling from creating the conversation until it ends.
curl "https://api.nuancelabs.ai/conversation/$CONVERSATION_ID/events?after=0" \
-H "Authorization: Bearer $SESSION_TOKEN"{ "events": [{ "type": "preparing", "id": 1792529097555620 }] }The response lists the events after after, oldest first, or {"events": []} if 20 seconds passed with none. As soon as a response arrives, send the next request, with after set to the largest id you've received so far.
| Event | What it means |
|---|---|
preparing | The persona is getting ready, which can take up to about half a minute. Sent at most once; some conversations skip it. |
admitted | The room is ready. Join it with this event's livekit_ and token. |
started | The persona has started. When seconds_ is set, the conversation has a time limit, counted from this response. |
ended | The conversation is over, and reason says why. No events follow it. |
- Skip event types you don't know, but still count their
idforafter. - If a request fails or times out, retry it with the same
afterafter a few seconds; no events are lost. Beforeadmitted, stop after six consecutive failures. - If the user cancels before
admitted, stop polling and callPOST /conversation/{id}/abandon(no body, withContent-Length: 0). That frees the conversation's place under your limit at once.
Join the room
When the admitted event arrives, connect to the room with LiveKit's library, using the event's livekit_url as the server URL and its token as the access token. Then publish the microphone, and the camera if you want the persona to see your user (leave out the camera line if not). In the browser, with livekit-client:
await room.connect(String(livekit_url), String(roomToken));
await room.localParticipant.setMicrophoneEnabled(true);
// Optional: let the persona see the user.
await room.localParticipant.setCameraEnabled(true);LiveKit's iOS, Android, Flutter, React Native, Unity and Rust libraries have the same two steps; the linked LiveKit pages show each one.
Capture the microphone with echo cancellation on, or the persona hears itself through the speaker and answers its own voice. Browsers and LiveKit's libraries do this when they capture the microphone; in Rust that means PlatformAudio, which uses the voice-processing audio unit on iOS. If you capture audio yourself, use your platform's voice-processing input, such as Android's VOICE_COMMUNICATION source.
The room token is for one participant, your user, so the room holds just your user and the persona. The persona listens to your user's microphone and watches their camera, and ignores screen shares. Show the persona's video and play its audio. In a browser, start from a click or tap, because browsers only play sound after the user interacts with the page.
session.started arrives once the persona can hear the microphone, and may never come without one. Keep sending microphone audio for the whole conversation, including silence.
The example below puts this page's steps into one TypeScript function for the browser, using livekit-client. A native app makes the same calls with its platform's LiveKit library. What your app sends from here is on Direct the persona live, and what comes back on Follow the conversation.
// In the browser: join a Nuance Live conversation's room with LiveKit's own
// SDK, and send and receive its events on the `nuance_live` topic.
import { Room, RoomEvent } from "livekit-client";
const NUANCE_API = "https://api.nuancelabs.ai";
const TOPIC = "nuance_live";
const CLOCK_TOPIC = "clock-sync";
/** The most one data packet may carry; a larger event goes as a text stream. */
const MAX_PACKET_BYTES = 64_000;
export type LiveEvent = { type: string } & Record<string, unknown>;
export interface LiveSession {
room: Room;
/** Sends one event; reliable, in order. */
send(event: LiveEvent): Promise<void>;
}
/** POSTs or GETs one API route with the session token, and reads its JSON. */
async function api<T>(token: string, path: string, body?: unknown): Promise<T> {
const response = await fetch(`${NUANCE_API}${path}`, {
method: body === undefined ? "GET" : "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!response.ok) {
throw new Error(
`${path} answered ${response.status}: ${await response.text()}`,
);
}
return (await response.json()) as T;
}
interface RouteEvent {
type: string;
id: number;
livekit_url?: string;
token?: string;
}
/**
* Follows the conversation's events route from `after`, calling `onEvent` for
* each; returns once `ended` comes. One request is always open, which keeps
* the conversation alive.
*/
async function follow(
token: string,
id: string,
onEvent: (event: RouteEvent) => void,
): Promise<void> {
let after = 0;
for (;;) {
const { events } = await api<{ events: RouteEvent[] }>(
token,
`/conversation/${id}/events?after=${after}`,
);
for (const event of events) {
after = event.id;
onEvent(event);
if (event.type === "ended") return;
}
}
}
/**
* Creates the conversation with `token`, joins its room with the microphone,
* and hands each Nuance Live event to `onEvent`, a `message.part` series
* joined into the event it carries. Call it from a click, so the browser
* plays the persona's audio.
*/
export async function joinNuanceLive(
token: string,
onEvent: (event: LiveEvent) => void,
): Promise<LiveSession> {
const { id } = await api<{ id: string }>(token, "/conversation", {
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});
const room = new Room();
const decoder = new TextDecoder();
let parts: string[] = [];
// #region clock
// Answer each clock ping at once, before anything else: the conversation
// waits for these before it starts.
room.on(RoomEvent.DataReceived, (payload, _participant, _kind, topic) => {
if (topic !== CLOCK_TOPIC) return;
const t1 = Date.now() / 1000;
const ping = JSON.parse(decoder.decode(payload)) as LiveEvent;
if (ping.type !== "clock_sync_ping") return;
const pong = {
type: "clock_sync_pong",
seq: ping.seq,
t0: ping.t0,
t1,
t2: Date.now() / 1000,
};
void room.localParticipant.publishData(
new TextEncoder().encode(JSON.stringify(pong)),
{ reliable: true, topic: CLOCK_TOPIC },
);
});
// #endregion clock
// #region receive
room.on(RoomEvent.DataReceived, (payload, _participant, _kind, topic) => {
if (topic !== TOPIC) return;
// #endregion receive
const event = JSON.parse(decoder.decode(payload)) as LiveEvent;
if (event.type !== "message.part") {
parts = [];
onEvent(event);
return;
}
// A part out of order drops the event being joined.
if (event.index !== parts.length) {
parts = [];
if (event.index !== 0) return;
}
parts.push(String(event.text));
if (event.index === Number(event.count) - 1) {
const whole = JSON.parse(parts.join("")) as LiveEvent;
parts = [];
onEvent(whole);
}
});
// Play the persona's audio as soon as its track arrives.
room.on(RoomEvent.TrackSubscribed, (track) => {
if (track.kind === "audio") document.body.append(track.attach());
});
const admitted = new Promise<RouteEvent>((resolve, reject) => {
follow(token, id, (event) => {
if (event.type === "admitted") resolve(event);
}).then(
() => reject(new Error("The conversation ended before it began")),
reject,
);
});
const { livekit_url, token: roomToken } = await admitted;
// #region join
await room.connect(String(livekit_url), String(roomToken));
await room.localParticipant.setMicrophoneEnabled(true);
// Optional: let the persona see the user.
await room.localParticipant.setCameraEnabled(true);
// #endregion join
const encoder = new TextEncoder();
return {
room,
async send(event) {
const text = JSON.stringify(event);
const bytes = encoder.encode(text);
// #region send
if (bytes.length <= MAX_PACKET_BYTES) {
await room.localParticipant.publishData(bytes, {
reliable: true,
topic: TOPIC,
});
} else {
await room.localParticipant.sendText(text, { topic: TOPIC });
}
// #endregion send
},
};
}
The data channel
Once your app is in the room, events go both ways over the room's data channel, LiveKit's way of sending small messages between the participants of a call (data packets). Each event is one JSON message with the topic nuance_live, sent reliably and in order.
-
Answer clock pings first. Before the conversation starts, Nuance sends pings on a separate
clock-synctopic, such as{"type": "clock_sync_ping", "seq": …, "t0": …}, and waits up to half a second for each reply. Reply right away, reliably on the same topic, with{"type": "clock_sync_pong", "seq": …, "t0": …, "t1": …, "t2": …}: copyseqandt0, and sett1to when the ping arrived andt2to when you reply, in Unix seconds.// Answer each clock ping at once, before anything else: the conversation // waits for these before it starts. room.on(RoomEvent.DataReceived, (payload, _participant, _kind, topic) => { if (topic !== CLOCK_TOPIC) return; const t1 = Date.now() / 1000; const ping = JSON.parse(decoder.decode(payload)) as LiveEvent; if (ping.type !== "clock_sync_ping") return; const pong = { type: "clock_sync_pong", seq: ping.seq, t0: ping.t0, t1, t2: Date.now() / 1000, }; void room.localParticipant.publishData( new TextEncoder().encode(JSON.stringify(pong)), { reliable: true, topic: CLOCK_TOPIC }, ); }); -
Send each event as its JSON in UTF-8, reliably, with the topic
nuance_live. Direct the persona live lists the events you can send. For example, where a web page callsconversation.sendInterfaceEvent({ type: "response.create" }), a native app publishes these bytes on thenuance_livetopic:{ "type": "response.create" }An event larger than one packet (Size limits), such as a tool result with images, goes as a text stream on the same topic instead.
if (bytes.length <= MAX_PACKET_BYTES) { await room.localParticipant.publishData(bytes, { reliable: true, topic: TOPIC, }); } else { await room.localParticipant.sendText(text, { topic: TOPIC }); } -
Receive events from the room's data-received event, keeping those whose topic is
nuance_live; each payload is one event's JSON in UTF-8. Follow the conversation lists the events you get. For example, the persona's words, which a web page gets inonInterfaceEvent, arrive as a data message onnuance_livewhose payload is:{ "type": "session.output_transcript.delta", "delta": " It's light rain", "start_ms": 41230, "end_ms": 41890 }A large event arrives split across
message.partmessages, one right after another:{ "type": "message.part", "id": "evt_41", "index": 0, "count": 2, "text": "{\"type\":\"response.event\",…" }Join the
textstrings inindexorder and parse the result once the part withindexcount - 1arrives. If another message comes between parts, or a part arrives out of order, drop the event. -
Ignore other topics, and event types and fields you don't know.
During the call, your app gets admitted and ended from polling, and every other event (Follow the conversation) from the data channel.
Tools
When the persona calls one of your tools, your app gets the tool calls as events on the data channel, runs each tool, and sends the results back. The diagram shows one tool request; the section below goes through it event by event.
How a tool request works
When the user asks for something that needs your tools, the persona starts a tool request. A tool request runs in rounds. In each round, the persona makes one or more tool calls and waits for your results; then it either starts another round of tool calls or gives the user its answer.
Every event of a tool request after the first arrives wrapped in a response.event, with the request's id in delegation_id and the actual event in event. Here is a whole tool request with one tool call, in order (shortened; the real events have more fields):
// The persona starts a tool request.
{ "type": "session.delegation.created", "delegation": { "id": "del_1", "type": "delegation", "target": "responses" } }
// Round 1: one tool call.
{ "type": "response.event", "delegation_id": "del_1", "event": { "type": "response.created", "response": { "id": "resp_1", "status": "in_progress" } } }
{ "type": "response.event", "delegation_id": "del_1", "event": { "type": "response.output_item.done", "item": { "type": "function_call", "call_id": "del_1_c1", "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" } } }
{ "type": "response.event", "delegation_id": "del_1", "event": { "type": "response.completed", "response": { "id": "resp_1", "status": "completed" } } }
// Your app sends the result, then asks the persona to continue.
{ "type": "response.item.create", "item": { "type": "function_call_output", "call_id": "del_1_c1", "output": "{\"sky\": \"light rain\", \"temperature_c\": 14}" } }
{ "type": "response.create" }
// Round 2: the answer, which the persona says in its own words.
{ "type": "response.event", "delegation_id": "del_1", "event": { "type": "response.created", "response": { "id": "resp_2", "status": "in_progress" } } }
{ "type": "response.event", "delegation_id": "del_1", "event": { "type": "response.output_item.done", "item": { "type": "message", "role": "assistant", "phase": "final_answer", "content": [{ "type": "output_text", "text": "It's light rain in Paris, 14 degrees." }] } } }
{ "type": "response.event", "delegation_id": "del_1", "event": { "type": "response.completed", "response": { "id": "resp_2", "status": "completed" } } }So, for each tool request:
- Find the tool calls. Each
response.output_item.donewhoseitem.typeisfunction_callis one tool call:item.nameis the tool, anditem.argumentsis its arguments as a JSON string. A round can have several. - Run each tool, after checking its arguments.
- Send the results. Once the round's
response.completedhas arrived and every tool call has a result, send oneresponse.item.createper tool call, with itscall_id, then oneresponse.create. To keep the persona from talking about a result, add"reply": falseto its item. - Repeat for the next round, until a round brings the answer: a
messageitem withphase: "final_answer".
Failures work as with the SDK (When a tool call fails). Other events can arrive in a round, such as response.in_progress, the answer's text streaming in response.output_text.delta, or a message item with phase: "commentary" before a tool call; skip the ones you don't need.
| Nested event | What it means |
|---|---|
response.created | A round started. |
response.output_item.done | An item is complete: a tool call (function_) to answer, or an assistant message. |
response., response. | A message's text as it streams, with the item's item_. |
response.completed | The round is complete. |
response.failed | The request failed (When a tool request fails on Nuance's side). |
End the conversation
When the user hangs up, send {"type": "session.close"} on the nuance_live topic. Wait a few seconds for session.closed, or ended on the events request if it comes first, then leave the room and stop the events request.
When the conversation ends on the persona's side, your app gets session.closed or ended unasked, and just leaves the room. Follow the conversation lists the reasons.
Nuance Live is in preview, so the API's routes and events can still change. Nuance will tell you before a change that breaks your app.