Add an AI Bot to Your Website With a Text LLM API
Adding an AI bot on website pages takes three parts: a small server endpoint that holds your API key, a chat widget that streams the reply, and a few limits so strangers cannot run up your bill. This guide builds all three.

Summary
- Never call the API from the browser; a server endpoint keeps the key secret and lets you enforce limits.
- Stream the reply with stream: true and read it in the widget with fetch, so text appears as it is written.
- Cap message length, history size, max_tokens and requests per visitor before launch.
- A bot handling 18,000 messages a month at 1,200 input and 200 output tokens each costs about $5.
The architecture in one picture
If you want an AI bot on website visitors can talk to, the browser must never hold the API key. Anything in a page's JavaScript can be read by anyone, and a leaked key means someone else spends your credit. Instead the widget talks to your own endpoint, and your endpoint talks to the API.
- The visitor types a message in the widget.
- The widget sends the recent conversation to
POST /api/chaton your server. - Your server checks limits, adds the system prompt and calls
https://api.uncensoredaibot.com/v1/chat/completionswith modeluncensored. - Your server streams the text back, and the widget prints it as it arrives.
The API is OpenAI-compatible, so the official openai package for Node works once you set the base URL. Get a key on the API key page; new accounts can claim $0.50 of trial credit, enough to build and test this whole project.
Step 1: the server endpoint
This example uses Node 18 or newer with Express. Install the packages, and set "type": "module" in your package.json so the import syntax works.
npm install express express-rate-limit openai
export API_KEY="paste-your-key-here"
node server.js
import express from "express";
import rateLimit from "express-rate-limit";
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.API_KEY,
baseURL: "https://api.uncensoredaibot.com/v1",
});
const SYSTEM =
"You are the help assistant for Example Shop. Answer questions about orders, " +
"shipping and products in two or three short paragraphs. If you do not know, say so.";
const app = express();
app.use(express.json({ limit: "20kb" }));
app.use("/api/chat", rateLimit({ windowMs: 60000, limit: 10 }));
let active = 0;
const MAX_ACTIVE = 6;
app.post("/api/chat", async function (req, res) {
const incoming = Array.isArray(req.body.messages) ? req.body.messages : [];
const history = [];
for (const m of incoming.slice(-10)) {
const okRole = m.role === "user" || m.role === "assistant";
const okText = typeof m.content === "string";
if (okRole === false || okText === false) continue;
history.push({ role: m.role, content: m.content.slice(0, 1000) });
}
if (history.length === 0) {
return res.status(400).json({ error: "No message" });
}
if (active >= MAX_ACTIVE) {
return res.status(503).json({ error: "Busy" });
}
active += 1;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Cache-Control", "no-store");
try {
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "system", content: SYSTEM }, ...history],
stream: true,
max_tokens: 400,
temperature: 0.6,
});
res.on("close", function () {
stream.controller.abort();
});
for await (const chunk of stream) {
const piece = chunk.choices[0]?.delta?.content;
if (piece) res.write(piece);
}
res.end();
} catch (err) {
if (res.headersSent) {
res.end();
} else {
res.status(err.status === 429 ? 503 : 500).json({ error: "Try again shortly" });
}
} finally {
active -= 1;
}
});
app.listen(3000);
The endpoint trusts nothing from the browser. It keeps only the last 10 messages, accepts only the user and assistant roles, trims each message to 1,000 characters, and adds the system prompt itself so visitors cannot replace it.
Step 2: the chat widget
The page needs three elements: a div with the id log for messages, a form with the id form, and a text input with the id input and a maxlength of 500. Then add this script. It uses textContent, never innerHTML, so model output cannot inject markup into your page.
const messages = [];
const log = document.getElementById("log");
const form = document.getElementById("form");
const input = document.getElementById("input");
function addLine(role, text) {
const p = document.createElement("p");
p.className = role;
p.textContent = text;
log.appendChild(p);
return p;
}
form.addEventListener("submit", async function (event) {
event.preventDefault();
const text = input.value.trim();
if (text === "") return;
input.value = "";
addLine("user", text);
messages.push({ role: "user", content: text });
const bubble = addLine("bot", "");
const resp = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: messages }),
});
if (resp.ok === false) {
bubble.textContent = "The assistant is busy. Please try again in a moment.";
messages.pop();
return;
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let answer = "";
while (true) {
const part = await reader.read();
if (part.done) break;
answer += decoder.decode(part.value, { stream: true });
bubble.textContent = answer;
}
messages.push({ role: "assistant", content: answer });
});
Streaming matters for perceived speed. Instead of waiting for the full reply, the visitor sees words appear within moments, and the server can stop paying for tokens if they close the tab, because the close handler aborts the upstream request.
Step 3: abuse limits before you go live
A public chat box is an open invitation for scripts. Set limits on four layers.
Per visitor
The example allows 10 requests per minute per IP address. Tighten it if your bot is used lightly. For stronger control, require a logged-in user or a signed session cookie and rate-limit by that instead of by IP, since many people share one address behind a network.
Per request
Limit message length (500 characters in the form, 1,000 on the server), history (10 messages), and max_tokens (400 here). These caps put a ceiling on the cost of any single call.
Across the whole bot
Your API key has its own ceiling: 8 concurrent requests and 300 requests per minute on a full key, and a streamed request holds its slot until the stream ends. The MAX_ACTIVE counter of 6 leaves headroom and turns overload into a clean "busy" message instead of a wave of 429 errors. If you do get a 429, the body carries the code rate_limited or concurrency, and a temporary overload sends Retry-After: 5.
Spend
Every response carries an X-Balance-USD header. Log it, and send yourself an alert when credit drops below a level you choose. Also check the Origin header on your endpoint so other websites cannot use your bot from their pages. The API documentation lists headers and error codes.
Test it before visitors do
Run the bot on a staging page first and try to break it. A short checklist catches most problems before launch.
- Send an empty and an oversized message. The server should answer with a clean error, not a stack trace.
- Close the tab mid-answer. The close handler should abort the upstream request, so you stop paying for tokens nobody reads.
- Fire a burst of requests. Open five tabs and send at once. The rate limiter and the busy counter should turn the surplus into a polite message.
- Try to override the prompt. Type "ignore your instructions" and see whether the bot stays on its job. If it drifts, tighten the system prompt and keep any hard rule in server code.
- Check streaming behind your proxy. If the reply arrives in one lump instead of word by word, a reverse proxy is buffering it. With nginx, switching
proxy_bufferingoff for the chat route usually fixes it; check your server's current documentation.
What an abusive visitor can cost
Estimate the worst case from your own caps. With 10 history messages of up to 1,000 characters each (about 2,500 tokens, at roughly four characters per token) plus the system prompt, a request carries about 2,600 input tokens and at most 400 output tokens. That is 2,600 x 0.15 / 1,000,000 = $0.00039 plus 400 x 0.50 / 1,000,000 = $0.0002, or about $0.00059 per request. At the limit of 10 requests a minute, one address can spend 600 requests x $0.00059, about $0.35, in an hour. That is small, but it adds up across many addresses, which is why the balance alert and the global busy counter matter.
Small touches that help visitors
Show a typing indicator until the first characters arrive, keep a visible "AI assistant" label on the widget, and offer a link to a human contact for anything the bot cannot answer. Save the conversation in the page only as long as the visitor needs it, and mention in your own privacy notice that messages are processed by an external API.
What it costs to run
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, paid from prepaid credit. Suppose 3,000 conversations a month, six messages each, so 18,000 messages. With a short system prompt and trimmed history, assume 1,200 input and 200 output tokens per message.
input: 1,200 x 0.15 / 1,000,000 = $0.00018
output: 200 x 0.50 / 1,000,000 = $0.00010
per message = $0.00028
18,000 messages x $0.00028 = $5.04 a month
Top-ups start at $20, credit never expires, and failed or refused requests are not charged. Details are on the pricing page.
Set expectations with your visitors
Tell people they are talking to an AI, and keep the system prompt specific about the bot's job. The model is tuned to answer without content refusals for lawful adult use, which means your own prompt is what keeps a shop assistant on topic. If your site is for adults only, add an age gate of your own. The one fixed limit is that sexual content involving minors is never allowed.
The service is text only, so the bot cannot send images or voice. For more on what an OpenAI-compatible, no-refusal text API offers, read the uncensored AI API guide.
More guides
Support & FAQ
Can I call the API straight from my website's JavaScript?
You can technically, but you should not. The key would be visible to every visitor. Route requests through your own server endpoint.
How do I stream the reply to the chat widget?
Set stream: true on the server request, write each delta to the response, and read the response body with fetch and a reader in the browser.
How do I stop abuse of a public chat bot?
Limit requests per visitor, message length, history size and max_tokens, cap concurrent calls, and watch the X-Balance-USD header so you notice unusual spending.
Does this work with frameworks other than Express?
Yes. Any backend that can make an HTTPS request and stream a response will do. The API follows the OpenAI format, so SDKs for Python, Node and other languages work with a changed base URL.
Generate your API token
Register, retrieve your key, and point to the endpoint. That’s the entire configuration.