EN ▾

unfilteredaiapi.comhttps://api.unfilteredaiapi.com/v1

Unfiltered AI

Raw, uncensored LLM API for developers.

Unfiltered AIGet API key

An unfiltered chatbot backend with FastAPI and server-sent events

This guide relays streamed model output through a small FastAPI backend. Keep the key on the server, isolate conversation history by session and handle interrupted streams before displaying a reply as complete.

An unfiltered chatbot backend with FastAPI and server-sent events

Key points

  • Dedicated inference providers like Unfiltered AI offer consistent uncensored behavior on a single model, avoiding the randomness of aggregator routing.
  • Aggregators like OpenRouter provide access to multiple models but may vary in how strictly they apply content filters depending on the specific model version.
  • Unfiltered AI uses an open-weight model on dedicated hardware with a 100k context window, priced at $0.15/$0.50 per million tokens.
  • For strict NSFW or roleplay consistency, a dedicated uncensored LLM API eliminates the need for complex prompt engineering to bypass generic filters.

The system as a picture in words

Picture three boxes in a row and two arrows between them. On the left, the browser. In the middle, your FastAPI process. On the right, the model endpoint at https://api.unfilteredaiapi.com/v1. The left arrow carries one user message and returns a stream of small text frames. The right arrow carries the full conversation and returns server-sent events. The middle box does three jobs and no more: it holds the API key, it owns the conversation state, and it converts one stream format into another.

Keeping the key in the middle box is the reason this layer exists. A key shipped to a browser is a key published to everyone who opens developer tools. The second reason is state: the browser sends only the new text and a session id, while the server decides how much history to replay. That decision becomes important once conversations grow, which the memory article treats in depth.

Everything here uses the standard chat-completions format with stream: true, so install fastapi, uvicorn and httpx and nothing else.

What arrives on the right-hand arrow

With streaming on, the response is a sequence of lines. Each useful line begins with data: followed by a JSON chunk whose choices[0].delta.content holds a few characters. The last real line is data: [DONE]. Just before that, a usage chunk is added automatically; it carries token counts and has no choices entries, so the relay must test for that before indexing.

Treat the stream as three phases: a quiet start while the model reads your prompt, a steady flow of fragments, and a short epilogue with usage and the sentinel. The relay below mirrors those phases. It forwards fragments as they arrive, accumulates them into one string, and writes that string to the session only when the flow ends.

The relay endpoint

The core is an async generator called stream_reply. FastAPI's StreamingResponse consumes it and flushes each yielded string to the client. Two routes wrap the same generator: a POST for fetch and a GET for EventSource.

# app.py
import json
import os
import uuid

import httpx
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

API_URL = "https://api.unfilteredaiapi.com/v1/chat/completions"
SYSTEM = {"role": "system", "content": "You are Corvin, a patient narrator of dark, adult-oriented fiction."}

app = FastAPI()
sessions: dict[str, list[dict]] = {}      # session id -> message list


class Turn(BaseModel):
    session_id: str
    text: str


def sse(data, event=None):
    head = f"event: {event}\n" if event else ""
    return f"{head}data: {json.dumps(data)}\n\n"


async def stream_reply(session_id: str, text: str):
    history = sessions.setdefault(session_id, [])
    history.append({"role": "user", "content": text})
    payload = {
        "model": "uncensored",
        "messages": [SYSTEM] + history,
        "stream": True,
        "max_tokens": 700,
    }
    headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
    parts: list[str] = []

    async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, read=120.0)) as client:
        async with client.stream("POST", API_URL, headers=headers, json=payload) as r:
            if r.status_code != 200:
                body = (await r.aread()).decode()
                history.pop()                       # do not keep a turn that got no answer
                yield sse({"status": r.status_code, "body": body}, event="error")
                return
            async for line in r.aiter_lines():
                if not line.startswith("data: "):
                    continue
                raw = line[6:]
                if raw == "[DONE]":
                    break
                chunk = json.loads(raw)
                if not chunk.get("choices"):         # the final usage chunk
                    continue
                piece = chunk["choices"][0]["delta"].get("content")
                if piece:
                    parts.append(piece)
                    yield sse(piece)

    history.append({"role": "assistant", "content": "".join(parts)})
    yield sse({}, event="done")


@app.post("/session")
def new_session():
    return {"session_id": uuid.uuid4().hex}


@app.post("/chat")
async def chat(turn: Turn):
    return StreamingResponse(
        stream_reply(turn.session_id, turn.text),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )


@app.get("/chat/stream")                              # for EventSource, which only does GET
async def chat_get(session_id: str, text: str):
    return StreamingResponse(
        stream_reply(session_id, text),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )

Read the generator top to bottom. It appends the user message first, so the model sees it. If the upstream status is not 200, it removes that message again and emits an error event, which keeps the history free of unanswered turns. On success it emits each fragment as a JSON string, which is how newlines and quotes survive the framing. When the loop ends, it stores the assistant text and sends a done event.

The two headers matter. Cache-Control: no-cache prevents intermediaries from holding the stream, and X-Accel-Buffering: no tells an nginx-style proxy to pass bytes through immediately.

Choosing a session store

The dictionary in the example is the simplest possible store: one list of messages per session id. It has three honest limitations. It vanishes on restart, it is not shared between worker processes, and it grows without bound. Pick the next step according to which limitation hurts first.

  1. Single process, short sessions: keep the dictionary, add a time-to-live sweep that deletes sessions idle for an hour.
  2. Several workers: move the message list to a shared key-value store, with the session id as the key and a JSON array as the value. Serialise access per session so two simultaneous requests cannot interleave.
  3. Durable history: write each turn to a database row keyed by session and sequence number, and load the tail on demand.

