EN ▾
Uncensored Chatbot APIDirect API access to one uncensored LLMGet API key

Uncensored Chatbot APISafety

How to Implement a Chatbot in a Website, Step by Step

Learning how to implement chatbot in website projects comes down to three parts: a chat box in the browser, a small backend that holds your API key, and a call to an OpenAI-compatible endpoint. This guide builds each part with working code.

Updated

Browser chat bubble connected through a key-holding server to a cloud API, showing how to add a chatbot to a website

Key points

  • Never call the API from browser code. Keep the key on a server and expose your own /api/chat route.
  • The API is OpenAI-compatible, so the standard SDKs work after you set the base URL and use model uncensored.
  • Stream replies so the page feels fast, and cap history on the server.
  • Handle 429 responses and set a per-visitor limit, since a full key allows 8 concurrent requests.

The architecture in one picture

The usual way to implement chatbot in website projects is a three-step relay. The visitor types into a chat box. Your page sends the message to your own server. Your server calls the model API with your secret key and passes the answer back. The browser never sees the key.

This matters because anything in front-end JavaScript is public. If you put the key in a script tag, anyone who opens developer tools can copy it and spend your balance. A backend route also gives you one place to add rate limits, history trimming, logging and an age gate. For a longer walkthrough of a finished page, see the web chat tutorial.

Step 1: get a key and test the endpoint

Sign up with Google or with email and password, then claim the free trial on the API key page. The trial is $0.50 of credit, valid for 7 days, one per person, and needs no payment. Save the key as an environment variable, not in your code.

Check that it works with curl before writing any app code:

export API_KEY="YOUR_KEY"

curl https://api.uncensoredchatbotapi.com/v1/models -H "Authorization: Bearer $API_KEY"

curl https://api.uncensoredchatbotapi.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "uncensored", "messages": [{"role": "user", "content": "Say hello in five words."}]}'

The first call lists models and the second returns a chat completion. If both succeed, the key and base URL are right. A 401 means the key is wrong or missing the Bearer prefix.

Step 2: write the backend route

The example below uses Node 18 or newer, Express and the official openai package. Install them with npm install express openai and set "type": "module" in package.json.

import express from "express";
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.uncensoredchatbotapi.com/v1",
  apiKey: process.env.API_KEY,
});

const SYSTEM = "You are a helpful assistant for our website. Keep answers under 150 words.";

const app = express();
app.use(express.json({ limit: "100kb" }));
app.use(express.static("public"));

app.post("/api/chat", async (req, res) => {
  const incoming = Array.isArray(req.body.messages) ? req.body.messages : [];
  const history = incoming.slice(-10).map((m) => ({
    role: m.role === "assistant" ? "assistant" : "user",
    content: String(m.content).slice(0, 4000),
  }));

  try {
    const stream = await client.chat.completions.create({
      model: "uncensored",
      messages: [{ role: "system", content: SYSTEM }, ...history],
      stream: true,
    });
    res.setHeader("Content-Type", "text/plain; charset=utf-8");
    for await (const chunk of stream) {
      const text = chunk.choices[0]?.delta?.content;
      if (text) res.write(text);
    }
  } catch (err) {
    if (res.headersSent === false) res.status(err.status === 429 ? 429 : 502);
  }
  res.end();
});

app.listen(3000, () => console.log("Listening on http://localhost:3000"));

Three details do real work here. The server rebuilds the message list itself, so a visitor cannot inject a fake system message. It keeps only the last 10 messages and cuts each to 4,000 characters, which controls cost. And it always sets the roles explicitly, mapping anything unknown to user.

Step 3: build the chat box

Put this in public/index.html. It uses plain JavaScript with no framework, so you can paste it into an existing template.

<div id="log"></div>
<form id="form">
  <input id="input" autocomplete="off" required />
  <button>Send</button>
</form>
<script>
const messages = [];
const log = document.getElementById("log");

document.getElementById("form").addEventListener("submit", async (e) => {
  e.preventDefault();
  const input = document.getElementById("input");
  messages.push({ role: "user", content: input.value });
  log.insertAdjacentHTML("beforeend", "<p></p>");
  log.lastElementChild.textContent = "You: " + input.value;
  input.value = "";

  const reply = document.createElement("p");
  log.appendChild(reply);
  const res = await fetch("/api/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ messages }),
  });
  if (res.ok === false) { reply.textContent = "Busy, please try again in a moment."; return; }

  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  let full = "";
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    full += decoder.decode(value, { stream: true });
    reply.textContent = full;
  }
  messages.push({ role: "assistant", content: full });
});
</script>

