Build an Unrestricted LLM Chatbot in Python
This tutorial shows how to build an unrestricted LLM chatbot of your own: a terminal app first, then the pieces a real product needs, such as history trimming, streaming and retries.
Updated

Key points
- A chatbot is a loop that resends the whole message list on every turn.
- Stream the reply and keep the history short to control both speed and cost.
- A typical 20-turn conversation costs about a cent and a half.
- Handle HTTP 429 with a short backoff; a stream holds its slot until it ends.
What you are building
An unrestricted LLM chatbot is an ordinary chat application whose model does not refuse lawful adult requests by reflex. The interface is no different from any other chatbot. What changes is the backend model, and with an OpenAI-compatible endpoint that is a two-line edit: a new base URL and a new key.
We will build the thing in stages. First a thirty-line terminal chat with memory. Then streaming, so replies appear word by word. Then a persona prompt, history trimming, error handling and a rough cost estimate. Everything uses the Python openai package with the base URL https://api.unrestricted.cc/v1 and the model ID uncensored.
Typical uses are fiction co-writing, roleplay and companion apps for adults, and interactive characters in games. The one hard rule is that content involving minors is never allowed, and you should build your own app's rules on top of that.
Setup
You need Python 3.9 or newer and an API key. Sign up, then claim the trial credit on the API key page: $0.50, valid for 7 days, no card needed. Install the SDK and store the key in an environment variable so it never lands in your source code.
pip install openai
export UNRESTRICTED_KEY="paste-your-key-here"
Remember that a trial key is limited to 2 concurrent requests and 60 requests per minute. A full key allows 8 concurrent requests and 300 per minute. For a single-user terminal chat, neither limit will bother you.
Step 1: a chat loop with memory
The API is stateless. The server does not remember your last message; you send the whole conversation each time. So the core of every chatbot is a list of messages that grows by two entries per turn: what the user said and what the model replied.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unrestricted.cc/v1",
api_key=os.environ["UNRESTRICTED_KEY"],
)
messages = [
{"role": "system", "content": "You are a witty co-writer for adult fiction."}
]
while True:
user = input("you> ").strip()
if user in {"exit", "quit"}:
break
messages.append({"role": "user", "content": user})
resp = client.chat.completions.create(model="uncensored", messages=messages)
reply = resp.choices[0].message.content
print("bot>", reply)
messages.append({"role": "assistant", "content": reply})
Run it and talk for a few turns. The bot recalls earlier lines because you keep appending them. If you forget to append the assistant reply, the model will lose track of its own side of the conversation, which is the most common beginner bug.
Step 2: stream the reply
Waiting for a full answer feels slow even when the total time is the same. Streaming prints tokens as they arrive. Set stream=True and read the chunks. The API sends them over server-sent events and includes token usage at the end.
def chat_stream(messages):
stream = client.chat.completions.create(
model="uncensored",
messages=messages,
stream=True,
temperature=0.9,
)
parts = []
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content or ""
print(delta, end="", flush=True)
parts.append(delta)
print()
return "".join(parts)
Swap this into the loop in place of the blocking call and append the returned string to the history. For creative chat, a temperature around 0.8 to 1.0 gives livelier prose; lower it toward 0.3 for tasks that need consistency. The API passes temperature, top_p, stop, seed and the penalties straight through, so you can tune all of them.
One operational detail: a streamed request occupies its concurrency slot until the stream finishes. If your web app opens a stream per visitor, that slot count is your real ceiling, not the requests-per-minute figure.
Step 3: write the persona prompt
With a model that does not refuse, the system prompt does more of the work. It decides tone, length, and boundaries. Vague prompts produce vague bots. Compare these two:
- Weak: "You are a helpful assistant."
- Better: "You are Mara, a dry-humoured ship's engineer in a sci-fi story. Stay in character. Reply in two to four short paragraphs. Ask one question at the end to keep the scene moving. Do not write on behalf of the user."
Four habits make persona prompts work. State the role and voice. Set a length range so replies do not balloon. Say what the bot must never do, such as speaking for the user or breaking the scene. And put the rules at the top, where they stay in view as the history grows.
If you run an app for the public, add your own house rules in the same place: no content involving minors, no real private individuals, whatever fits your audience. The model is tuned to answer without content refusals, so the boundaries of your product are yours to define and enforce.
Step 4: keep the history under control
Each turn resends everything, so input tokens grow with the length of the conversation. The context window is 100,000 tokens covering prompt plus completion, which is generous, but you pay for every input token on every turn. A simple fix is to keep the system message plus the last N messages.
MAX_MESSAGES = 24 # system prompt + last 23 messages
def trim(messages):
if len(messages) <= MAX_MESSAGES:
return messages
return [messages[0]] + messages[-(MAX_MESSAGES - 1):]
Call trim(messages) before each request. Dropping old turns loses some memory, so for long roleplay you can ask the model to write a short running summary every 20 turns and store it in a second system message. That gives the story continuity at a fraction of the token cost.
What a conversation costs
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. Take a 20-turn chat where the average request carries 4,000 input tokens and the average reply is 250 tokens.
- Input: 20 x 4,000 = 80,000 tokens, so 0.08 x $0.15 = $0.012.
- Output: 20 x 250 = 5,000 tokens, so 0.005 x $0.50 = $0.0025.
- Total: $0.0145 per conversation, about a cent and a half.
At that rate, 1,000 such conversations come to $14.50. The pricing page lists the top-up options, which start at $20.
Step 5: handle errors and limits
Production chatbots fail in boring ways, and most of them are rate limits. When you exceed the per-minute cap the API returns HTTP 429 with error code rate_limited. Too many simultaneous calls returns 429 with code concurrency. Temporary overload also returns 429, with a Retry-After: 5 header. The OpenAI SDK retries a couple of times by default; you can raise that and add your own message for users.
import time
from openai import OpenAI, RateLimitError
client = OpenAI(
base_url="https://api.unrestricted.cc/v1",
api_key=os.environ["UNRESTRICTED_KEY"],
max_retries=4,
)
def safe_chat(messages):
for attempt in range(3):
try:
return chat_stream(messages)
except RateLimitError:
time.sleep(5 * (attempt + 1))
return "The service is busy right now. Please try again in a moment."
Two more things to wire up. Responses include an X-Balance-USD header, handy for alerting yourself before credit runs out, and an X-Request-Id you should log so support can trace a problem. Failed or refused requests are not charged, so retries do not cost you twice.
Test the bot before real users do
Spend an hour trying to break your own chatbot before anyone else uses it. Write twenty prompts that cover your real use case, including the awkward ones, and run them in one batch. Read the replies for three things: does the character stay in voice, does the length stay inside your range, and does the bot ever speak for the user. Change the system prompt, rerun the same twenty and compare. Fixing a persona by testing beats fixing it by guessing.
Set a fixed seed while you compare versions of a prompt, because the API passes it through and the same input then gives more repeatable output. Once the prompt is settled, remove the seed so replies vary naturally. Also test the unhappy paths: unplug your network mid-stream, send an empty message, paste a very long one. A message near the 8 MB body limit is rejected, so decide in advance what your app tells the user. Small checks like these separate a demo from something people can rely on.
Turning it into a web chatbot
The terminal app becomes a web app with the same loop behind an HTTP route. Keep the API key on the server, never in browser code. Store each visitor's message list server-side, keyed by a session ID, and stream the reply to the browser with server-sent events. Cap the number of messages per session and per minute so one visitor cannot use up your 8 concurrent slots.
If you only want the model inside an existing chat client, you may not need to write code at all: many clients accept a custom OpenAI-compatible endpoint, and you paste in the base URL and key. For background on what this kind of model does and does not do, read our overview of chatbots on an uncensored model, and keep the API docs open for the full parameter list.
Your prompts are not used for training. Still, if your product handles personal conversations, publish your own privacy notice and decide how long you store chat logs.
More guides
Questions and answers
Do I need to write code to chat with the model?
No. Any client that accepts a custom OpenAI-compatible endpoint works. Paste the base URL, your key and the model ID uncensored.
Why does the bot forget things in long chats?
The API keeps no memory between requests. If you trim old messages to save tokens, the model cannot see them, so use a running summary for long stories.
How many users can chat at once?
A full key allows 8 concurrent requests and 300 requests per minute. Streams hold a slot until they finish, so plan around the concurrency number.
Is anything off limits?
Yes. Sexual content involving minors is never allowed, and you should add rules suited to your own audience on top.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.