Node.js TTS Pipeline with an LLM Text API
For node.js tts work, Node has no speech engine built in, so the usual design is a script writer in front of a speech step. Here is how to build the script writer with an OpenAI-compatible text API, including streaming, JSON mode and tool calls.
Updated

Key points
- Install the openai package, change the base URL, use model uncensored. Nothing else about the client changes.
- Stream the answer and cut it into sentences, so speech can start before the text is finished.
- JSON mode or tool calls give you speaker and pace fields you can map to voices.
- Handle HTTP 429 with the Retry-After header, and cap concurrency at 8 on a full key.
The shape of a Node text-to-speech pipeline
If you search for node.js tts you will find packages that wrap a speech engine, packages that call a hosted voice service, and tutorials that shell out to a command-line synthesizer. They all solve the same last step: turn a string into sound. What they do not solve is where the string comes from. In a game, an audiobook tool, a companion app or a narrated dashboard, somebody has to write the text, and writing it by hand does not scale.
This article covers that first step. The hosted API on this site speaks the OpenAI Chat Completions format, so the official openai package in Node works against it after you change the base URL and the key. The model ID is uncensored. The response is text. There is no audio endpoint, so you pair it with a speech engine of your choice, local or hosted, and the examples show a swap-in point for that engine.
The pipeline has four small stages: build a prompt, get text from the API, split the text into units a speech engine can handle, and play or save each unit. The sections below build those stages one at a time, starting with the smallest working call. The quickstart in the docs has the same request in other languages if you want to compare.
Step 1: the smallest working call
Create a project, set "type": "module" in package.json so top-level await works, and run npm install openai. Get a key from the API key page and export it as NSFWTTS_KEY.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.nsfwtts.cc/v1",
apiKey: process.env.NSFWTTS_KEY,
});
const res = await client.chat.completions.create({
model: "uncensored",
messages: [
{ role: "system", content: "Write narration meant to be read aloud. Plain sentences, no markdown." },
{ role: "user", content: "Two sentences announcing that the night shift is starting." },
],
});
console.log(res.choices[0].message.content);
console.log(res.usage); // prompt_tokens, completion_tokens
Run it with node index.js. You should see two sentences and a usage object. If you get a 401, the key is wrong or the header is missing. If you get a network error, check that the base URL ends in /v1 and has no trailing slash.
The same request as plain HTTP is POST https://api.nsfwtts.cc/v1/chat/completions with Authorization: Bearer <key>. Only chat/completions and GET /v1/models exist on this service, so do not look for embeddings or audio routes.
A word on the prompt. Text for speech needs its own style rules: write for the ear, spell out symbols, avoid parentheses and markdown. Put these in the system message instead of cleaning the output with regular expressions afterwards. A model that is told once is more reliable than a regex that has to guess.
Step 2: stream and speak by sentence
Waiting for a full paragraph before the first sound is the main reason a voice pipeline feels slow. Streaming fixes that. With stream: true the API sends Server-Sent Events, and the SDK turns them into an async iterator. The trick is to collect tokens in a buffer and release a sentence as soon as it ends.
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://api.nsfwtts.cc/v1", apiKey: process.env.NSFWTTS_KEY });
export async function* sentences(messages) {
const stream = await client.chat.completions.create({
model: "uncensored",
messages,
stream: true,
});
let buffer = "";
for await (const chunk of stream) {
buffer += chunk.choices[0]?.delta?.content ?? "";
// cut at a period, question or exclamation mark followed by a space or the end of the buffer
let match;
while ((match = buffer.match(/^(.+?[.?\u0021])(\s+|$)/s)) && match[0].length < buffer.length) {
yield match[1];
buffer = buffer.slice(match[0].length);
}
}
if (buffer.trim()) yield buffer.trim();
}
The regular expression looks for a sentence-ending mark followed by whitespace, which avoids cutting at a full stop at the very end of the buffer when more text might still arrive. Whatever remains when the stream closes is yielded at the end. The API reports usage at the end of a stream, so the last chunk is the place to log token counts and cost per clip.
Now connect it to a speech step. The example uses espeak-ng, a free command-line synthesizer, only because it needs no account. Replace the body of speak with a call to your own engine.
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { sentences } from "./stream.js"; // talks to https://api.nsfwtts.cc/v1
const run = promisify(execFile);
// Replace this with a call to whatever speech engine you use.
async function speak(text) {
await run("espeak-ng", ["-s", "160", text]);
}
const messages = [
{ role: "system", content: "You are a calm narrator. Plain sentences only." },
{ role: "user", content: "Describe a train arriving at an empty station at dawn." },
];
for await (const line of sentences(messages)) {
console.log(line);
await speak(line); // speaks sentence 1 while the model is still writing sentence 3
}
Abbreviations such as "Dr." or "e.g." can trigger a false sentence break. If your content has many, ask the model in the system prompt to avoid abbreviations; it costs nothing and removes the problem at the source.
Step 3: structured scripts with JSON mode
Once you have more than one voice, plain text stops being enough. You need to know who says each line. JSON mode forces the reply to be a valid JSON object, which you can parse and loop over. Set response_format: {"type": "json_object"} and also describe the shape you want in the prompt, because the flag guarantees valid JSON, not your particular fields.
// client created with baseURL "https://api.nsfwtts.cc/v1", as in step 1
const res = await client.chat.completions.create({
model: "uncensored",
response_format: { type: "json_object" },
messages: [
{
role: "system",
content:
"Return JSON only, shaped as {\"lines\": [{\"speaker\": \"narrator\" | \"mara\", \"text\": string}]}. " +
"Each text is at most 25 words and has no markdown.",
},
{ role: "user", content: "A short exchange between the narrator and Mara at a locked door." },
],
});
const script = JSON.parse(res.choices[0].message.content);
for (const { speaker, text } of script.lines) {
await speakAs(speaker, text); // pick a voice per speaker in your own engine
}
Keep each line short in the prompt. Speech engines handle short units better, and a limit of about 25 words per line keeps scripts easy to cache. If a reply fails to parse, which can happen when output hits a token cap and gets cut off, retry once without a cap rather than trying to repair broken JSON. There is no required max_tokens on this API; a completion can use whatever remains of the 100,000-token window, so only set a cap when you want one.
Caching lines
Scripts that repeat, such as menu prompts, item descriptions or recurring greetings, should be generated once and stored with the audio. Hash the prompt plus the model ID plus the seed, and use the hash as the file name. Since seed is passed through, you can also regenerate a line on purpose and get the same wording while you tune the voice.
Step 4: tool calling for voice and pace
JSON mode returns data you then interpret. Tool calling lets the model act on a function you define, which suits a scene director that picks the voice and pace per line. Define a speak tool, let the model call it, run your engine, and send a role: "tool" message back so the conversation stays consistent.
// client created with baseURL "https://api.nsfwtts.cc/v1", as in step 1
const tools = [
{
type: "function",
function: {
name: "speak",
description: "Say one line aloud with the chosen voice and pace.",
parameters: {
type: "object",
properties: {
text: { type: "string" },
voice: { type: "string", enum: ["narrator", "mara"] },
pace: { type: "string", enum: ["slow", "normal", "fast"] },
},
required: ["text", "voice"],
},
},
},
];
const messages = [
{ role: "system", content: "You direct a voice scene. Use the speak tool for every line." },
{ role: "user", content: "Mara greets a guest, then the narrator closes the scene." },
];
const first = await client.chat.completions.create({
model: "uncensored",
messages,
tools,
tool_choice: "auto",
});
const reply = first.choices[0].message;
messages.push(reply);
for (const call of reply.tool_calls ?? []) {
const args = JSON.parse(call.function.arguments);
await speakAs(args.voice, args.text, args.pace);
messages.push({ role: "tool", tool_call_id: call.id, content: "played" });
}
Always parse function.arguments with a try/catch in production code. The arguments are a JSON string produced by a model, and an occasional malformed one is normal for any model. Validate the enum values too, and fall back to a default voice when the model invents one. Streamed responses deliver tool_calls in pieces, so if you combine streaming with tools, concatenate the argument fragments by index before parsing.
Limits, retries and cost
A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. A streamed request keeps its concurrency slot until the stream ends, so a slow speech step that reads from the stream lazily can hold a slot longer than you expect. If your speech engine is slow, read the whole stream into a queue first and let playback drain the queue.
When you exceed a limit the API returns HTTP 429 with the code rate_limited or concurrency. A temporary overload also gives 429 with Retry-After: 5. This wrapper honours the header:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.nsfwtts.cc/v1",
apiKey: process.env.NSFWTTS_KEY,
maxRetries: 0, // handle retries ourselves
});
export async function complete(messages, tries = 4) {
for (let i = 0; i < tries; i++) {
try {
return await client.chat.completions.create({ model: "uncensored", messages });
} catch (err) {
const retryable = err.status === 429 && i < tries - 1;
if (retryable === false) throw err;
const h = err.headers;
const ra = typeof h?.get === "function" ? h.get("retry-after") : h?.["retry-after"];
const wait = Number(ra ?? 5) * 1000;
console.warn("429", err.code, "waiting", wait, "ms");
await new Promise((r) => setTimeout(r, wait));
}
}
}
Cost is easy to estimate. Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. A clip with an 800-token prompt and a 400-token script costs 800 x $0.15 / 1,000,000 = $0.00012 for input plus 400 x $0.50 / 1,000,000 = $0.0002 for output, so $0.00032 in total. A thousand clips come to $0.32. The speech engine is billed separately, if it is hosted, so check their current pricing before you plan a budget.
Top-ups run from $20 to $500 in whole amounts, with a bonus of 5% from $50, 10% from $100 and 15% from $200. This site takes crypto only, USDT on TRC20 or USDC on Base. The pricing page has the details, and new accounts can claim $0.50 of trial credit in one click, valid for 7 days.
Where this fits and where it does not
This setup works well for narration, character dialogue, interactive fiction, accessibility read-outs and any workflow where the script changes often. It is the wrong tool if you need the model to produce audio, embeddings or images, because it only does text. It is also a poor choice if you need a specific vendor's model by name: the service runs one open-weight model from an independent provider and is not a router across vendors.
The model is tuned to answer without content refusals for lawful adult use, which matters for adult fiction and roleplay projects. Content involving minors is never allowed. For a longer look at how script generation and voice synthesis combine, see the article on a text LLM API in a TTS workflow. Prompts are not used for training.
More guides
Questions and answers
Does this API return audio for my Node.js app?
No. It returns text from the uncensored model. Pass that text to a speech engine you choose, local or hosted, to get audio.
Can I use the official openai npm package?
Yes. Set baseURL to https://api.nsfwtts.cc/v1, pass your key as apiKey, and use the model uncensored. Streaming, tools and JSON mode work through the same calls.
How do I avoid 429 errors in a batch job?
Cap in-flight calls at 6 or 7 on a full key, and respect the Retry-After header when it appears. The error code concurrency means too many at once, rate_limited means too many per minute.
How long can the script text be?
Prompt plus completion can use up to 100,000 tokens. For speech you will usually keep each unit to a sentence or two, far below that.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.