Using textContent instead of innerHTML for model output prevents the reply from injecting markup into your page. Keep that habit even when the model is well behaved.

Step 4: handle limits and errors

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. When you go over, the API returns HTTP 429 with an error code: rate_limited for requests per minute or concurrency for too many at once. On temporary overload it also returns 429 with a Retry-After: 5 header.

Two practical rules follow. First, retry 429 after the delay with a short backoff, and show the visitor a friendly message if it keeps failing. Second, remember that a streamed request holds its concurrency slot until the stream ends. If ten visitors stream at once on a full key, two of them will be turned away, so add a small queue or a per-visitor limit on your server. A simple in-memory counter keyed by IP is enough for a small site.

The response headers help you debug: X-Request-Id identifies a call if you contact support, and X-Balance-USD shows your remaining credit. The request body limit is 8 MB, far above what a chat needs, and the context window is 100,000 tokens.

Pitfalls when you deploy

The code above works on localhost. These are the problems that show up once it is on a real server.

  • Buffering proxies. Some reverse proxies hold back streamed responses until they finish, so the reply appears all at once. If you use nginx, turn off response buffering for the chat route. Test streaming through the same proxy chain you use in production, not only on your laptop.
  • Keys in the repository. Keep the key in an environment variable or a secrets store and add any local env file to your ignore list. If a key ever lands in a public repo, create a new one and stop using the old one.
  • Trusting the client. The browser sends the chat history, so a visitor can edit it. That is why the server in step 2 sets roles itself and cuts message length. Never accept a system message from the client.
  • Cross-origin calls. If your page and your backend live on different domains, the browser will block the request until your server sends the right CORS headers. Serving both from one origin avoids the issue.
  • Runaway cost. One scripted visitor can send hundreds of messages. Count requests per IP or session on the server and refuse when the count is too high. Also cap message length, as the example does.
  • Markdown and links. Models often reply with lists and code fences. Decide whether you render that or show plain text, and never insert reply text as raw HTML.

A last check is the mobile layout. Most chat traffic on public sites comes from phones, so test with a narrow screen, a software keyboard open, and a flaky connection. If the stream breaks halfway, the visitor should be able to resend without losing the thread.

Extending the bot later

Once the basic relay works, the same route can do more, because the API supports the standard OpenAI features. You can ask for structured output with JSON mode by setting response_format to {"type": "json_object"} and saying in the prompt that the reply must be JSON. That suits a lead form that turns a free-text message into fields like name, topic and urgency.

Tool calling lets the model ask your server to run a function, such as looking up an order or checking opening hours. You pass a tools list, read the tool_calls in the response, run the function yourself, and send the result back as a message with role: "tool". The model then writes the final answer from your data. This is how a website bot gets real information instead of guessing.

Sampling settings are also open to you. A lower temperature suits factual help desks and a higher one suits storytelling. Add one change at a time and compare the results on the same five test questions.

Step 5: shape the bot and go live

The system prompt defines your bot. Tell it who it is, what it covers and how long answers should be. If the character has a personality, the notes on persona design go deeper. Because the model is tuned to answer without content refusals for lawful adult use, the guardrails for your audience are yours to write: an age confirmation, a report link and a clear list of what the bot will not discuss. Sexual content involving minors is never allowed. See the page on responsible usage and safeguards before launch.

On cost, you pay $0.15 per 1M input tokens and $0.50 per 1M output tokens. A reply with 1,200 input tokens and 300 output tokens costs $0.00018 plus $0.00015, which is $0.00033. A $20 top-up covers over 60,000 such replies. Top-ups run from $20 to $500, with +5% from $50, +10% from $100 and +15% from $200, paid in USDT on TRC20 or USDC on Base. Credit never expires. The pricing page has the details, and the docs list every supported parameter, including tool calling and JSON mode.

Before you launch, test with a few long conversations, watch the logs for 429s, and confirm that your server trims history. Prompts are not used for training, but you should still tell your visitors what you store.

Questions and answers

Can I call the API directly from browser JavaScript?

You can, but you should not. The key would be visible to every visitor. Route requests through your own server and keep the key in an environment variable.

Which languages and SDKs work?

Any OpenAI SDK or HTTP client. Set the base URL to https://api.uncensoredchatbotapi.com/v1, use your key as a bearer token and set the model to uncensored. Python, Node and curl all work.

Does streaming work in a browser?

Yes. The API streams over SSE with stream set to true. The example relays the text through your server with fetch and a stream reader.

What happens when I hit the rate limit?

You get HTTP 429 with the code rate_limited or concurrency. Wait and retry. For temporary overload the Retry-After header is 5 seconds.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API keyRead the docs