EN ▾
Get API key

Build an OpenAINSFW Chat Bot with Streaming and History

This tutorial builds a working command-line chat bot with memory and live streaming on an OpenAI-compatible endpoint, then shows how to move the same core into a Telegram, Discord or web bot.

Updated

Glowing chat bubbles flowing into a geometric robot, illustrating a streaming chat bot

What the bot needs

An openainsfw chat bot is a small program with three jobs: take a message from a person, send it to the model together with the earlier conversation, and show the answer as it arrives. The API is stateless, so the second job is yours. Nothing on the server remembers what was said ten seconds ago unless you send it again.

That makes the data model simple. Keep a Python list of messages, each with a role of system, user or assistant. Append the user message, call the API, append the reply. The endpoint is OpenAI-compatible, so the official SDK works unchanged with base URL https://api.openainsfw.com/v1 and model uncensored. Get a key from the API key page; new accounts can claim $0.50 of trial credit with one click, valid for 7 days.

The model is a single open-weight model run by an independent provider, tuned to answer without content refusals for lawful adult use. It is text only. Use cases that fit well are fiction, roleplay and companion-style apps for adults. One rule is fixed: nothing sexual involving minors, ever, so build your own checks into any public bot.

A first version in 40 lines

Install the SDK with pip install openai and export the key as UNCENSORED_API_KEY. This script is a full terminal chat with streaming.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.openainsfw.com/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
)

SYSTEM = (
    "You are Mara, a dry-witted storyteller for adult readers. "
    "Stay in character, keep replies under 150 words."
)
history = [{"role": "system", "content": SYSTEM}]

while True:
    try:
        text = input("you> ").strip()
    except (EOFError, KeyboardInterrupt):
        break
    if not text:
        continue

    history.append({"role": "user", "content": text})
    stream = client.chat.completions.create(
        model="uncensored",
        messages=history,
        stream=True,
        temperature=0.9,
    )

    reply = ""
    print("bot> ", end="", flush=True)
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            piece = chunk.choices[0].delta.content
            reply += piece
            print(piece, end="", flush=True)
    print()
    history.append({"role": "assistant", "content": reply})

Walk through the loop. The system message sets the character and is never removed. Each pass appends the user text, streams the answer piece by piece, and stores the full reply so the next turn includes it. If you stop the program, the conversation is gone, because the list lives in memory only. Persistence comes later.

Shaping the persona with the system prompt

Most of what makes a bot feel like a product happens in the system message. A few habits give better results than a long, vague description.

  • Be specific about voice. "Short sentences, dry humour, never apologises" steers the style better than "friendly and helpful".
  • State the length. A word limit in the prompt controls output cost and keeps chat bubbles readable.
  • Give the setting. For roleplay, name the scene, the characters and what the bot should not do, such as speaking for the user.
  • Test with seed and low temperature. The API passes temperature, top_p, stop, seed and the penalties through, so you can make a run repeatable while tuning, then raise the temperature for production.

Keep the prompt short, since it is sent on every turn and billed every time as input. A 600-token persona over a 20-turn chat adds 12,000 input tokens, about $0.0018 in total. That is small, yet in a busy bot it multiplies by thousands of chats.

Trimming history so it does not grow forever

The context window is 100,000 tokens, shared between prompt and reply, which is far more than a casual chat needs. The problem with an ever-growing history is not the limit but the cost and speed: every turn resends everything before it. A simple fix is to keep the system message plus the last N messages.

from openai import OpenAI

client = OpenAI(base_url="https://api.openainsfw.com/v1", api_key="set-from-env")
MODEL = "uncensored"  # model ID used with every call to the endpoint
MAX_MESSAGES = 24     # about 12 exchanges

def trimmed(history):
    system, rest = history[0], history[1:]
    return [system] + rest[-MAX_MESSAGES:]

# inside the loop, call the API with the trimmed copy:
# client.chat.completions.create(model=MODEL, messages=trimmed(history), stream=True)

Cutting by message count is crude but predictable. A better rule is a token budget: estimate tokens as characters divided by four, and drop the oldest messages until the total fits. For long-running characters, summarise instead of dropping. Every 30 messages, ask the model to write a short summary of the older part, store it as a second system message, and delete the originals. The bot then remembers the plot without paying to resend it word for word.

Limits, 429 errors and retries

A full key allows 8 requests at once and 300 per minute. A trial key allows 2 and 60. A streamed reply holds its concurrency slot until the stream finishes, so a slow reader counts as a busy request the whole time. For a single-user terminal bot this never matters. For a public bot it decides whether people see errors.

On overload the API returns HTTP 429. The error code rate_limited means too many requests per minute, and concurrency means too many at once. A temporary overload also sends Retry-After: 5. Wrap the call in a small retry:

import os
import time
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.openainsfw.com/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
)

