EN ▾
Get API key

NSFW API Python Tutorial: Chat, Stream, Tools

You can call this uncensored LLM from Python with the standard openai package and two changed values. The examples below go from a first request to streaming, JSON output, tools and safe retries.

Updated

Terminal emitting a stream of speech bubbles, illustrating calling an LLM API from Python code

Setup in four lines

For an NSFW API Python project, you do not need a special library. The service is OpenAI-compatible, so the official openai package works as it is. Install it, put your key in an environment variable, and create a client with the right base URL.

pip install openai
export NSFWHUB_KEY="paste-your-key-here"
import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You write mature fiction for adult readers."},
        {"role": "user", "content": "Open a noir scene in a rain-soaked harbour bar."},
    ],
)
print(resp.choices[0].message.content)
print(resp.usage)

If you do not have a key yet, the key page shows how to sign up with Google or with email and password, and how to claim the $0.50 trial credit with one click. The trial needs no payment, lasts 7 days and is limited to one per person.

The model is one open-weight text model run by an independent provider, tuned to answer without content refusals for lawful adult use. It is not the official API of any model vendor. The rule against sexual content involving minors cannot be changed by any prompt.

What the response gives you

The returned object is the usual chat completion. resp.choices[0].message.content holds the text and resp.usage holds token counts for prompt and completion. If you want the raw headers as well, the SDK can hand them to you:

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Say hi in five words."}],
)
print(raw.headers.get("x-request-id"))
print(raw.headers.get("x-balance-usd"))
resp = raw.parse()
print(resp.choices[0].message.content)

The headers worth logging are X-Request-Id for tracing a single call, X-Balance-USD for the remaining credit, and the two X-RateLimit-Limit-* headers that report the limits on your key. A script that checks the balance header after each call can stop itself before the credit runs out.

Sampling controls are passed through, so temperature, top_p, stop, seed, frequency_penalty and presence_penalty all behave as you expect. For repeatable tests while you tune a prompt, fix seed and temperature and change one thing at a time.

Streaming replies

Bots and chat windows should stream, because a long answer then appears word by word instead of after a pause. Pass stream=True and iterate. Usage arrives at the end of the stream, so guard against chunks with no choices and read the counts from the last one.

def stream_reply(messages):
    text = []
    stream = client.chat.completions.create(
        model="uncensored",
        messages=messages,
        stream=True,
    )
    try:
        for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                piece = chunk.choices[0].delta.content
                text.append(piece)
                print(piece, end="", flush=True)
            if getattr(chunk, "usage", None):
                print("\n[tokens]", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
    finally:
        stream.close()
    return "".join(text)

The finally block matters. A streamed request holds one of your concurrency slots until the stream ends, so a loop that exits early and leaves the stream open will quietly use up slots and later calls will fail with the concurrency error.

A small chat loop with memory

The API is stateless, so the conversation lives in your list. Append each user message and each reply, and send the whole list every turn. That is also why long chats cost more over time: the full history is billed as input on each call.

history = [{"role": "system", "content": "You are a dry-witted narrator for an adult interactive story."}]

while True:
    user = input("> ")
    if user.strip().lower() in {"quit", "exit"}:
        break
    history.append({"role": "user", "content": user})
    reply = stream_reply(history)
    history.append({"role": "assistant", "content": reply})
    print()

    # keep the system prompt plus the last 20 messages
    if len(history) > 21:
        history = history[:1] + history[-20:]

Trimming by message count is the simplest approach. For stories that need long-range memory, ask the model to summarise the oldest turns into a paragraph and keep that paragraph as a second system message. The context window is 100,000 tokens for prompt plus completion, so you have room, but cost and focus both improve when the prompt stays lean. The page on NSFW chat and roleplay covers prompt design for that kind of app.

JSON mode and tool calls

For structured output, set response_format to a JSON object and say in the prompt what shape you want. Always parse inside a try block.

import json

r = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply only with JSON: {\"name\": str, \"traits\": [str], \"hook\": str}"},
        {"role": "user", "content": "Create a morally grey smuggler character for an adult fantasy novel."},
    ],
)
try:
    character = json.loads(r.choices[0].message.content)
except json.JSONDecodeError:
    character = None  # retry or log the raw text

Tool calling follows the standard shape. You describe the function, the model asks for it, you run it, and you return the result with role: "tool".

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 lockpicking attempt."}]
first = client.chat.completions.create(
    model="uncensored", 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:
        args = json.loads(call.function.arguments)
        result = {"roll": 14, "sides": args["sides"]}  # replace with real logic
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })
    final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
    print(final.choices[0].message.content)

