EN ▾
Get API key

Unrestricted Chatbot in Python: Minimal Code Example

This unrestricted chatbot python example needs only the OpenAI SDK, a new base URL and the model ID uncensored. Below is a working loop with history, then streaming, retries, tools and JSON mode.

Updated

Terminal with a stream of light packets flowing from a snake-shaped pipe into a chat bubble, for a Python chatbot

Key points

  • Install openai, set base_url to https://api.unrestrictedchatbot.cc/v1 and use the model uncensored.
  • Memory is a list of messages that you resend on each turn, so trim it as it grows.
  • Streaming, tool calling and JSON mode follow the standard OpenAI formats.
  • On 429, wait and retry; a full key allows 8 concurrent requests and 300 per minute.

Install and configure in one minute

An unrestricted chatbot in Python takes about forty lines, because the API speaks the OpenAI chat completions format. You install the official openai package, point it at a different base URL, and use the model ID uncensored. Nothing else in your code needs to change.

Get a key first. Sign up with Google, or with email and password, and open the API key page. New users can claim $0.50 of trial credit there with one click, which is plenty for everything in this article. Then set the key as an environment variable so it never lands in a source file.

pip install openai
export UNRESTRICTED_API_KEY="paste-your-key-here"
# endpoint used below: https://api.unrestrictedchatbot.cc/v1 , model: uncensored

Two details to keep in mind. The auth scheme is a standard Authorization: Bearer header, which the SDK sets for you from api_key. And the service exposes two methods, POST /v1/chat/completions and GET /v1/models, so code that depends on other OpenAI endpoints such as embeddings or images will not work here. The model is text only.

A minimal chat loop with history

The core idea of every chatbot is one list. The API remembers nothing between requests, so you keep a list of messages and send the whole list each time. Append the user's text, call the API, append the reply. That is the entire memory system.

import os
from openai import OpenAI

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

messages = [{"role": "system", "content": "You are a blunt, helpful assistant."}]

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

    messages.append({"role": "user", "content": text})
    r = client.chat.completions.create(model="uncensored", messages=messages)
    answer = r.choices[0].message.content
    messages.append({"role": "assistant", "content": answer})
    print("bot>", answer)

The first message, with role system, sets behaviour. Change its text and the personality of the bot changes. The model is one open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use, so a system prompt that asks for blunt or dark fiction is followed rather than met with a stock refusal. One rule stays fixed: no sexual content involving minors.

Run the script, type a few messages and ask the bot to repeat something you said two turns earlier. If it can, the history is working.

Stream the reply as it is written

The blocking loop above waits for the whole answer before printing. For long replies this feels slow, and streaming fixes it. Pass stream=True and the server sends the text in small pieces over server-sent events. Usage numbers arrive at the end of the stream, so you can still log what each turn cost.

import os
from openai import OpenAI

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

messages = [{"role": "system", "content": "You are a blunt, helpful assistant."}]

def ask(text):
    messages.append({"role": "user", "content": text})
    stream = client.chat.completions.create(
        model="uncensored",
        messages=messages,
        stream=True,
    )
    parts, usage = [], None
    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)
        if getattr(chunk, "usage", None):
            usage = chunk.usage
    print()
    messages.append({"role": "assistant", "content": "".join(parts)})
    return usage

while True:
    try:
        text = input("you> ").strip()
    except (EOFError, KeyboardInterrupt):
        break
    if text:
        print("bot> ", end="")
        u = ask(text)
        if u:
            print(f"[{u.prompt_tokens} in, {u.completion_tokens} out]")

Two practical notes. First, a streamed request holds one of your concurrency slots until the stream ends. A full key allows 8 at once and a trial key allows 2, so a chat app serving many people needs a queue or a retry rule. Second, join the pieces and store the finished text in your history, not the individual chunks.

Keep the history from growing without limit

The context window is 100,000 tokens, prompt and completion together, which is large but not infinite. More to the point, you pay for the history again on every turn, at $0.15 per 1M input tokens. A chat that has reached 20,000 tokens of history costs 20,000 x $0.15 / 1,000,000 = $0.003 in input alone for each new message. That is small, and it adds up across thousands of turns. A cheap way to trim is to drop the oldest user and assistant pair while keeping the system prompt.

from openai import OpenAI

client = OpenAI(
    base_url="https://api.unrestrictedchatbot.cc/v1",
    api_key="set-from-env-in-real-code",
)
MODEL = "uncensored"
MAX_CHARS = 120_000   # rough budget for history, about 30k tokens

def trim(messages):
    system, rest = messages[:1], messages[1:]
    while sum(len(m["content"]) for m in rest) > MAX_CHARS and len(rest) > 2:
        rest = rest[2:]          # drop the oldest user+assistant pair
    return system + rest

The character count is a rough stand-in for tokens, since English text averages somewhere around four characters per token. If you need an exact count, use a tokenizer library, or read the usage numbers the API returns. For stories where old events matter, ask the model to summarise the dropped turns into a short note and add the note to the system message. The cost and trade-offs article shows how history length turns into dollars.

