EN ▾
Claim trial key
FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI FilterNoAI

AI No Filter Chatbot in Python: Tutorial

An ai no filter chatbot python tutorial in about 70 lines: a terminal chat with streaming replies, history trimming and rate-limit handling.

Last updated

Terminal window streaming chat bubbles while light scissors trim the oldest message card

Summary

  • The API has no memory, so your code resends the history each turn
  • Trim history by estimated tokens to keep cost flat
  • Stream with stream=True and handle 429 with Retry-After
  • The $0.50 trial is enough to build and test the whole bot

What you will build

This ai no filter chatbot python tutorial builds a terminal chat program of about 70 lines. It talks to an OpenAI-compatible endpoint, streams replies word by word, keeps a conversation history, trims that history so it never grows without limit, and waits politely when the API says 429. You can then reshape it into a Discord bot, a web backend or a writing tool.

You need Python 3.9 or newer and an API key. If you have no key yet, sign up and claim the $0.50 trial on the API key page. It needs no card and is valid for 7 days, which is plenty for this project.

pip install openai
export NOFILTER_KEY="paste-your-key-here"

Step 1: the smallest working chat

Start with a single call so you know the connection works. Only the base URL, the key and the model ID are specific to this service.

import os
from openai import OpenAI

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

reply = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a sharp, informal conversation partner."},
        {"role": "user", "content": "Say hello in one sentence."},
    ],
)
print(reply.choices[0].message.content)

If that prints a greeting, the key and URL are right. The model is tuned to answer without content refusals for lawful adult use, so your system prompt is where you set the personality and the limits of your bot.

Step 2: remember the conversation

The API has no memory. Each request must contain the whole conversation, so your program keeps a list and appends to it. After the user speaks, add a message with role user. After the model answers, add one with role assistant. The system message goes first on every call, but you do not store it in the list, which keeps trimming simple.

The cost of this design is that input grows with each turn. A history of 6,000 tokens plus a short system prompt means roughly 6,500 input tokens on every call, or 6,500 / 1M x $0.15 = $0.000975. That is cheap, but an unbounded history will eventually reach the 100,000-token context window, and it makes every turn dearer than the last. Hence trimming.

Step 3: trim history by estimated tokens

Exact token counts need the model's tokenizer, which you do not have. A good-enough estimate for English is one token per four characters. The trimming function below drops the oldest messages until the estimate falls under a budget, and makes sure the history always starts with a user message.

MAX_HISTORY_TOKENS = 6000

def estimate_tokens(text):
    return len(text) // 4 + 4

def trim(history):
    def total():
        return sum(estimate_tokens(m["content"]) for m in history)
    while len(history) > 2 and total() > MAX_HISTORY_TOKENS:
        history.pop(0)
        while history and history[0]["role"] == "assistant":
            history.pop(0)

The newest exchange always survives. If you want the bot to remember older facts, replace the dropped messages with a short summary instead of discarding them. Ask the model itself: "Summarize this conversation in 120 words, keeping names and open threads", and put the result in the system message.

Step 4: stream and survive 429

Streaming makes a chat feel quick, because text appears as it is generated. Set stream=True and print each delta. Two details matter. A streamed request holds its concurrency slot until the stream ends, so do not start a second request while one is still open. And rate limits need handling: a full key allows 8 concurrent requests and 300 per minute, a trial key 2 and 60. Going over returns HTTP 429, with the code rate_limited or concurrency, or a Retry-After: 5 header on temporary overload.

The OpenAI SDK retries some errors by itself. Set max_retries=0 if you want to control the waiting, as the script below does. It reads Retry-After when present and sleeps for that long.

The full script

Save this as chat.py and run python chat.py. Type /reset to clear the history and /quit to leave.

import os
import time
from openai import OpenAI, RateLimitError

client = OpenAI(base_url="https://api.filternoai.com/v1", api_key=os.environ["NOFILTER_KEY"], max_retries=0)
MODEL = "uncensored"
SYSTEM = "You are a sharp, informal conversation partner. Keep replies under 150 words."
MAX_HISTORY_TOKENS = 6000


def estimate_tokens(text):
    return len(text) // 4 + 4


