EN ▾
Get API key

Unfiltered AI API in Python: A Working Example

A terminal cube sending a ribbon of light to a network of nodes, illustrating a Python call to a text API

Updated

Use the official openai package, point it at a different base URL, and set the model to uncensored. This guide covers a minimal call, streaming, JSON mode, tools and sane error handling.

Key points

  1. Install openai, set base_url and api_key, use model uncensored. No other change is needed.
  2. Stream with stream=True; a streamed request holds its concurrency slot until the stream ends.
  3. A full key allows 8 concurrent requests and 300 per minute, so cap your async workers at 8.
  4. Handle 429 by reading the error code and waiting before you retry.

The minimal unfiltered AI API Python example

The shortest working version of an unfiltered AI API Python call is ten lines. The service is OpenAI-compatible, so you use the official SDK and change two settings: the base URL and the key.

pip install openai
from openai import OpenAI

client = OpenAI(
    base_url="https://api.unfilteredaiimage.cc/v1",
    api_key="YOUR_KEY",
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Describe a thunderstorm in the voice of a tired sea captain."}],
)

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

That is all. The model ID is uncensored, the key is sent as Authorization: Bearer by the SDK, and the endpoint is POST /v1/chat/completions. The model behind it is one open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. It is not an official endpoint of any model vendor. If you need a key, the API key page shows how to sign up and claim the $0.50 trial.

Two things to know before you build on it. The service is text only, so there is no image, audio or video generation and no embeddings endpoint. And while the model is tuned to skip content refusals for lawful adult use, one rule is fixed: no sexual content involving minors. Prompts are not used for training, which matters if you send drafts or private notes through a script.

Keep the key out of your code

Hard-coding a key works for a first test and is a mistake after that. Read it from an environment variable instead, and keep the base URL in one place.

import os
from openai import OpenAI

client = OpenAI(
    base_url=os.environ.get("LLM_BASE_URL", "https://api.unfilteredaiimage.cc/v1"),
    api_key=os.environ["LLM_API_KEY"],
)
export LLM_API_KEY="YOUR_KEY"
python app.py

The SDK also reads OPENAI_BASE_URL and OPENAI_API_KEY if you construct OpenAI() with no arguments. That is handy for existing projects and for libraries built on the SDK: set the two variables in your shell and the library talks to this API without code changes. To check that the key works before anything else, list the models:

for m in client.models.list():
    print(m.id)

This calls GET /v1/models and should print uncensored.

Streaming responses

For anything longer than a sentence, stream. The first tokens arrive quickly and your interface can show text as it is produced. Set stream=True and iterate. If you want the token counts at the end, ask for them with stream_options; usage is delivered at the end of the stream.

stream = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a blunt, funny writing partner."},
        {"role": "user", "content": "Give me five opening lines for a heist story."},
    ],
    temperature=0.9,
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if getattr(chunk, "usage", None):
        print("\n\nusage:", chunk.usage)

Remember that a streamed request occupies its concurrency slot until the stream finishes. If you open a stream and never read it to the end, that slot stays busy and later requests can fail with concurrency errors. Close streams you abandon, or use the SDK in a with block.

Parameters that pass through

These sampling settings are passed through to the model: temperature, top_p, stop, seed, presence_penalty and frequency_penalty. max_tokens is optional; leave it out and the completion can use the rest of the 100,000-token window, prompt included.

GoalTry
Creative draftingtemperature 0.9, top_p 0.95
Careful rewritingtemperature 0.5
Repeatable test runstemperature 0.2 and a fixed seed
Less repetition in long textpresence_penalty 0.3
Stop at a markerstop=["###"]

These are starting points, not rules. Change one setting at a time and compare outputs on the same prompt. A fixed seed helps when you are debugging a prompt, though you should not treat identical output as guaranteed across every change.

JSON mode and tool calling

JSON mode

When you need structured output, set the response format and say in the prompt that you want JSON. The model is then constrained to return a JSON object.

import json

r = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "user", "content": "Return a JSON object with keys name, flaw and secret "
         "for a fictional smuggler character."},
    ],
    response_format={"type": "json_object"},
)
character = json.loads(r.choices[0].message.content)
print(character["name"])

Tool calling

Define tools, let the model decide when to call them, run the function yourself and send the result back as a role: "tool" message.

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 twenty-sided die for my attack."}]
first = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message

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

Always check that msg.tool_calls is not empty. The model may answer directly instead of calling the function. Details are on the docs page.

A small chat class for multi-turn conversations

The API is stateless. It does not remember earlier requests, so a conversation means you send the earlier messages again each time. A tiny wrapper class keeps this tidy and gives you one place to trim the history.

class Chat:
    def __init__(self, system, keep=20):
        self.system = system
        self.keep = keep
        self.history = []

    def say(self, text):
        self.history.append({"role": "user", "content": text})
        messages = [{"role": "system", "content": self.system}] + self.history[-self.keep:]
        r = client.chat.completions.create(
            model="uncensored", messages=messages, temperature=0.8
        )
        reply = r.choices[0].message.content
        self.history.append({"role": "assistant", "content": reply})
        return reply

