EN ▾
Get API key

Unfiltered LLM API in Python: Batch Prompts

You can call an unfiltered LLM API from Python with the standard OpenAI SDK by changing two settings. This walkthrough goes from a single call to a batch runner that respects the rate limits.

Updated

Glowing cable feeding cards into a terminal through parallel lanes, picturing batch prompts in Python

Key points

  1. Install the openai package, set base_url to https://api.unfilteredimagegenerator.com/v1 and use the model ID uncensored.
  2. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60.
  3. Handle HTTP 429 by reading the error code and the Retry-After header, and wait before retrying.
  4. Use JSON mode and the usage field to get parseable output and exact token counts.

Setup in three steps

For an unfiltered llm api python setup you need the OpenAI SDK, a key, and the right base URL. Nothing else is special. The service speaks the OpenAI chat completions format, so the same client library you would use for any compatible endpoint works here.

  1. Install the library with pip install openai. Version 1.x or newer uses the client interface shown below.
  2. Create a key. Sign up with Google, or with email and password, then open the API key page. New users can claim a $0.50 trial credit there with one click; it is valid for 7 days.
  3. Export the key so it stays out of your source: export API_KEY=your-key-here.

Then run a test call:

import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a two-sentence villain monologue."}],
)
print(resp.choices[0].message.content)
print(resp.usage)

If that prints text and a usage object, you are connected. The model ID is uncensored, the endpoints are POST /v1/chat/completions and GET /v1/models, and authentication is a standard Authorization: Bearer header, which the SDK adds for you.

What unfiltered means for your Python code

For the code itself, nothing changes. There is no extra parameter that turns refusals off. The model behind uncensored is one open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. The behavior comes from the model, not from a flag.

Two practical consequences. First, you do not need to write retry-with-rewording logic for refusals, which is a common pattern with other endpoints. Second, you should still validate the output, because a model that does not refuse also does not apologize when it is wrong. And there is one hard limit that no prompt changes: no sexual content involving minors.

This is a text API only. If your batch job is meant to produce prompts for an image generator, the API writes the prompts, and you pass them to your own image tool. It does not generate images, audio, video or embeddings, and it has no fine-tuning.

The context window is 100,000 tokens, counting prompt plus completion, so a batch item can carry a long character sheet or story so far. The completion may use whatever remains of the window, which is why max_tokens is optional. For batch work, set it anyway as a safety cap.

Know your limits before you batch

A batch script fails in predictable ways when it ignores limits, so read these first.

LimitFull keyTrial key
Concurrent requests82
Requests per minute30060
Max request body8 MB8 MB

Going over returns HTTP 429. The error code tells you which limit you hit: rate_limited means too many requests per minute, concurrency means too many at once. The API can also answer 429 on temporary overload, and in that case it sends a Retry-After: 5 header. A streamed request keeps its concurrency slot until the stream ends, so a script that opens eight streams and reads them slowly blocks itself.

Each response includes X-Request-Id, X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency. Log the request ID with every failure; include it whenever you report a problem.

A batch runner with concurrency and retries

Here is a complete script. It reads one idea per line from ideas.txt, asks the model for a detailed image-generation prompt for each, runs several requests in parallel, retries on 429, and writes results to a JSON Lines file. Set CONCURRENCY to 2 on a trial key and up to 8 on a full key.

import asyncio
import json
import os
import random

from openai import AsyncOpenAI, RateLimitError

client = AsyncOpenAI(
    base_url="https://api.unfilteredimagegenerator.com/v1",
    api_key=os.environ["API_KEY"],
    max_retries=0,  # we handle retries ourselves
)

CONCURRENCY = int(os.environ.get("CONCURRENCY", "2"))
SEM = asyncio.Semaphore(CONCURRENCY)
SYSTEM = (
    "Turn the user's idea into one detailed image-generation prompt "
    "of at most 60 words. Reply with the prompt only."
)


async def one(idea, tries=6):
    for attempt in range(tries):
        wait = 0
        async with SEM:
            try:
                r = await client.chat.completions.create(
                    model="uncensored",
                    messages=[
                        {"role": "system", "content": SYSTEM},
                        {"role": "user", "content": idea},
                    ],
                    temperature=0.9,
                    max_tokens=200,
                )
                return {
                    "idea": idea,
                    "prompt": r.choices[0].message.content.strip(),
                    "in": r.usage.prompt_tokens,
                    "out": r.usage.completion_tokens,
                }
            except RateLimitError as e:
                wait = float(e.response.headers.get("Retry-After", 5))
        await asyncio.sleep(wait + random.random() * 2)
    return {"idea": idea, "error": "gave up after retries"}


async def main():
    with open("ideas.txt", encoding="utf-8") as f:
        ideas = [line.strip() for line in f if line.strip()]
    results = await asyncio.gather(*(one(i) for i in ideas))
    with open("prompts.jsonl", "w", encoding="utf-8") as out:
        for row in results:
            out.write(json.dumps(row, ensure_ascii=False) + "\n")
    ok = [r for r in results if "prompt" in r]
    cost = sum(r["in"] * 0.15 + r["out"] * 0.50 for r in ok) / 1_000_000
    print(f"{len(ok)}/{len(results)} done, approx cost ${cost:.4f}")


