EN ▾
Get API key

Uncensored LLM API in JavaScript: Fetch and SDK

Looking for an uncensored LLM API JavaScript example? Point the official openai package, or a plain fetch call, at a new base URL and send the model ID uncensored. Below is working Node code for chat, streaming, JSON mode and tool calling, plus the safe way to use it from a browser.

A browser and a Node server connected by glowing cables to a central key-holding server cube

Updated

Key points

  • Only two values change from stock OpenAI code: the base URL and the API key; the model is uncensored.
  • Plain fetch works in Node 18+ and in browsers; the openai package is shorter and handles streaming for you.
  • Never put the key in front-end code. Call the API from a server route and let the browser talk to that.
  • Handle HTTP 429 by reading the error code and the Retry-After header, then retry.

Project setup in two minutes

Before any of the code above runs, you need a small project. Check your Node version with node --version; 18 or newer has global fetch, and 20 or newer is the safer pick because older releases are out of maintenance. Then create the folder and install the one dependency you need:

mkdir llm-demo && cd llm-demo
npm init -y
npm pkg set type=module
npm install openai
export API_KEY="paste-your-key-here"
curl -s https://api.unfilteredimagegenerator.cc/v1/models -H "Authorization: Bearer $API_KEY"

The curl line at the end is a useful sanity check. It calls GET /v1/models and should list the model ID uncensored. If you get a 401, the key is wrong or has a stray space or newline; if the request hangs, check that the base URL ends in /v1 and that you did not add /chat/completions twice. The SDK appends /chat/completions itself, so its baseURL must stop at /v1, while a raw fetch call needs the full path.

Keep the key out of your repository. A .env file loaded with node --env-file=.env app.mjs (Node 20.6 and later) is enough for local work, with .env listed in .gitignore. In production, use your host's secret store. You can get a key and the one-click trial credit from the API key page.

Quick start with fetch

The shortest working call needs no package at all. Node 18 and later ship with fetch, and so does every current browser. You send a JSON body to /chat/completions under the base URL with a bearer token:

const BASE = "https://api.unfilteredimagegenerator.cc/v1";
const KEY = process.env.API_KEY;

const res = await fetch(`${BASE}/chat/completions`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${KEY}`,
  },
  body: JSON.stringify({
    model: "uncensored",
    messages: [
      { role: "system", content: "You are a blunt, concise assistant." },
      { role: "user", content: "Give me three plot twists for a heist story." },
    ],
    temperature: 0.8,
  }),
});

if (res.ok === false) {
  throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const data = await res.json();
console.log(data.choices[0].message.content);
console.log("balance:", res.headers.get("X-Balance-USD"));

Save it as an ES module (.mjs, or "type": "module" in package.json) so top-level await works. The response carries an X-Request-Id header you can log for support, and X-Balance-USD, which is handy for a low-balance warning. To get a key, use the API key page; new accounts can claim $0.50 of trial credit there.

Use the openai package

The official SDK works because the API speaks the same protocol. Install it with npm install openai and set baseURL:

import OpenAI from "openai";

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

const completion = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Write a villain monologue in 80 words." }],
  max_tokens: 200,
});

console.log(completion.choices[0].message.content);
console.log(completion.usage);

Everything else you know from the SDK carries over: temperature, top_p, stop, seed and the frequency and presence penalties are passed through. The SDK retries some failures by itself; if you prefer to control that, pass maxRetries: 0 to the constructor and handle 429 yourself as shown further down. If you need to confirm the model list, await client.models.list() calls GET /v1/models.

Frameworks that wrap the SDK usually expose the same two settings under names like "base URL" and "API key". The docs page has the complete list of supported fields.

Stream tokens as they arrive

Streaming uses server-sent events: set stream: true and read chunks. With the SDK it is an async iterator:

// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const stream = await client.chat.completions.create({
  model: "uncensored",
  stream: true,
  stream_options: { include_usage: true },
  messages: [{ role: "user", content: "Tell a short ghost story." }],
});

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) process.stdout.write(delta);
  if (chunk.usage) console.log("\nusage:", chunk.usage);
}

The stream ends with a usage block, so you can still count tokens. Without the SDK you parse the data: lines yourself:

// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const res = await fetch(`${BASE}/chat/completions`, {
  method: "POST",
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${KEY}` },
  body: JSON.stringify({
    model: "uncensored",
    stream: true,
    messages: [{ role: "user", content: "Count to five in words." }],
  }),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split("\n");
  buffer = lines.pop();
  for (const line of lines) {
    if (line.startsWith("data: ") === false) continue;
    const payload = line.slice(6).trim();
    if (payload === "[DONE]") continue;
    const delta = JSON.parse(payload).choices[0]?.delta?.content;
    if (delta) process.stdout.write(delta);
  }
}

