Quickstart
Build a web page where a persona greets you and holds a conversation, with a small Node server and no build step.
You'll build a small project with three files: a server that keeps your API key and gets session tokens from Nuance, a web page, and the script that puts the persona on it.
Step 0: Get an API key
Sign in to the platform and create an API key. The first time you sign in, it asks you to accept the API Developer Agreement and the Acceptable Use Policy and to verify a mobile number. Copy the key, which starts with nk_: the platform shows it only once.
Try a persona without writing code
The platform's Playground lets you talk to a persona right away: choose an API key, a persona and your own instructions, and press Start. Its Code tab shows the same settings as code you can copy.
Step 1: Set up the project
You need Node.js 20 or later. Check with node --version.
Make a folder for the project, and in it a file named .env that holds your key:
mkdir my-persona
cd my-persona
echo "NUANCE_API_KEY=nk_your_key_here" > .envReplace nk_your_key_here with your key. Keep .env out of version control, since anyone with the key can spend your credits.
Step 2: Add the server
Your server does two jobs. It sends the browser your page, and when the page requests a session token, it gets one from Nuance with your API key. The key never leaves the server.
Save this as server.mjs in your project folder:
// @ts-check
// server.mjs: serves your page and the endpoint that gets it a session token.
// Run it with: node --env-file=.env server.mjs
import { readFile } from "node:fs/promises";
import { createServer } from "node:http";
const NUANCE_API = "https://api.nuancelabs.ai";
/**
* Who is asking. Every visitor counts as the same person here, so anyone who
* can open this page can start conversations on your account. Before you put
* this anywhere public, return the id of the user your own sign-in found, and
* null when nobody is signed in.
* @param {import("node:http").IncomingMessage} _request
* @returns {string | null}
*/
function currentUserId(_request) {
return "quickstart-user";
}
/**
* Asks Nuance for a session token with your API key.
* @param {string} userId
*/
async function sessionToken(userId) {
const response = await fetch(`${NUANCE_API}/session-tokens`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.NUANCE_API_KEY}`,
"Content-Type": "application/json",
},
// Your id for the person, so a policy pause stops them, not your account.
body: JSON.stringify({ end_user_id: userId }),
});
if (!response.ok) {
// Shown in your terminal: 401 means the API key is wrong or revoked.
throw new Error(
`Nuance answered ${response.status}: ${await response.text()}`,
);
}
return (await response.json()).token;
}
const FILES = {
"/": ["index.html", "text/html"],
"/page.js": ["page.js", "text/javascript"],
};
createServer(async (request, response) => {
if (request.method === "POST" && request.url === "/api/nuance-token") {
const userId = currentUserId(request);
if (!userId) {
response.writeHead(401).end("Sign in to start a conversation");
return;
}
try {
const token = await sessionToken(userId);
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify({ token }));
} catch (error) {
console.error(error);
response.writeHead(502).end("Couldn't start a conversation");
}
return;
}
const file = FILES[/** @type {keyof typeof FILES} */ (request.url)];
if (request.method === "GET" && file) {
const body = await readFile(new URL(file[0], import.meta.url));
response.writeHead(200, { "Content-Type": file[1] }).end(body);
return;
}
response.writeHead(404).end();
}).listen(3000, () => console.log("Open http://localhost:3000"));
Before you put this online
currentUserId treats every visitor as the same person, so anyone who can open your page can start conversations on your account. That's fine on your own computer. In a real app, return the id of the user your own sign-in found, and null when nobody is signed in.
Step 3: Add the page
The page has a video for the persona, an audio element for its voice, Start and Hang up buttons, and a place to show what the persona says. Save this as index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My first persona</title>
<!-- Lets page.js import the JS SDK straight from a CDN, with no build step. -->
<script type="importmap">
{ "imports": { "@nuancelabs/js-sdk": "https://esm.sh/@nuancelabs/js-sdk@0.40.0" } }
</script>
</head>
<body>
<video id="avatar-video" autoplay playsinline width="480"></video>
<audio id="avatar-audio" autoplay></audio>
<p>
<button type="button" id="start">Start</button>
<button type="button" id="hang-up">Hang up</button>
</p>
<pre id="transcript"></pre>
<script type="module" src="/page.js"></script>
</body>
</html>
Then save the script as page.js. It asks your server for a token, starts the conversation when you press Start, plays the persona's video and voice, and writes down its words as it speaks. The persona never speaks first, so once it's in view the script asks it to say hello.
// @ts-check
// page.js: runs in the browser. It starts a conversation, shows the persona
// and writes down what the persona says.
import { createNuanceConversation } from "@nuancelabs/js-sdk";
const video = /** @type {HTMLVideoElement} */ (
document.querySelector("#avatar-video")
);
const audio = /** @type {HTMLAudioElement} */ (
document.querySelector("#avatar-audio")
);
const transcript = /** @type {HTMLElement} */ (
document.querySelector("#transcript")
);
const conversation = createNuanceConversation({
// Asks your server (server.mjs) for a session token each time a
// conversation starts.
token: async () => {
const response = await fetch("/api/nuance-token", { method: "POST" });
if (!response.ok) throw new Error(await response.text());
return (await response.json()).token;
},
});
conversation.onChange((event) => {
// The persona's video and voice have arrived: play them.
if (event.type === "tracks-changed") {
conversation.avatar.videoTrack?.attach(video);
conversation.avatar.audioTrack?.attach(audio);
}
// The persona never speaks first. Once it's in view, ask it to say hello.
if (event.type === "avatar-presented") {
void conversation.sendInterfaceEvent({
type: "response.create",
response: { instructions: "Greet the user and ask how you can help." },
});
}
if (event.type === "session-ended") {
transcript.textContent += `\n(Conversation over: ${event.reason})`;
}
});
// Write down the persona's words as it speaks them.
conversation.onInterfaceEvent((event) => {
if (event.type === "session.output_transcript.delta") {
transcript.textContent += String(event.delta);
}
});
// Browsers play sound only after a click, so start from the button.
document.querySelector("#start")?.addEventListener("click", () => {
void conversation.connect();
});
document.querySelector("#hang-up")?.addEventListener("click", () => {
void conversation.disconnect();
});
Step 4: Try it
-
In a terminal, in your project folder, start the server:
node --env-file=.env server.mjsIt prints
Open http://localhost:3000. -
Open http://localhost:3000 in Chrome, Edge, Firefox or Safari.
-
Click Start, and allow the microphone and camera when the browser asks.
-
Wait for the persona to appear and greet you. Getting it ready can take up to about half a minute.
-
Say hello. Its words show up under the video as it speaks.
-
Click Hang up when you're done. To stop the server, press
Ctrl+Cin the terminal.
If nothing happens, look at the terminal first: a line like Nuance answered 401 means the API key in .env is wrong. Then open the browser's console (F12, or Cmd+Option+J on a Mac) for errors on the page. Troubleshooting lists the other usual causes.
Next
- How a conversation works: what your server, your page and Nuance each do, step by step.
- Configure the conversation: give the persona your own prompt, pick its character, and turn its features on or off.
- Direct the persona live: tell it what is happening in your app, stop it, or keep it quiet.
- Tools: let it call your functions.
- JavaScript SDK: use the SDK from npm in your own app.