Unrestricted AI API: Python Setup with the OpenAI SDK
An unrestricted ai api here means a hosted, OpenAI-compatible text endpoint whose model answers lawful adult requests without the usual content refusals. This guide shows the Python setup, from a ten-line script to streaming, tools and retry logic.
Updated

Key points
- Install the openai package, set base_url and api_key, and use model <code>uncensored</code>.
- Chat history is yours to manage: resend the messages list on each turn.
- Cap parallel calls at 8 with a semaphore (2 on a trial key) and retry 429 responses.
- Top up by crypto from $20; a one-click $0.50 trial covers testing.
The ten-line version
If you already have Python 3.9 or newer, this is the full setup. Install the SDK, export your key, and run the script.
# base URL https://api.unrestrictedaichatbot.top/v1, model uncensored
pip install openai
export UNRESTRICTED_API_KEY="paste-your-key-here"import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unrestrictedaichatbot.top/v1",
api_key=os.environ["UNRESTRICTED_API_KEY"],
)
reply = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Name three plot twists for a space-opera mystery."}],
)
print(reply.choices[0].message.content)That is the entire integration. The service implements POST /v1/chat/completions and GET /v1/models, so the official OpenAI package works once the base URL and key are swapped. The model is one open-weight model run by an independent provider, tuned to answer without content refusals for lawful adult use. It is not an official API of any large vendor and not a router, and it has one hard rule: no sexual content involving minors. Text only, so no images, audio, embeddings or fine-tuning. For a fuller picture of what the service does and does not claim, read the myths and facts article.
Getting a key and paying for it
Create an account with Google or with an email and password, then open the key page. New users can claim $0.50 of trial credit with one click. It is limited to one per person, lasts 7 days and needs no card. A trial key runs at 2 concurrent requests and 60 requests per minute.
For real use, add credit from $20 to $500 in any whole amount. You can pay with crypto (USDT on TRC20, USDC on Base). Bonuses apply on larger top-ups: +5% from $50, +10% from $100, +15% from $200. Billing is per token, $0.15 per 1M input and $0.50 per 1M output, with no subscription and no expiry on credit. A full key allows 8 concurrent requests and 300 requests per minute. Current figures are on the pricing page.
Configure the client once, reuse it everywhere
Create the client at module level and import it. The SDK keeps connections open and reuses them, which is faster than building a new client per call. The constructor also accepts a timeout and a retry count, both of which are worth setting.
# llm.py
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unrestrictedaichatbot.top/v1",
api_key=os.environ["UNRESTRICTED_API_KEY"],
timeout=120.0,
max_retries=3,
)
MODEL = "uncensored"
def ask(messages, **kwargs):
r = client.chat.completions.create(model=MODEL, messages=messages, **kwargs)
return r.choices[0].message.contentA timeout of 120 seconds suits long answers, because a reply that fills a big part of the 100,000-token window takes a while to generate. The SDK's built-in retry handles transient 429 and server errors with a short backoff. For code that you run in bulk, add your own handling as shown further down.
Keep the key in an environment variable or a secrets manager and never in the repository. If you ever suspect a leak, create a fresh key and replace it. Check the documentation for the current reference when you need exact field names.
Build a chat loop with memory
The API is stateless. The model remembers nothing between calls, so a chatbot is simply a list that you keep appending to and send back each time.
# client and MODEL come from llm.py (base_url https://api.unrestrictedaichatbot.top/v1, model uncensored)
from llm import client, MODEL
history = [
{"role": "system", "content": "You are Mara, a dry-witted ship's navigator in a sci-fi roleplay. Stay in character."}
]
while True:
user = input("you> ").strip()
if user in {"quit", "exit"}:
break
history.append({"role": "user", "content": user})
r = client.chat.completions.create(
model=MODEL,
messages=history,
temperature=0.9,
max_tokens=500,
)
answer = r.choices[0].message.content
history.append({"role": "assistant", "content": answer})
print("mara>", answer)Two details matter. First, the system message sets the character and the rules of the scene, so write it with care, and keep it first in the list. Second, the list grows each turn and you pay input price for all of it on every call. Once a session passes a few dozen turns, trim older messages, or replace them with a short summary that you ask the model to write. The window allows 100,000 tokens, but you rarely need to use that much for a conversation.
Persistence is up to you. A web app usually stores the list per conversation in a database and loads it on each request. A command-line tool can dump it to a JSON file on exit. Whichever you choose, store the raw messages and not only the final text, so you can rebuild the prompt exactly, change the system message later or cut the history to a shorter window without losing the original.
Use cases that fit this pattern are fiction and roleplay tools, companion apps for adults, drafting assistants and writing-room utilities. Keep your own checks in place for who can use your product, because the lawful-adult-use boundary is yours to enforce on your side as well.
Streaming the answer
For anything interactive, stream. Set stream=True and iterate over the chunks. Tokens arrive over SSE, and usage is reported at the end.
# client and MODEL come from llm.py (base_url https://api.unrestrictedaichatbot.top/v1, model uncensored)
from llm import client, MODEL
stream = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Describe a rainy harbour town in two paragraphs."}],
stream=True,
)
parts = []
for chunk in stream:
if not chunk.choices:
continue
piece = chunk.choices[0].delta.content
if piece:
parts.append(piece)
print(piece, end="", flush=True)
full_text = "".join(parts)Join the pieces into one string as shown, so you can store the finished reply in your history list after the stream ends. If you only print tokens and forget to keep them, the next turn will have a hole in the conversation. For web apps, forward each piece to the browser over your own SSE or WebSocket connection and keep the join on the server.
One operational note: a streaming request occupies its concurrency slot until the stream ends, not until the first token. If a client disconnects, close the stream in your code so the slot is released sooner.
JSON mode and tool calling
JSON mode returns a valid JSON object when you pass response_format. Describe the keys in the prompt, since the flag controls format and not schema.
import json
# client and MODEL come from llm.py (base_url https://api.unrestrictedaichatbot.top/v1, model uncensored)
from llm import client, MODEL
r = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": "Reply with a JSON object with keys name, role and secret."},
{"role": "user", "content": "Invent a side character for a noir story."},
],
response_format={"type": "json_object"},
)
character = json.loads(r.choices[0].message.content)
print(character["name"])Tool calling follows the OpenAI format. Declare the tools, check whether the reply contains tool_calls, run your function, and send the result back with role: "tool".
import json, random
# client and MODEL come from llm.py (base_url https://api.unrestrictedaichatbot.top/v1, model uncensored)
from llm import client, MODEL
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll one die with the given number of sides",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer"}},
"required": ["sides"],
},
},
}]
messages = [{"role": "user", "content": "Roll a twenty-sided die for the lockpicking check."}]
first = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, tool_choice="auto")
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg)
for call in msg.tool_calls:
sides = json.loads(call.function.arguments)["sides"]
messages.append({"role": "tool", "tool_call_id": call.id, "content": str(random.randint(1, sides))})
final = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
print(final.choices[0].message.content)
else:
print(msg.content)The second call is needed because the model only asks for the tool; it never runs it. Your code runs the function, hands back the result, and the model then writes the final reply in its own words. For a game master bot, the same loop can drive dice, inventory lookups or a database of character sheets. Tool calls can also stream, with tool_calls arriving in pieces that you join before parsing.
Always parse tool arguments with json.loads and validate them. A model can produce an argument you did not expect, and your function should not trust it blindly.
Production habits and using the API without the SDK
The SDK is optional. Because the API is plain HTTPS and JSON, the requests library works if you want fewer dependencies, for instance in a small serverless function.
import os
import requests
r = requests.post(
"https://api.unrestrictedaichatbot.top/v1/chat/completions",
headers={"Authorization": "Bearer " + os.environ["UNRESTRICTED_API_KEY"]},
json={
"model": "uncensored",
"messages": [{"role": "user", "content": "Give me a villain's catchphrase."}],
"max_tokens": 60,
},
timeout=120,
)
r.raise_for_status()
print(r.json()["choices"][0]["message"]["content"])
print("balance:", r.headers.get("X-Balance-USD"))Libraries that wrap the OpenAI client generally expose the same two knobs. LangChain's ChatOpenAI, for example, takes a base_url, an api_key and a model argument, so the values from this article carry over directly.
A few habits save trouble once the script becomes a product:
- Log usage per request. Store
usage.prompt_tokensandusage.completion_tokenswith a user ID. At $0.15 and $0.50 per 1M tokens, that table is your cost report. - Validate user input size. The request body is limited to 8 MB, and the window to 100,000 tokens. Reject or trim oversized input before you send it.
- Keep the key on the server. Never ship it inside a browser or mobile app. Call the API from your backend and expose your own endpoint.
- Separate environments. Use the trial key for development, so a bug in a loop cannot spend a paid balance.
Prompts are not used for training, which is worth stating in your own privacy text if your product handles personal conversations.
Rate limits, retries and parallel calls
Over a limit the API returns HTTP 429. The error code rate_limited means too many requests per minute, and concurrency means too many at once. On temporary overload you also get 429 with a Retry-After: 5 header. In the SDK these surface as openai.RateLimitError. The body size cap is 8 MB.
For batch work, an asyncio semaphore keeps you inside the concurrency limit, and a simple retry loop handles the rest.
import asyncio, os
from openai import AsyncOpenAI, RateLimitError
client = AsyncOpenAI(
base_url="https://api.unrestrictedaichatbot.top/v1",
api_key=os.environ["UNRESTRICTED_API_KEY"],
max_retries=0,
)
sem = asyncio.Semaphore(8) # use 2 for a trial key
async def one(prompt):
async with sem:
for attempt in range(5):
try:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
max_tokens=300,
)
return r.choices[0].message.content
except RateLimitError:
await asyncio.sleep(5)
return None
async def main():
prompts = [f"Write a one-line tavern rumour, number {i}." for i in range(40)]
results = await asyncio.gather(*(one(p) for p in prompts))
print(sum(r is not None for r in results), "done")
asyncio.run(main())Failed and refused requests are not charged, so retries cost nothing when they fail. Read X-Balance-USD from a response to track your balance, and keep the X-Request-Id value in your logs so the support team can find a specific call.
More guides
Questions and answers
Can I use the official OpenAI Python package?
Yes. Set base_url to the service URL and api_key to your key, use model uncensored, and the rest of the code stays the same.
Which Python version do I need?
Any version supported by the current openai package works. Python 3.9 or newer is a safe choice.
Does the API remember my conversation?
No. It is stateless, so you send the full messages list on each request and manage history yourself.
How do I handle 429 errors in Python?
Catch RateLimitError, wait about five seconds and retry, and limit parallel calls to 8 with a semaphore. Use 2 on a trial key.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.