The short answer: three lines change
LangChain.js talks to any OpenAI-compatible server through the ChatOpenAI class. You keep the class, point it at a different base URL, and give it a different key and model name. Nothing else in your chains, prompts or output parsers needs to change.
The base URL is https://api.nsfwtts.com/v1, the model ID is uncensored, and the key goes in as a Bearer token, which the OpenAI client does for you. Here is the smallest program that works:
import { ChatOpenAI } from "@langchain/openai";
const model = new ChatOpenAI({
model: "uncensored",
apiKey: process.env.NSFWTTS_API_KEY,
configuration: { baseURL: "https://api.nsfwtts.com/v1" },
temperature: 0.8,
});
const reply = await model.invoke("Write a two-line villain monologue.");
console.log(reply.content);
Run it as an ES module (a .mjs file, or "type": "module" in package.json, or a TypeScript file run through your usual tool). If it prints text, the wiring is correct and the rest of this page is about the details that matter once you build something larger.
One thing to keep straight: the apiKey option here is the key from this site, not an OpenAI key, and the baseURL sits inside the configuration object, not at the top level of the constructor. Putting it at the top level is the most common reason requests silently go to the wrong host.
Install and project setup
You need three packages for the examples below: the OpenAI integration, the core package that holds the message and tool types, and zod for tool schemas.
npm install @langchain/openai @langchain/core zod
export NSFWTTS_API_KEY="paste-your-key-here"
Get the key from the API key page. New accounts can claim $0.50 of trial credit with one click on that page, valid for 7 days and without a card. The trial key is limited to 2 concurrent requests and 60 requests per minute, which is plenty for trying out chains but worth remembering if you run a batch.
If you write TypeScript, the types come with the packages, so there is nothing extra to install. A minimal tsconfig.json with "module": "NodeNext" and "moduleResolution": "NodeNext" avoids the usual import errors with these packages. Keep the key in an environment variable or a secrets manager, never in the source file you commit.
To check the key and the URL before involving LangChain at all, call the models endpoint directly:
curl https://api.nsfwtts.com/v1/models \
-H "Authorization: Bearer $NSFWTTS_API_KEY"
A JSON list that includes uncensored means the key is good and the base URL is right. When something fails later inside a chain, this call tells you quickly whether the problem is the connection or your chain code.
Prompts, chains and message history
A model object is a runnable, so it composes with prompt templates and output parsers the way any other LangChain.js chat model does. The model does not know or care that the server is not run by the original SDK vendor.
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
const model = new ChatOpenAI({
model: "uncensored",
apiKey: process.env.NSFWTTS_API_KEY,
configuration: { baseURL: "https://api.nsfwtts.com/v1" },
temperature: 0.9,
topP: 0.95,
});
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are the narrator of a dark fantasy story for adult readers. Stay in character."],
["human", "Continue the scene: {scene}"],
]);
const chain = prompt.pipe(model).pipe(new StringOutputParser());
const text = await chain.invoke({ scene: "The caravan reaches the burned bridge." });
console.log(text);
Sampling options such as temperature, topP, stop and the frequency and presence penalties are passed through to the model, so tuning them in the constructor has the effect you expect. If you pass a seed, you get repeatable runs for debugging, though identical output is never a hard promise from any sampled model.
Long conversations
The context window is 100,000 tokens, prompt plus completion. For a chat app that is a lot of room, but the bill and the latency both grow with the prompt, because every turn resends the history. A sensible pattern is to keep the system prompt and the last N turns, and summarize older turns into one short message once the history passes a size you pick. LangChain.js has memory helpers for this, and a plain array of messages you trim yourself works equally well.
Because max_tokens is optional, a model call with no limit can use the rest of the window. For chat, set maxTokens to a figure that fits your interface, since a runaway answer costs output tokens at $0.50 per 1M.
Streaming tokens to the user
Streaming uses server-sent events (stream: true on the wire). In LangChain.js you call .stream() and iterate the chunks:
const stream = await model.stream("Describe a storm over a harbor town in one paragraph.");
for await (const chunk of stream) {
process.stdout.write(chunk.content);
}
process.stdout.write("\n");
The same works for a whole chain: await chain.stream({ scene }) yields string pieces when the last step is a string parser. In a web app you forward these pieces to the browser with your framework's streaming response, or over a WebSocket.
Two practical points. First, usage figures arrive at the end of the stream, so if you track cost per user, read them from the final chunk metadata rather than estimating. Second, a streamed request holds its concurrency slot until the stream ends. A user who opens a response and walks away with the connection still open is occupying one of your 8 slots. Set a timeout or abort the request when the client disconnects. You can pass a signal option to .stream() for that:
const controller = new AbortController();
req.on("close", () => controller.abort());
const stream = await model.stream(messages, { signal: controller.signal });Tool calling with bindTools
The endpoint supports tools, tool_choice, streamed tool_calls and results sent back as role: "tool" messages. LangChain.js wraps all of that in bindTools.
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { HumanMessage, ToolMessage } from "@langchain/core/messages";
const rollDice = tool(
async ({ sides }) => String(1 + Math.floor(Math.random() * sides)),
{
name: "roll_dice",
description: "Roll one die with the given number of sides and return the result.",
schema: z.object({ sides: z.number().int().min(2).max(100) }),
}
);
const withTools = model.bindTools([rollDice]);
const messages = [new HumanMessage("Roll a twenty-sided die for the ambush check.")];
const ai = await withTools.invoke(messages);
messages.push(ai);
for (const call of ai.tool_calls ?? []) {
const result = await rollDice.invoke(call.args);
messages.push(new ToolMessage({ content: result, tool_call_id: call.id }));
}
const final = await withTools.invoke(messages);
console.log(final.content);
The flow is the standard one: the model answers with a tool call, you run the function, you append a tool message that carries the matching tool_call_id, and you call the model again. If you use LangGraph.js or an agent executor, it runs this loop for you.
The model behind this API is an open-weight model, so treat tool use the way you would with any such model. Write short, specific tool descriptions, keep schemas small, and validate the arguments in your function even when a Zod schema exists. If a tool must be used, pass tool_choice to force it instead of hoping the model decides to call it.
JSON mode and structured output
JSON mode is available through response_format: {"type":"json_object"}. In LangChain.js you can set it on the model, or ask for structured output with the JSON mode method:
import { z } from "zod";
const Character = z.object({
name: z.string(),
role: z.string(),
traits: z.array(z.string()),
});
const structured = model.withStructuredOutput(Character, { method: "jsonMode" });
const result = await structured.invoke(
"Return a JSON object for a ship's cook in a pirate story, with the keys name, role and traits."
);
console.log(result);
Notice that the prompt names the keys. JSON mode makes the output valid JSON, but it cannot guess which fields your Zod schema wants, so say them in the prompt. If the parse still fails now and then, catch the error and retry once with a lower temperature.
If you prefer to set the raw option yourself, new ChatOpenAI({ ..., modelKwargs: { response_format: { type: "json_object" } } }) sends it straight through.
Rate limits, retries and batches
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. When you go over, the API answers with HTTP 429 and an error code: rate_limited for too many requests per minute, concurrency for too many at once. On temporary overload it also returns 429, with a Retry-After: 5 header.
LangChain.js retries failed calls by default, and you control it with maxRetries. For batches, cap the parallelism at your limit instead of letting the retry logic absorb the errors:
const model = new ChatOpenAI({
model: "uncensored",
apiKey: process.env.NSFWTTS_API_KEY,
configuration: { baseURL: "https://api.nsfwtts.com/v1" },
maxRetries: 3,
});
const inputs = scenes.map((s) => `Write a one-sentence hook for: ${s}`);
const outputs = await model.batch(inputs, { maxConcurrency: 6 });
Choosing 6 on a full key leaves headroom for other traffic from the same key. On a trial key, use 2. Responses carry X-Request-Id, X-Balance-USD and the rate-limit headers, which is useful when you log calls or need to give support a request to look at. Failed or refused requests are not charged, so a 429 costs you nothing but time.
Request bodies can be up to 8 MB, which only matters if you paste very large documents into the prompt. The 100,000 token window will be the limit you hit first.
Common problems and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Request goes to the wrong host or fails to connect | baseURL placed at the top level of the constructor | Put it in configuration: { baseURL } |
| Authentication error | Key from another service, or a stray space or newline in the env var | Copy the key again from the key page and trim it |
| Error mentioning an unknown model | Model name left at a default | Set model: "uncensored" |
429 with concurrency | More than 8 requests in flight, or 2 on a trial key | Lower maxConcurrency, close abandoned streams |
429 with rate_limited | More than 300 requests per minute (60 on trial) | Space out calls and honor Retry-After |
| Tool call arguments are malformed | Schema too loose or description vague | Tighten the schema, validate in code, retry once |
Prices and top-up options are on the pricing page, and the full endpoint reference is in the API documentation. Credit is prepaid and does not expire, and top-ups are paid in crypto (USDT on TRC20 or USDC on Base).
The text model does not produce audio or images. If your LangChain.js project needs speech or pictures, keep a separate provider for those steps and use this endpoint for the text. For the speech side, the TTS integration guide on this site is a reasonable place to start. Prompts are not used for training, and the one hard content rule is that nothing sexual involving minors is allowed.