bot = Chat("You are the narrator of a grim fantasy adventure for adults.")
print(bot.say("I push open the cellar door."))
print(bot.say("I light a torch and step down."))

Trimming to the last 20 messages keeps each request small. For stories that need long memory, add a summary message at the top of the history instead of sending everything. The context window is 100,000 tokens for prompt plus completion, which is a lot, but every input token is billed on every call, so shorter histories are cheaper.

Common mistakes and quick fixes

  • Wrong base URL. The URL must end in /v1. If you get a 404, check for a missing or doubled path segment.
  • Wrong model name. The only model ID is uncensored. A name copied from another service will not work.
  • 401 errors. The key is missing, mistyped or has a stray space or newline from a copy and paste. Print its length and compare with the key page.
  • Environment variable not set. os.environ["LLM_API_KEY"] raises KeyError in a new shell. Export it again or use a .env loader.
  • Using the old SDK. Examples here use the 1.x interface (client.chat.completions.create). If you see openai.ChatCompletion in your code, upgrade with pip install -U openai.
  • Body too large. The request body is limited to 8 MB. Very long prompts are fine in tokens, but pasting huge files as text can reach the byte limit first.
  • Hung scripts. Set a timeout on the client, for example OpenAI(timeout=120, ...), so a stuck connection does not block a worker forever.

If something still looks wrong, send the X-Request-Id value from the response headers to the support page contact. Quoting that ID lets someone find the exact call.

The same call from Node and curl

Python is not the only option. The same endpoint works from any HTTP client. For a quick check in a terminal:

curl https://api.unfilteredaiimage.cc/v1/chat/completions \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"uncensored","messages":[{"role":"user","content":"Say hello in one line."}]}'

And with the official Node package:

import OpenAI from "openai";

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

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

The only things that change between languages are syntax and the way you read the key. The URL, the model ID and the JSON body stay the same, so a prompt you tuned in Python behaves the same in Node.

Handle 429 and other errors

The API returns HTTP 429 in three situations. Error code rate_limited means you went over the per-minute limit (300 requests on a full key, 60 on a trial key). Error code concurrency means too many requests are in flight (8 on a full key, 2 on a trial key). A 429 with a Retry-After: 5 header means temporary overload: wait and try again.

import time
from openai import OpenAI, RateLimitError, APIConnectionError, APIStatusError

def ask(messages, retries=5):
    delay = 2
    for attempt in range(retries):
        try:
            r = client.chat.completions.create(model="uncensored", messages=messages)
            return r.choices[0].message.content
        except RateLimitError as e:
            wait = e.response.headers.get("Retry-After")
            time.sleep(float(wait) if wait else delay)
            delay = min(delay * 2, 30)
        except APIConnectionError:
            time.sleep(delay)
            delay = min(delay * 2, 30)
        except APIStatusError as e:
            if e.status_code >= 500:
                time.sleep(delay)
                delay = min(delay * 2, 30)
            else:
                raise
    raise RuntimeError("gave up after retries")

The SDK also retries some failures by itself; you can set max_retries on the client. Failed or refused requests are not charged, so a retry loop does not double your bill. The response headers X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency tell you the limits attached to your key, and X-Balance-USD shows the remaining credit. Keep X-Request-Id in your logs for support.

Run many requests in parallel without hitting limits

For batch jobs, such as rewriting a few thousand records, use the async client with a semaphore that matches your concurrency limit. With a full key that is 8; with the trial key use 2.

import asyncio
from openai import AsyncOpenAI

aclient = AsyncOpenAI(
    base_url="https://api.unfilteredaiimage.cc/v1",
    api_key="YOUR_KEY",
)
sem = asyncio.Semaphore(8)

async def rewrite(text):
    async with sem:
        r = await aclient.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": "Rewrite in a darker tone:\n" + text}],
            temperature=0.7,
        )
        return r.choices[0].message.content

async def main(items):
    return await asyncio.gather(*(rewrite(t) for t in items))

results = asyncio.run(main(["The lamp flickered.", "She waited at the door."]))
print(results)

Eight workers is the ceiling for concurrency, but the per-minute cap of 300 can still bite if every request is short. A simple fix is a small sleep between task launches, or a token bucket. Cost stays low either way: at $0.15 and $0.50 per 1M tokens, a rewrite with 500 input and 500 output tokens costs $0.000075 + $0.00025 = $0.000325, so 1,000 rewrites cost $0.325. Pricing and top-ups from $20 are described on the pricing page.

Questions and answers

Do I need a special SDK?

No. The official openai Python package works. Set base_url to the API address, use your key and set the model to uncensored.

Does it support async code?

Yes. Use AsyncOpenAI with the same base URL and key, and limit workers to your concurrency cap of 8 on a full key.

Can I pass a system prompt?

Yes. Messages with role system, user, assistant and tool work as in any chat completions API.

What happens when I hit the rate limit?

You get HTTP 429 with error code rate_limited or concurrency. Wait, honour the Retry-After header if present, and retry.

Your key is one form away

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