How often the model chooses to call a tool depends on the model, so test with your real schemas and keep descriptions short and specific.

Retries and parallel requests

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Over a limit you get HTTP 429 with the code rate_limited or concurrency, and on temporary overload you get a 429 with Retry-After: 5. The SDK already retries some failures, and you can turn the count up when you create the client. If you prefer explicit control, wrap the call yourself:

import random
import time
from openai import RateLimitError

def ask(messages, tries=5):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError as e:
            wait = float(e.response.headers.get("retry-after", 5))
            time.sleep(wait + random.random())
    raise RuntimeError("still rate limited after retries")

Failed and refused requests are not charged, so retries cost nothing extra. To process a batch, cap your worker count at the concurrency limit:

from concurrent.futures import ThreadPoolExecutor

prompts = [f"Write a one-line tagline for story idea number {i}." for i in range(40)]

def run(p):
    r = ask([{"role": "user", "content": p}])
    return r.choices[0].message.content

with ThreadPoolExecutor(max_workers=8) as pool:
    results = list(pool.map(run, prompts))

Threads are enough for most scripts, because the work is waiting on the network. Keep the pool at or below the concurrency limit and you will rarely see a 429 at all. If you do see them in bursts, the cause is usually the per-minute cap rather than concurrency: 300 requests per minute is five per second, so a pool of 8 fast workers on short prompts can outrun it. Add a small sleep between submissions, or let the retry wrapper absorb the occasional rejection. Also write results to disk as they arrive. A long batch that dies at item 900 should not force you to repeat the first 899.

On a trial key, set max_workers=2. The request body limit is 8 MB, which only matters if you paste very large documents into the prompt.

Async code and testing

If your bot or web service is already async, use AsyncOpenAI. It takes the same arguments and the same model name, and the calls are awaited. Limit the number of tasks in flight with a semaphore so you never go above the concurrency allowance of your key.

import asyncio
from openai import AsyncOpenAI

aclient = AsyncOpenAI(
    base_url="https://api.nsfwapihub.com/v1",
    api_key=os.environ["NSFWHUB_KEY"],
)
gate = asyncio.Semaphore(8)

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

async def main():
    outs = await asyncio.gather(*(one(f"Name a ship, idea {i}.") for i in range(20)))
    print(len(outs), "done")

asyncio.run(main())

A few testing habits save time. First, run a single prompt with a fixed seed before you scale up, so you know what normal output looks like. Second, cap max_tokens during development; without it a reply can use the rest of the context window, which wastes credit when a prompt goes wrong. Third, log the request id and the first 200 characters of every reply, so a bad output can be traced later. Fourth, keep prompts in files or constants rather than f-strings buried in loops, because small wording changes alter the style of the output and you will want to compare versions.

When something fails and the cause is not obvious, print the status code and the error body before anything else. A rate-limit error, an overload error and an input error each call for a different response, and the body says which one you have. If the problem is on the service side, send the request id to support.

Cost of a Python script

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, prepaid, with no subscription. Suppose the batch above sends 40 prompts of about 60 tokens each and gets about 30 tokens back. Input is 40 x 60 = 2,400 tokens, which costs 2,400 x $0.15 / 1M = $0.00036. Output is 40 x 30 = 1,200 tokens, which costs 1,200 x $0.50 / 1M = $0.0006. The whole batch is $0.00096, under a tenth of a cent.

A heavier job: 5,000 requests with 4,000 input tokens and 800 output tokens each. Input totals 20M tokens, costing 20 x $0.15 = $3.00. Output totals 4M tokens, costing 4 x $0.50 = $2.00. The job costs $5.00.

This site takes crypto only, with USDT on TRC20 or USDC on Base. Top-ups run from $20 to $500 in whole amounts, with +5% from $50, +10% from $100 and +15% from $200. Credit never expires. Details are on the pricing page, and the full endpoint reference is in the docs.

Prompts are not used for training. The service is text only, so there are no images, audio, embeddings or fine-tuning, and the Python code above is everything you need to start.

Questions and answers

Do I need a special Python library?

No. Install the official openai package and set base_url to https://api.nsfwapihub.com/v1 with your own key and the model uncensored.

Does the Python SDK retry on 429 errors?

The SDK retries some failures automatically, and you can raise the retry count on the client. For control over waiting, catch RateLimitError and honour the Retry-After header.

Can I use async Python?

Yes. The AsyncOpenAI client takes the same base_url and api_key arguments. Keep the number of simultaneous tasks at or below 8 on a full key.

How do I try it for free?

Claim the $0.50 trial credit with one click on the API key page after sign-up. It lasts 7 days, needs no payment and is one per person.

Your key is one form away

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

Get API key