def ask(messages, tries=4):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(
                model="uncensored", messages=messages, stream=True
            )
        except RateLimitError as err:
            wait = 5
            retry_after = getattr(err.response, "headers", {}).get("retry-after")
            if retry_after and retry_after.isdigit():
                wait = int(retry_after)
            time.sleep(wait * (attempt + 1))
    raise RuntimeError("still rate limited, try again later")

Create the client with max_retries=0 if you want this function to be the only retry layer; otherwise the SDK adds its own. Failed or refused requests are not charged, so retrying is free of billing risk. For many users at once, put a semaphore of 8 around the API call and queue the rest.

From terminal to Telegram, Discord or the web

The terminal loop is the core. Platform bots only change how messages arrive and leave. The design that works across all of them is one history per conversation, keyed by chat ID:

  1. Receive an incoming message with the platform library (python-telegram-bot, discord.py, or a web framework route).
  2. Look up histories[chat_id], creating it with the system message if it is new.
  3. Append the user message, trim, and call the API with stream=True.
  4. Edit the outgoing message in batches as chunks arrive. Most chat platforms limit how often you can edit a message, so update every second or every few dozen tokens instead of on each chunk.
  5. Save the finished reply to the history and write it to disk or a database.

Store histories in SQLite or Redis once the bot restarts matter. Save the raw message list as JSON per chat. Also log the X-Request-Id response header with each turn; the support page asks for it if something looks wrong. The header X-Balance-USD shows the remaining credit, so your bot can warn you in an admin channel before the balance runs out.

Other tools can do the same job without code. SillyTavern, for example, lets you add an OpenAI-compatible endpoint: paste the base URL and key, and choose uncensored as the model. Write your own bot when you need custom logic, billing, or a specific platform.

Guardrails and failure handling for a public bot

A bot on your own laptop only has to work. A bot that strangers use has to survive them. Three things are worth adding before you share the link.

Input limits. Reject or cut messages above a sensible length, say 4,000 characters. The request body can be up to 8 MB, but a single user pasting a novel into every turn will inflate your bill, since that text is then resent as history on every later turn.

Per-user rate limits. The API limit is per key, so one noisy user can use up the minute for everyone else. Count messages per user and refuse politely after, for example, 10 per minute. A short "give me a moment" message is better than a silent failure.

Content rules of your own. The model is tuned not to refuse lawful adult requests, which means your app is where age gating and house rules live. State clearly who the bot is for, ask users to confirm they are adults if your service requires it, and block anything sexual involving minors outright. The API itself forbids it, and so should your terms and your code.

Finally, decide what the user sees when the API fails. Catch exceptions, show a plain message such as "I lost the thread, please resend", and keep the history unchanged so the retry does not duplicate the user turn. Remove the unanswered user message from the list if the call failed, otherwise the next request will carry two user messages in a row.

What a bot costs to run

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit with no subscription. Here is a worked estimate for a public bot.

Assume 200 conversations per day, each with 15 turns, so 3,000 turns per day. With a trimmed history, a typical turn sends about 3,000 input tokens and returns about 250 output tokens.

  • Input per day: 3,000 turns times 3,000 tokens is 9,000,000 tokens, which costs 9 times $0.15, or $1.35.
  • Output per day: 3,000 times 250 is 750,000 tokens, which costs 0.75 times $0.50, or $0.375.
  • Total per day: $1.725. Over 30 days: $51.75.

Halve the history cap and most of the input line halves with it. That is why trimming matters more than any other optimisation. For a hobby bot used by a few friends, the numbers are tiny: a 20-turn chat with a short persona costs a couple of cents.

The lowest top-up is $20, any whole amount up to $500. Bonuses start at 5% from $50, 10% from $100 and 15% from $200. Payment is crypto only, in USDT on TRC20 or USDC on Base, and credit never expires. See the pricing page for details, and the quickstart for the first request. Prompts are not used for training.

Questions and answers

Does the API remember earlier messages in a chat?

No. Every call must include the history you want the model to see. Keep a list of messages in your code and send it each time.

How do I make the bot answer in a fixed character?

Put the character description in a system message at the start of the list, and keep it when you trim old messages. Specific voice and length rules work better than vague adjectives.

How many users can the bot serve at once?

A full key allows 8 concurrent requests and 300 per minute. A streamed reply holds its slot until it finishes, so queue extra requests behind a semaphore of 8.

Can I use this with SillyTavern or other front ends?

Any client that accepts an OpenAI-compatible endpoint can use it. Enter the base URL https://api.openainsfw.com/v1, your key, and the model ID uncensored.

Is there a content limit I must enforce in my bot?

Yes. Sexual content involving minors is never allowed. If your bot is public, add your own age and content checks on top.

Your key is one form away

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

Get API key