The architecture in one paragraph
A live chat has three parts. The browser sends the message history to your server. Your server calls the model API with stream: true and your secret key. As pieces come back, the server writes them to the browser, which appends them to the page. The key never leaves the server, and you get one place to add logging, limits and message trimming.
This split also gives you a natural place to enforce your own limits. A full key allows 8 requests at once, so a public chat with many visitors needs a counter on the server that refuses or queues new streams past that number. Without it, the ninth visitor gets an error even though nothing is wrong with the key.
The API is OpenAI-compatible, so the server uses the standard openai package with a different base URL. The model ID is uncensored. If you have not used the API yet, this walkthrough on using AI models covers keys and a first request, and the docs list the parameters.
The server: a streaming proxy
This Express server accepts a list of messages and relays the model's tokens as server-sent events. Install with npm install express openai.
import express from "express";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredaimodel.com/v1",
apiKey: process.env.API_KEY,
});
const app = express();
app.use(express.json());
app.use(express.static("public"));
app.post("/api/chat", async (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("X-Accel-Buffering", "no");
const ctrl = new AbortController();
res.on("close", () => ctrl.abort());
try {
const stream = await client.chat.completions.create(
{ model: "uncensored", messages: req.body.messages, stream: true },
{ signal: ctrl.signal }
);
for await (const chunk of stream) {
const piece = chunk.choices?.[0]?.delta?.content;
if (piece) res.write("data: " + JSON.stringify({ t: piece }) + "\n\n");
if (chunk.usage) res.write("data: " + JSON.stringify({ usage: chunk.usage }) + "\n\n");
}
res.write("data: [DONE]\n\n");
} catch (err) {
if (ctrl.signal.aborted === false) {
res.write("data: " + JSON.stringify({ error: err.message }) + "\n\n");
}
}
res.end();
});
app.listen(3000);
Two details matter. The res.on("close") handler aborts the upstream request as soon as the browser disconnects or the user presses Stop. A streamed request holds one concurrency slot until it ends, so leaving it running wastes capacity and can push your next request into a 429. The X-Accel-Buffering: no header tells Nginx not to hold your events back.
The browser: read the stream and print it
Browsers have EventSource for SSE, but it only supports GET requests, and a chat needs to POST its history. The fix is to read the response body directly.
let controller = null;
const out = document.getElementById("out");
async function send(messages) {
controller = new AbortController();
out.textContent = "";
try {
const res = await window.fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages }),
signal: controller.signal,
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const events = buf.split("\n\n");
buf = events.pop();
for (const ev of events) {
const data = ev.startsWith("data: ") ? ev.slice(6) : "";
if (data === "") continue;
if (data === "[DONE]") return;
const msg = JSON.parse(data);
if (msg.t) out.textContent += msg.t;
if (msg.usage) showUsage(msg.usage);
if (msg.error) out.textContent += "\n[error] " + msg.error;
}
}
} catch (e) {
if (e.name === "AbortError") return;
out.textContent += "\n[connection lost]";
}
}
document.getElementById("stop").onclick = () => controller && controller.abort();
The line buf = events.pop() is the part people skip. Network chunks do not line up with event boundaries, so the last piece may be half an event. Keeping it in the buffer until the next read prevents JSON parse errors in the middle of a reply.
Use textContent, not innerHTML, when printing model output. The text is untrusted, and inserting it as HTML opens your page to script injection.
Cancellation and dropped connections
A Stop button is just controller.abort(). The browser closes the connection, the server's close handler fires, and the upstream request is cancelled. Keep the text printed so far as the user's reply, and add it to the history if they continue the conversation.
A dropped connection looks the same as a cancel to the server, but not to the user. In the client, the catch block separates the two: an AbortError means the user pressed Stop, anything else means the network failed. In that case, show a Retry button and keep the partial text visible. Resending the same history is the simplest recovery. Failed requests are not charged, and a retried request gets billed on its own usage.
One more case: a user who closes the laptop lid mid-reply. The server sees a closed connection and stops, so you pay only for tokens generated up to that point. When they come back, load the saved history, show the partial answer, and offer to regenerate. Do not silently resume, because the new text will not continue the old one word for word.
If you see a hard limit being hit, check the status. Limits on a full key are 8 concurrent requests and 300 per minute; a trial key gets 2 and 60. Over a limit the API returns HTTP 429 with the code rate_limited or concurrency. In this proxy, the 429 surfaces as an exception before any tokens flow, and the catch block sends it to the browser as an error event.
Show usage and cost after the reply
The last events of a stream carry token usage. In the example above the server forwards them, and showUsage can compute the price from the rates of $0.15 per 1M input tokens and $0.50 per 1M output tokens:
function showUsage(u) {
const cost = (u.prompt_tokens * 0.15 + u.completion_tokens * 0.5) / 1e6;
document.getElementById("cost").textContent =
u.prompt_tokens + " in / " + u.completion_tokens + " out, $" + cost.toFixed(6);
}
For a turn with 900 input tokens and 350 output tokens the result is (900 x 0.15 + 350 x 0.5) / 1,000,000 = (135 + 175) / 1,000,000 = $0.00031. Showing this next to each message makes it easy to see how history growth raises the input side. The pricing page has the full rate table.
Polish that users notice
- Auto-scroll with an escape hatch. Scroll to the bottom as text arrives, but stop if the user scrolls up to read.
- Disable the send button while a stream is open. This keeps one conversation from taking two slots.
- Render markdown after the stream ends. Rendering on every token flickers and costs CPU. Print plain text while streaming, then format once.
- Trim the history on the server. The window is 100,000 tokens for prompt and completion together, and every resent token costs input price.
- Test on a slow network. Use the throttling option in browser developer tools to check that the Stop button and the retry path still work when events arrive slowly.
- Handle the Retry-After header. On temporary overload the API returns 429 with
Retry-After: 5. Wait that long before retrying.
For a quick test without any front end, a terminal request with stream: true prints the same events. When the chat works, get an API key to run it against real traffic. New accounts can claim $0.50 of trial credit with one click, with no card needed, valid for 7 days. Top-ups from $20 accept crypto.