Handle rate limits and errors

Limits on a full key are 8 concurrent requests and 300 requests per minute, and 2 and 60 on a trial key. Past either limit the API returns HTTP 429. The error code is rate_limited when you sent too many requests per minute and concurrency when too many were in flight. On temporary overload you also get a 429, with a Retry-After: 5 header. The Python SDK raises RateLimitError for all of these, so one handler covers them.

import time
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.unrestrictedchatbot.cc/v1",
    api_key="set-from-env-in-real-code",
)

def complete(messages, tries=4):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError:
            time.sleep(5 * (attempt + 1))   # the API sends Retry-After: 5 on overload
    raise RuntimeError("still rate limited after retries")

Requests that fail or are refused are not charged. The request body can be up to 8 MB, which only matters if you paste very large documents. Every response includes X-Request-Id for support questions, plus X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency.

Add tool calling and JSON mode

A chatbot that only talks is useful, and one that can call your code is more so. Tool calling follows the OpenAI format: you describe functions with tools, the model replies with tool_calls, you run the function, and you send the result back as a message with role: "tool". This example gives the bot a clock.

import json, os
from datetime import datetime, timezone
from openai import OpenAI

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

tools = [{
    "type": "function",
    "function": {
        "name": "utc_now",
        "description": "Return the current UTC time as an ISO 8601 string.",
        "parameters": {"type": "object", "properties": {}},
    },
}]

messages = [{"role": "user", "content": "What time is it in UTC right now?"}]
r = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
msg = r.choices[0].message

if msg.tool_calls:
    messages.append(msg)
    for call in msg.tool_calls:
        result = datetime.now(timezone.utc).isoformat()
        messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
    r = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)

print(r.choices[0].message.content)

When you need structured output instead, such as a mood tag next to the reply, JSON mode makes the model return a valid JSON object. Tell it the keys you want in the system message, because the mode guarantees syntax and not your schema.

import json, os
from openai import OpenAI

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

r = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply only with JSON: {\"mood\": string, \"reply\": string}"},
        {"role": "user", "content": "I finally fixed that bug."},
    ],
)
data = json.loads(r.choices[0].message.content)
print(data["mood"], "->", data["reply"])

Node developers can use the same pattern with the official JavaScript package. Only the base URL and key change.

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.unrestrictedchatbot.cc/v1",
  apiKey: process.env.UNRESTRICTED_API_KEY,
});

const r = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Say hello in five words." }],
});
console.log(r.choices[0].message.content);

For the full list of supported parameters, including temperature, top_p, stop, seed and the penalties, see the API docs.

Common problems and quick fixes

Most first-run failures come from a short list of causes.

  • 401 or authentication errors. The key is missing or has a stray space or newline. Print len(os.environ["UNRESTRICTED_API_KEY"]) to check that the variable is set in the shell that launches Python.
  • An error about the model. The model ID must be exactly uncensored. You can list what the key can see with GET /v1/models or client.models.list().
  • Connection errors against api.openai.com. You created the client without base_url, or an environment variable such as OPENAI_BASE_URL from another project overrides your setting. Pass the URL in code to be explicit.
  • The bot forgets earlier messages. The reply was not appended to the list, or the list is rebuilt inside the loop. Check that messages is created once, outside the loop.
  • The bot writes the user's lines too. Add a stop sequence such as "you>", or state in the system prompt that it must answer only as itself.
  • Replies cut off or very long. Set max_tokens if you want a cap. It is optional, and without it a reply can use whatever is left of the 100,000-token window.

If a problem persists, keep the value of the X-Request-Id response header for the failing call and send it through the support page.

What this costs to run

A hobby chatbot is cheap. Say one exchange sends 2,000 input tokens and returns 400 output tokens: 2,000 x $0.15 / 1M = $0.0003, and 400 x $0.50 / 1M = $0.0002, so $0.0005 per message. A thousand messages cost $0.50, which is the size of the trial credit. A $20 top-up covers about 40,000 messages of that shape. Top-ups run from $20 to $500 in any whole amount, with +5% from $50, +10% from $100 and +15% from $200. On this site you pay by crypto (USDT on TRC20, USDC on Base), and credit never expires. The pricing page has the full table.

Prompts are not used for training. That covers what you send through your Python bot, though you remain responsible for what you store in your own logs.

Questions and answers

Which model ID do I use in Python?

Use uncensored as the model value and set base_url to https://api.unrestrictedchatbot.cc/v1 on the OpenAI client. The key goes in api_key.

Does my existing OpenAI SDK code work?

For chat completions, streaming, tool calling and JSON mode, yes, after you change the base URL, key and model. Endpoints for images, audio or embeddings are not available.

How do I keep the conversation memory?

Store every message in a list and send the whole list with each request. The server keeps no state between calls.

Why do I get a 429 error?

You passed 300 requests per minute, 8 concurrent requests, or the lower trial limits of 60 and 2. The error code tells you which, and a short wait and retry fixes it.

Your key is one form away

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