EN ▾
Get API key

Unrestricted AI in Python: OpenAI SDK Quickstart

To run unrestricted ai python code you need the official openai package, a key, and two changed lines: the base URL and the model name. The rest of your OpenAI code stays as it is. This quickstart goes from install to streaming, JSON mode, tools and error handling.

Updated

Abstract terminal emitting a stream of light particles, representing a Python script calling an AI API

No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).

Get API key

Key points

  • pip install openai, then set base_url to https://api.unrestrictedaichat.com/v1 and model to uncensored.
  • Streaming, JSON mode and tool calling use the same arguments as the OpenAI SDK.
  • Catch RateLimitError and read Retry-After; a full key allows 8 concurrent requests.
  • Pay by crypto (USDT on TRC20, USDC on Base), from $20.

Install and make the first call

You need Python 3.8 or newer and the official SDK. Create a virtual environment so the dependency stays out of your system Python, then install it.

python -m venv .venv
source .venv/bin/activate
pip install openai
export UNRESTRICTED_KEY="paste-your-key-here"

Get the key on the sign-up page. You can register with Google or with an email and password, and new users can claim $0.50 of trial credit with one click on the key page. The credit lasts 7 days, so claim it when you are ready to test.

Now the smallest useful script for unrestricted ai python work:

import os
from openai import OpenAI

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

response = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a blunt, helpful assistant."},
        {"role": "user", "content": "Give me three plot twists for a spy thriller."},
    ],
)

print(response.choices[0].message.content)
print(response.usage)

Run it with python hello.py and you should see a short list of ideas followed by a usage object with prompt and completion token counts. If you get an authentication error instead, print the first four characters of the key to confirm the variable is set, and check there is no stray whitespace around it.

That is the whole integration. The model uncensored is one open-weight model run by an independent provider and tuned to answer without content refusals for lawful adult use. It is not the official API of any big vendor. The one fixed rule is that sexual content involving minors is blocked.

Keep the key and settings out of your code

Hard-coded keys end up in repositories. Read them from the environment, as above, or from a .env file loaded at start-up. The OpenAI SDK also reads two environment variables on its own, so you can configure it with no arguments at all:

export OPENAI_API_KEY="$UNRESTRICTED_KEY"
export OPENAI_BASE_URL="https://api.unrestrictedaichat.com/v1"
from openai import OpenAI

client = OpenAI()  # picks up both variables
r = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Say hello in five languages."}],
)
print(r.choices[0].message.content)

This is the easiest way to switch existing scripts and libraries over, because code you do not control, such as a framework that builds its own client, will honour the same variables. Check that your variable names are not already pointing at another provider in the same shell, or you will send the wrong key to the wrong host.

Streaming responses

For chat interfaces and long outputs, stream. Tokens arrive as they are generated, and the usage totals come at the end of the stream.

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a 300-word noir opening."}],
    stream=True,
    temperature=0.9,
)

parts = []
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        text = chunk.choices[0].delta.content
        parts.append(text)
        print(text, end="", flush=True)

full_text = "".join(parts)

Sampling arguments sit next to stream in the same call. Use a temperature near 0.9 for creative text and near 0.3 for extraction or rewriting. If the output loops on the same phrases, add frequency_penalty=0.3 or presence_penalty=0.3. Add stop=[" ###"] if you use a delimiter to end a section, and seed=42 when you want repeatable runs while you compare prompts.

The guard on chunk.choices avoids an index error on a final chunk that carries no text. One operational point: a streamed request occupies one of your concurrency slots until the stream finishes. If you consume the stream slowly, for example while writing to a slow client, you hold that slot the whole time.

JSON mode and structured output

When your program, not a person, reads the answer, ask for JSON. Describe the keys in the prompt and switch on JSON mode.

import json

r = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply with a JSON object with keys name, role and secret."},
        {"role": "user", "content": "Invent a character for a heist story."},
    ],
)

try:
    character = json.loads(r.choices[0].message.content)
except json.JSONDecodeError:
    character = None
print(character)

Keep the try block. JSON mode asks for a valid object, but a response that runs out of tokens can still be cut, so do not set max_tokens too tight. Validate the keys you need before using them.

Tool calling in a few lines

Tools use the standard format. The model returns a call, you run it, and you send the output back with role: "tool".

import json

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll a die with the given number of sides",
        "parameters": {
            "type": "object",
            "properties": {"sides": {"type": "integer"}},
            "required": ["sides"],
        },
    },
}]