def trim(history):
    def total():
        return sum(estimate_tokens(m["content"]) for m in history)
    while len(history) > 2 and total() > MAX_HISTORY_TOKENS:
        history.pop(0)
        while history and history[0]["role"] == "assistant":
            history.pop(0)


def stream_reply(messages):
    for attempt in range(4):
        try:
            stream = client.chat.completions.create(
                model=MODEL, messages=messages, stream=True, temperature=0.8
            )
            parts = []
            for chunk in stream:
                if chunk.choices and chunk.choices[0].delta.content:
                    piece = chunk.choices[0].delta.content
                    parts.append(piece)
                    print(piece, end="", flush=True)
            print()
            return "".join(parts)
        except RateLimitError as e:
            wait = int(e.response.headers.get("Retry-After", "5"))
            print(f"[rate limited, waiting {wait}s]")
            time.sleep(wait)
    return None


def main():
    history = []
    print("Type /reset to clear history, /quit to exit.")
    while True:
        try:
            user = input("you> ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            break
        if not user:
            continue
        if user == "/quit":
            break
        if user == "/reset":
            history.clear()
            print("history cleared")
            continue
        history.append({"role": "user", "content": user})
        trim(history)
        print("bot> ", end="")
        reply = stream_reply([{"role": "system", "content": SYSTEM}] + history)
        if reply is None:
            history.pop()
            print("[giving up after repeated rate limits]")
            continue
        history.append({"role": "assistant", "content": reply})


main()

Testing and debugging the bot

Run the script with the trial key and walk through a short checklist before you add features.

  1. Check the connection. If the first reply never arrives, print the exception. A 401 usually means the key variable is empty or mistyped, and a connection error points to a wrong base URL.
  2. Check the memory. Tell the bot a fact, ask a different question, then ask for the fact back. If it forgets at once, the history is not being appended.
  3. Check the trimming. Temporarily set MAX_HISTORY_TOKENS to 200 and chat for a few turns. Old messages should drop away while the newest exchange stays.
  4. Check the limits. Start two copies of the script on a trial key and send messages in both at once. The trial key allows 2 concurrent requests, so a third request is the one that triggers a 429 and the wait message.

To see what a session costs, log response.usage or read the X-Balance-USD header before and after. A 20-turn chat with a trimmed history of about 2,000 input tokens per turn and 200 output tokens per reply uses 40,000 input and 4,000 output tokens in total. That is 40,000 / 1M x $0.15 + 4,000 / 1M x $0.50 = $0.006 + $0.002 = $0.008, so the $0.50 trial covers around 60 such conversations.

Handling other errors

The script only catches rate limits. For a real deployment, also catch connection errors and server errors, retry them once or twice with a short pause, and show the user a plain message instead of a stack trace. Never retry in a tight loop, and keep the key in an environment variable rather than in the source file.

Where to take it next

  • Personas. Keep several system prompts in a dictionary and switch with a slash command. A narrator, a rival, a game master.
  • Saving. Write history to a JSON file on exit and load it on start, so a chat survives restarts.
  • Tools. The API supports tool calling, with results sent back as role: "tool" messages, so the bot can look up a dice roll or a note.
  • Several users. Keep one history per user ID, and cap total parallel requests at 8 on a full key.
  • Cost display. Read X-Balance-USD from the response headers to show the remaining credit.

The API documentation covers tools, JSON mode and the balance endpoints. For per-turn cost examples, see pricing, and for the economic side of running uncensored models, read No Filter: Cost and Trade-offs of Uncensored LLMs. If you ship this to others, add your own content rules, and remember the hard limit: sexual content involving minors is never produced.

Frequently asked questions

Which Python library do I need?

The official openai package. Set base_url to the API address, use your key, and set the model to uncensored.

Why does my bot forget earlier messages?

Either the history was trimmed past that point, or you are not sending it. The API keeps no memory between calls, so your code must resend the conversation.

Is streaming required?

No. It makes replies feel faster, but you can leave stream off and print the full reply once it arrives.

What happens when I hit a rate limit?

The API returns HTTP 429. Wait for the Retry-After time, then try again, as the script above does.

Access your API key

Sign up, copy the token, update your base URL. That is all.