Whatever you choose, hide it behind two functions, load(session_id) and append(session_id, message), so stream_reply never learns where the data lives. Also generate session ids on the server, as the /session route does, and treat them as unguessable secrets.

The browser end with fetch

On the left-hand arrow the browser must read a streaming POST body. fetch exposes it as a readable stream, and TextDecoderStream turns bytes into text. Frames are separated by a blank line, so the client buffers incoming text and slices off complete frames.

<!doctype html>
<meta charset="utf-8">
<title>Chat</title>
<div id="log"></div>
<form id="f"><input id="t" autocomplete="off" size="50"><button>Send</button></form>
<script>
const sid = localStorage.getItem("sid") ?? (() => {
  const id = crypto.randomUUID().replaceAll("-", "");
  localStorage.setItem("sid", id);
  return id;
})();
const log = document.getElementById("log");

function line(text) {
  const p = document.createElement("p");
  p.textContent = text;
  log.append(p);
  return p;
}

document.getElementById("f").addEventListener("submit", async (e) => {
  e.preventDefault();
  const box = document.getElementById("t");
  const text = box.value.trim();
  if (!text) return;
  box.value = "";
  line("You: " + text);
  const out = line("");

  const res = await fetch("/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ session_id: sid, text }),
  });
  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
  let buf = "";
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buf += value;
    let cut;
    while ((cut = buf.indexOf("\n\n")) >= 0) {
      const frame = buf.slice(0, cut);
      buf = buf.slice(cut + 2);
      if (frame.startsWith("event: done")) continue;
      if (frame.startsWith("event: error")) { out.textContent += " [request failed]"; continue; }
      if (frame.startsWith("data: ")) out.textContent += JSON.parse(frame.slice(6));
    }
  }
});
</script>

The page writes with textContent, never innerHTML, so model output cannot inject markup into your page. That is a small habit with a large payoff when the model is producing arbitrary fiction.

Trying the relay before writing any front end

Test the middle box in isolation first. A terminal client removes the browser from the equation, so any problem you see belongs to the relay. The -N flag turns off curl's output buffering; without it you would see the whole reply arrive at once and wrongly conclude streaming is broken.

uvicorn app:app --port 8000 &
SID=$(curl -s -X POST localhost:8000/session | python3 -c "import sys,json; print(json.load(sys.stdin)['session_id'])")
curl -N -X POST localhost:8000/chat -H "Content-Type: application/json" \
  -d "{\"session_id\": \"$SID\", \"text\": \"Open with a storm.\"}"

You should see lines beginning with data: , each carrying a quoted fragment, then a final event: done frame. Send a second message with the same session id and ask the narrator to continue; if it picks up where it stopped, the store works. If the lines all arrive in one burst, something between you and the process is buffering, and the usual suspect is a reverse proxy with response buffering left on.

Once this passes, the browser page is only a matter of reading the same frames. The site home and the docs list the request fields if you want to pass more sampling options through the relay.

The EventSource variant, and its trade-off

The browser's EventSource API handles parsing and reconnection for you, but it can only issue GET requests. That is why the backend has a second route. The cost is that the user's text travels in the URL, and URLs tend to end up in access logs on machines you run. For private conversations prefer the POST and fetch approach.

const q = new URLSearchParams({ session_id: sid, text: "Describe the harbour at dusk." });
const src = new EventSource("/chat/stream?" + q);
const out = document.getElementById("log").appendChild(document.createElement("p"));

src.onmessage = (ev) => { out.textContent += JSON.parse(ev.data); };
src.addEventListener("done", () => src.close());   // without this, EventSource reconnects
src.addEventListener("error", () => src.close());

Pay attention to the done listener. When a server closes an event stream, EventSource assumes a network fault and reconnects, which would send the same message again. Closing the source yourself on done and on error breaks that loop.

Failure modes and limits to design around

Walk the arrows once more and ask what can break on each. On the right: a 401 means a bad key, a 402 means the balance is used up, a 403 means the request was blocked, a 429 means you passed 300 requests a minute on this key, and a 503 with upstream_busy deserves a retry after a few seconds. The relay surfaces all of them as one error event with the status attached, so the browser can choose a message.

A client that disconnects mid-stream cancels the generator, and the partial assistant text is never saved. That is usually the right behaviour; if you prefer to keep partial replies, store them in a finally block.

For cost planning, assume a turn that sends 3,000 input tokens and returns 600. At $0.15 and $0.50 per million, that is $0.00075 plus $0.0006, about $0.00135 per turn, so a thousand turns cost near $1.35. These figures are assumptions; check the usage chunk for your real numbers. For rates see pricing, and for an overview of choices read the chatbot API comparison.

Questions and answers

Why not call the model directly from the browser?

The API key would be visible to every visitor. A small relay keeps the key private and lets you control history and rate limits.

Does the stream include token usage?

Yes. A final usage chunk is appended automatically, and it has no choices entries, so skip chunks without them when extracting text.

When should I use EventSource instead of fetch?

Use EventSource when GET is acceptable and you want built-in reconnection. Use fetch for POST bodies, which keeps private text out of URLs.

How many users can one key support?

The limit is 300 requests per minute per key, shared across all your users, so add a per-user cooldown in the relay.

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