messages = [{"role": "user", "content": "Roll a 20-sided die for my character."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
msg = first.choices[0].message

if msg.tool_calls:
    call = msg.tool_calls[0]
    sides = json.loads(call.function.arguments)["sides"]
    messages.append(msg)
    messages.append({"role": "tool", "tool_call_id": call.id, "content": "14"})
    final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
    print(final.choices[0].message.content)

In real code you would call a random number function with sides instead of returning a fixed value, and loop until the model stops requesting tools. Parameters such as temperature, top_p, stop, seed and the penalties are passed through, as listed in the documentation.

Errors, retries and async

The SDK raises typed exceptions. The one you will meet first is RateLimitError, which maps to HTTP 429. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. The error code tells you which limit applies: rate_limited for requests per minute, concurrency for too many at once. Temporary overload also returns 429, with a Retry-After: 5 header.

import time
from openai import RateLimitError, APIConnectionError

def chat(messages, tries=4):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError as exc:
            wait = int(exc.response.headers.get("Retry-After", 2 ** attempt))
            time.sleep(wait)
        except APIConnectionError:
            time.sleep(2 ** attempt)
    raise RuntimeError("gave up after retries")

For batches, use the async client with a semaphore so you stay under your concurrency allowance:

import asyncio
from openai import AsyncOpenAI

aclient = AsyncOpenAI(
    base_url="https://api.unrestrictedaichat.com/v1",
    api_key=os.environ["UNRESTRICTED_KEY"],
)
gate = asyncio.Semaphore(6)

async def one(prompt):
    async with gate:
        r = await aclient.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": prompt}],
        )
        return r.choices[0].message.content

async def main():
    prompts = ["Name a pirate.", "Name a smuggler.", "Name a detective."]
    print(await asyncio.gather(*(one(p) for p in prompts)))

asyncio.run(main())

Responses carry X-Request-Id and X-Balance-USD headers. To read them, call the raw variant: raw = client.chat.completions.with_raw_response.create(...), then use raw.headers.get("X-Balance-USD") and raw.parse() to get the usual object. Quote the request ID when you write to support.

A chat loop that remembers

The API keeps no memory between calls, so a chat program stores the history itself and sends it each time. Here is a terminal chat in about twenty lines.

history = [{"role": "system", "content": "You are a witty storyteller who stays in character."}]

while True:
    user = input("you> ").strip()
    if user in ("", "quit"):
        break
    history.append({"role": "user", "content": user})
    stream = client.chat.completions.create(
        model="uncensored", messages=history, stream=True
    )
    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})

Two things will bite you as the chat grows. The first is price: each turn resends everything, so turn 40 costs far more input than turn 1. The second is the window: the model accepts 100,000 tokens of prompt plus completion. A simple policy is to keep the system message and the last 20 turns, and when you cut older turns, replace them with a one-paragraph summary that you ask the model to write. This keeps the character consistent while holding the bill down.

Common mistakes and quick fixes

  • Wrong base URL. It must end in /v1 and must not include /chat/completions. The SDK adds the path itself.
  • Old model name left in place. Code copied from a tutorial often says another model. Replace it with uncensored, or the call fails with a model error.
  • Another provider's key. If OPENAI_API_KEY holds a different service's key and you rely on defaults, you send it to the wrong host. Pass api_key explicitly while you are testing.
  • No timeout. Long generations can take a while. Set timeout=120 on the client, so a stalled connection fails instead of hanging.
  • Unbounded loops. A retry or agent loop with no cap can burn credit quickly. Always set a maximum number of tries.
  • Parsing JSON blindly. Wrap json.loads in a try block and have a fallback.

If a bug is not on this list, check the request ID from the response headers and send it to support with a short description. The docs hold the full parameter list.

What it costs and how to pay

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit with no subscription. Credit never expires, and failed or refused requests are not charged. A script that sends 1,200 input tokens and receives 600 output tokens pays 1,200 / 1,000,000 x $0.15 = $0.00018 for input and 600 / 1,000,000 x $0.50 = $0.0003 for output, so $0.00048 per call. A thousand calls cost $0.48, which fits inside the $0.50 trial credit with a little left over.

Top-ups are by crypto (USDT on TRC20, USDC on Base). Any whole amount from $20 to $500 works, with a +5% bonus from $50, +10% from $100 and +15% from $200. So $100 buys $110 of credit, and $200 buys $230. The pricing page has the details, and if you care about how traffic reaches the model, the guide to the anonymous LLM proxy explains the setup. Prompts are not used for training.

Trial keys are limited to 2 concurrent requests and 60 per minute, so keep the semaphore at 1 or 2 while testing, then raise it after you top up.

Questions and answers

Do I need a special library?

No. The official openai package works. Set base_url to https://api.unrestrictedaichat.com/v1, use your key, and set the model to uncensored.

Does it work with the async client?

Yes. AsyncOpenAI takes the same base_url and api_key arguments. Use a semaphore so you stay within 8 concurrent requests on a full key.

How do I get the usage and balance?

Read response.usage for token counts. The X-Balance-USD header shows your remaining credit, available through with_raw_response.

Which payment methods are accepted?

Crypto only: USDT on TRC20 and USDC on Base, for any whole amount from $20 to $500.

Your key is one form away

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

Get API key