asyncio.run(main())

Three details matter. The semaphore is released before the sleep, so a waiting task does not hold a slot while it backs off. max_retries=0 turns off the SDK's own retry so you do not stack two retry layers. And the cost line recomputes the bill from the usage counts using $0.15 per 1M input tokens and $0.50 per 1M output tokens, so you can compare it with your real balance.

Getting parseable output with JSON mode

If you want several prompts per request, or fields you can validate, use JSON mode. It makes the reply a JSON object, which saves you from stripping stray text.

import json
import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": 'Reply as JSON: {"prompts": ["...", "...", "..."]}. Give exactly three prompts.'},
        {"role": "user", "content": "a ruined greenhouse at dawn"},
    ],
    temperature=0.8,
)

data = json.loads(resp.choices[0].message.content)
for p in data["prompts"]:
    print("-", p)

Describe the exact shape in the system message, as above. Still wrap json.loads in a try block and handle a bad reply, because a long output that hits max_tokens can be cut off mid-object. Failed requests are not charged, but a reply that arrives with broken JSON still costs its tokens, so log and skip those rows instead of retrying blindly.

Sampling controls such as temperature, top_p, stop, seed and the penalties are passed through to the model. For varied prompts, use a temperature around 0.8 to 1.0. For repeatable runs while you debug, set seed and a low temperature.

Streaming and tool calls from Python

Batch jobs rarely need streaming, but interactive tools do: a chat window or a roleplay front-end feels slow if the reply appears all at once. Pass stream=True and iterate over the chunks. Ask for usage at the end if you track tokens per message.

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Tell a short ghost story set on a night ferry."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
print()

Tool calling follows the OpenAI shape too. You send a tools list and optionally tool_choice, the model replies with tool_calls (also streamed, in pieces), and you answer each call with a message whose role is tool. This is useful when a batch step needs structured lookups, such as pulling a character sheet from your database before the model writes a scene. Keep in mind that every streamed request holds one of your concurrency slots until the last chunk arrives, so a loop that streams and then does slow work between chunks can starve the rest of your pool. If you mix both patterns in one program, give interactive traffic its own small semaphore so a long batch does not crowd it out.

Watching cost and balance

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit with no subscription and no expiry. A request that fails or is refused is not charged. A quick worked example for the runner above: 1,000 ideas, each with 120 input tokens (system message plus idea) and 90 output tokens. Input is 120,000 tokens, which is 0.12M x $0.15 = $0.018. Output is 90,000 tokens, which is 0.09M x $0.50 = $0.045. The total is $0.063. The trial credit of $0.50 would cover that job several times over, as long as you stay within its 2 concurrent and 60 per minute limits.

To read the live balance in code, use the raw response wrapper:

import os
from openai import OpenAI

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

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Say ok."}],
    max_tokens=5,
)
print("balance USD:", raw.headers.get("X-Balance-USD"))
print("request id:", raw.headers.get("X-Request-Id"))
completion = raw.parse()

After the trial, top-ups run from $20 to $500 in any whole amount, with +5% from $50, +10% from $100 and +15% from $200. This site accepts crypto: USDT on TRC20 or USDC on Base. See the pricing page for the current details. There is no free tier beyond the one-time trial.

Common problems and fixes

  • 401 or invalid key. The key is missing or has a typo, or the header is wrong. With the SDK, check that api_key is set and that you did not leave the default OpenAI base URL in place.
  • Connection errors to the wrong host. The base URL must end in /v1 and start with https. The SDK appends /chat/completions itself.
  • 429 with concurrency. Lower CONCURRENCY. A trial key supports only 2 in flight.
  • 429 with rate_limited. You exceeded the per-minute count. Slow the worker pool, or batch several ideas into one request.
  • Cut-off output. Your max_tokens is too low for the task, or the context is too full. Raise the cap or shorten the input.
  • Model not found. Use the exact ID uncensored. You can list models with client.models.list().

For endpoint reference and more examples in other languages, see the API documentation. If you are weighing the service for a larger project, the article on unfiltered text generation explains where it fits and where it does not.

Questions and answers

Do I need a special Python library?

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

How many requests can I run in parallel?

A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 concurrent and 60 per minute. Going over returns HTTP 429.

How do I handle a 429 error in Python?

Catch RateLimitError, read the Retry-After header if present, wait that long plus a little random jitter, and retry. The error code says whether you hit rate_limited or concurrency.

Does streaming work from Python?

Yes. Pass stream=True and iterate over the chunks. Usage is reported at the end of the stream, and the request keeps its concurrency slot until it finishes.

Can this API generate images from my prompts?

No. It is text only. Use it to write the prompts, then send them to your own image tool.

Your key is one form away

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