EN ▾
Get API key

How to Make an Unrestricted AI Chatbot in Python

If you are searching for how to make unrestricted ai chatbot code, here it is in about 60 lines of Python. You need an API key, the openai package, and a loop that keeps the conversation and streams each reply. The model behind it answers without content refusals for lawful adult use.

A workbench building a chat bubble from glowing blocks with a stream of light, illustrating building a chatbot
Balance scale weighing a glowing coin against many chat bubbles, illustrating low per-message API cost

Updated

Key points

  • Install the openai package and point it at https://api.unrestrictedchatbot.com/v1 with model uncensored.
  • Memory is a list of messages that you resend on every call.
  • Stream with stream=True and print chunks as they arrive.
  • Trim and summarize history to stay far below the 100,000-token window and keep cost low.

Step 1: get a key

Sign up with Google or with email and password, then open the API key page. One click claims $0.50 of trial credit with no card. It is valid for 7 days and limited to one per person. Copy the key and store it in an environment variable so it never ends up in your code.

export API_KEY="paste-your-key-here"
python3 -m venv venv
source venv/bin/activate
pip install openai

The API is OpenAI-compatible, so the official openai package works. You only change the base URL, the key and the model ID.

Step 2: send one message

Start with the smallest working program, so you know the connection is fine before you add features.

import os
from openai import OpenAI

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

r = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Introduce yourself in two sentences."}],
)
print(r.choices[0].message.content)

If this prints a reply, you are done with setup. If you get an error, the status code tells you where to look: a rejected key, a wrong URL, or a limit. The documentation lists them.

Step 3: add a personality

"Unrestricted" describes what the model will answer. It does not decide how the bot behaves. That is your system prompt. Without one, the bot is a generic assistant. With one, it has a voice.

SYSTEM = (
    "You are Rook, a sarcastic, well-read chess club veteran. "
    "Answer directly, with short sentences and dry humor. "
    "You speak with adults and do not lecture."
)

The model itself is one open-weight model tuned to answer without refusals for lawful adult use, run by an independent provider. It is not any vendor's official product. One limit stays fixed: no sexual content involving minors.

Tune the settings

Three settings change how the bot feels more than any other. temperature controls randomness: 0.3 to 0.5 gives steady, factual answers; 0.8 to 1.0 gives livelier, more varied text. max_tokens is optional, since the completion can use the rest of the window, but a cap of 300 to 500 keeps a chat bot from writing essays. Penalties such as frequency_penalty reduce repeated phrases in long sessions.

Write the system prompt as instructions, not as a story. "Answer in under 80 words" works better than "Rook is a man of few words". Test a persona against five or six awkward user messages before you ship it, and keep the ones that stayed in character.

Step 4: memory, streaming and the full loop

The API is stateless. The model remembers nothing between calls, so the bot's memory is a list that you append to and resend. Streaming makes replies appear word by word instead of after a pause.

import os
from openai import OpenAI

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

SYSTEM = "You are Rook, a sarcastic, well-read chess club veteran. Be brief."
history = []

def chat(user_text):
    history.append({"role": "user", "content": user_text})
    messages = [{"role": "system", "content": SYSTEM}] + history[-30:]
    stream = client.chat.completions.create(
        model="uncensored",
        messages=messages,
        stream=True,
        temperature=0.8,
    )
    reply = ""
    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})

while True:
    text = input("you> ").strip()
    if text in ("quit", "exit"):
        break
    chat(text)

Notice history[-30:]. It keeps the last 30 messages, which means the bot forgets older turns but costs stay flat.

Step 5: save sessions

A bot that loses its memory on restart feels broken. Save the list to disk after each turn with the standard library.

import json, pathlib

SAVE = pathlib.Path("session.json")

def load():
    if SAVE.exists():
        return json.loads(SAVE.read_text())
    return []

def save(history):
    SAVE.write_text(json.dumps(history, ensure_ascii=False, indent=2))

# at start: history = load()
# at the end of chat(): save(history)

For several users, use one file or database row per user, keyed by their ID. Do not mix histories.

Handle errors without crashing

A chatbot that dies on the first network hiccup is annoying. Wrap the call so it retries on rate limits and reports other errors in plain words. The openai package raises typed exceptions you can catch.

import time
import openai

def safe_create(**kwargs):
    for attempt in range(4):
        try:
            return client.chat.completions.create(**kwargs)
        except openai.RateLimitError:
            time.sleep(5 * (attempt + 1))
        except openai.APIConnectionError:
            time.sleep(2)
        except openai.APIStatusError as e:
            print("API error", e.status_code, e.message)
            return None
    print("gave up after retries")
    return None

On a temporary overload the API answers 429 with Retry-After: 5, so a wait of five seconds is a sensible first delay. A request that fails or is refused is not billed, which makes retries safe for your balance. For streaming calls, pass stream=True through safe_create and loop over the result as before.

Cost and limits for a chatbot

At $0.15 per 1M input tokens and $0.50 per 1M output tokens, a turn with 2,000 tokens of history and a 200-token reply costs 2,000 / 1,000,000 x $0.15 + 200 / 1,000,000 x $0.50 = $0.0003 + $0.0001 = $0.0004. One thousand turns cost $0.40. Your trial credit of $0.50 therefore covers about 1,250 turns.

Limits matter if you serve many people. A full key allows 8 concurrent requests and 300 requests per minute. A streamed request holds its slot until the stream ends. When you exceed a limit you get HTTP 429, with rate_limited or concurrency as the code, and you should retry after a short delay. Failed or refused requests are not charged. When the trial runs out, see the pricing page: top-ups start at $20, by crypto, and credit never expires.

Where to take it next

  • Summaries: every 20 turns, ask the model to summarize older messages and keep the summary instead of the raw text.
  • Tool calling: let the bot call functions such as a dice roller or a note saver using the tools field.
  • Front ends: put the same loop behind a web page, a Discord bot or a Telegram bot.
  • Safety: add an adult gate and a block on any request involving minors in your own app code.

For the product side, read the page on the unrestricted chatbot itself, and the unrestricted API overview.

Questions and answers

Do I need a GPU to make an unrestricted AI chatbot?

No. The model runs on the provider's servers. Your computer only needs Python and an internet connection.

Why does my bot forget earlier messages?

The API keeps no state. You must resend the history with each call, and trimming it removes older turns.

Can I use Node instead of Python?

Yes. The openai package for Node accepts the same baseURL and apiKey options, with model uncensored.

Are my chats used to train the model?

No. Prompts are not used for training.

Your key is one form away

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