Keep the partial last line in buffer; a chunk boundary can fall in the middle of a line. One more detail: a streamed request holds its concurrency slot until the stream ends, so close or abort streams you no longer need.

JSON mode and tool calling

For machine-readable output set response_format: { type: "json_object" } and describe the keys in your prompt:

// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const r = await client.chat.completions.create({
  model: "uncensored",
  response_format: { type: "json_object" },
  messages: [
    { role: "system", content: 'Reply as JSON: {"title": string, "tags": string[]}' },
    { role: "user", content: "A noir story set on a space station." },
  ],
});
const obj = JSON.parse(r.choices[0].message.content);

Tool calling follows the OpenAI shape: pass tools and optionally tool_choice, run the function the model asks for, and send the result back with role: "tool".

// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const tools = [{
  type: "function",
  function: {
    name: "roll_dice",
    description: "Roll an n-sided die",
    parameters: {
      type: "object",
      properties: { sides: { type: "integer" } },
      required: ["sides"],
    },
  },
}];

const messages = [{ role: "user", content: "Roll a d20 for my attack." }];
const first = await client.chat.completions.create({ model: "uncensored", messages, tools });
const call = first.choices[0].message.tool_calls?.[0];

if (call) {
  const sides = JSON.parse(call.function.arguments).sides;
  messages.push(first.choices[0].message);
  messages.push({
    role: "tool",
    tool_call_id: call.id,
    content: String(1 + Math.floor(Math.random() * sides)),
  });
  const final = await client.chat.completions.create({ model: "uncensored", messages, tools });
  console.log(final.choices[0].message.content);
}

Always parse arguments inside a try block. Open-weight models occasionally emit malformed arguments, and a single retry is cheaper than a crash.

Using it from a browser safely

Calling the API straight from page JavaScript works technically, but the key then sits in your bundle where anyone can copy it and spend your balance. The pattern that holds up is a thin server route that adds the key and forwards the request. Here is a minimal Express version that streams through:

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

const app = express();
app.use(express.json({ limit: "1mb" }));

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

app.post("/api/chat", async (req, res) => {
  const stream = await client.chat.completions.create({
    model: "uncensored",
    stream: true,
    messages: req.body.messages.slice(-20),
  });
  res.setHeader("Content-Type", "text/event-stream");
  for await (const chunk of stream) {
    res.write(`data: ${JSON.stringify(chunk)}\n\n`);
  }
  res.end();
});

app.listen(3000);

The route trims history to the last 20 messages, which keeps your bill predictable, and it is the place to add your own user login and per-user limits. The upstream body limit is 8 MB, so a 1 MB cap on your side is a sensible guard. The same shape works in Next.js route handlers, Cloudflare Workers or any serverless function; only the wrapper changes.

Keep conversation state and cancel requests

The API is stateless, so a chat is just an array you grow and resend. Keep it in memory per session and push both sides of each exchange:

// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const history = [
  { role: "system", content: "You are the narrator of a dark fantasy campaign." },
];

async function say(text) {
  history.push({ role: "user", content: text });
  const r = await client.chat.completions.create({ model: "uncensored", messages: history });
  const reply = r.choices[0].message;
  history.push({ role: "assistant", content: reply.content });
  return reply.content;
}

console.log(await say("I open the iron door."));
console.log(await say("I light the torch and step inside."));

Two refinements matter in real apps. First, trim. Keep the system message and the last N turns, or summarize older turns into one short message, because every old turn is billed as input again on each request. The 100,000-token window is large, but there is no reason to pay for 60,000 tokens of small talk. A rough rule of thumb is four characters per English token; for exact counts, read usage.prompt_tokens from the previous response.

Second, let users cancel. Pass an AbortController signal so a closed tab or a Stop button ends the stream and frees the concurrency slot:

// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 15000);

try {
  const stream = await client.chat.completions.create(
    { model: "uncensored", stream: true, messages: history },
    { signal: ctrl.signal },
  );
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
  }
} catch (err) {
  if (err.name === "AbortError") console.log("\ncancelled");
  else throw err;
}

With plain fetch the same idea is fetch(url, { signal: ctrl.signal }). Without it, an abandoned stream keeps running until it finishes, and on a key limited to 8 concurrent requests a few of those can block your real users.

Handle 429 and other errors

A full key allows 8 concurrent requests and 300 requests per minute. The trial key allows 2 and 60. When you go over, the API answers HTTP 429 with an error code: rate_limited for requests per minute, concurrency for too many at once. On short overload you also get 429 with Retry-After: 5. A small wrapper covers all three:

async function chat(body, tries = 4) {
  for (let i = 0; i < tries; i++) {
    const res = await fetch(`${BASE}/chat/completions`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "Authorization": `Bearer ${KEY}` },
      body: JSON.stringify(body),
    });
    if (res.status === 429) {
      const wait = Number(res.headers.get("Retry-After")) || 2 ** i;
      await new Promise((r) => setTimeout(r, wait * 1000));
      continue;
    }
    return res;
  }
  throw new Error("still rate limited");
}

For batch jobs, cap parallelism yourself instead of relying on retries: a simple queue with 6 workers stays below the concurrency limit of 8. Failed or refused requests are not charged, so retries cost nothing extra when the first attempt errors out. The X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency headers tell you which limits apply to your key. Check pricing before running a large loop: $0.15 per 1M input tokens and $0.50 per 1M output tokens is cheap, but a bug that resends a 90,000-token history in a loop is still a bill.

A reusable client module

Once the first call works, move the setup into one file so the rest of the app never sees the base URL or the key. Here is a small module with a typed helper, written in TypeScript but valid JavaScript if you strip the annotations:

// llm.ts
import OpenAI from "openai";

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

export async function ask(system, user, temperature = 0.7) {
  const r = await client.chat.completions.create({
    model: "uncensored",
    temperature,
    messages: [
      { role: "system", content: system },
      { role: "user", content: user },
    ],
  });
  return {
    text: r.choices[0].message.content ?? "",
    tokens: r.usage,
  };
}

Returning the usage object with every answer lets you add cost tracking in one place later: input tokens times 0.15 plus output tokens times 0.50, divided by one million, gives the dollar cost of that call. Because the module owns the model ID, a future change is a one-line edit rather than a search through the codebase.

Test the integration before you ship

Run three quick checks and you will catch nearly every setup mistake. First, a plain non-streaming call, as in the quick start. Second, a streaming call in a terminal, to confirm that text appears piece by piece and that the final usage block arrives. Third, a deliberate error: send a request with a wrong key and confirm that your code shows a readable message rather than an empty page. A 401 body is JSON, so print it.

For automated tests, do not call the live API in every run. Wrap ask in an interface and swap in a fake that returns a fixed string, then keep one small smoke test that hits the real endpoint with a one-line prompt and a low max_tokens. That smoke test costs a fraction of a cent. Use a separate key for CI so you can revoke it without touching production, and read the rate limit headers, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency, in the test log so you see which limits apply.

When something fails in a way you cannot explain, include the X-Request-Id value from the response headers when you contact the team through the support page. It lets them find that exact request.

Questions and answers

Do I need a special SDK?

No. The standard openai package for Node works when you set the base URL and key, and plain fetch works without any package.

Is it safe to call the API from client-side JavaScript?

Not with a real key, because anyone can read it from your page. Put a small server route in between and keep the key in an environment variable.

Which model ID do I send?

Send uncensored as the model value. You can confirm it by calling GET /v1/models.

Does it support function calling and JSON mode?

Yes to both. Tool calling uses the tools and tool_choice fields with role tool results, and JSON mode uses response_format with json_object.

What happens when I hit a rate limit?

You get HTTP 429 with the code rate_limited or concurrency, or a Retry-After header of 5 on temporary overload. Wait and retry.

Your key is one form away

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

Start with trial credit

Email and password, key on screen right away.