EN ▾

Uncensored text AI for developers

Get API key

Fluxnsfw API in Python: Text Prompts Example

The text API on fluxnsfw.cc speaks the OpenAI protocol, so the standard openai Python package works after you change two values. This page walks through a first call, streaming, JSON mode, tool calling and error handling.

Updated

Abstract terminal with flowing code feeding a chat bubble, illustrating a Python call to a text API

Key points

  • Install the openai package, set base_url to https://api.fluxnsfw.cc/v1 and use the model ID uncensored.
  • Streaming, JSON mode and tool calling use the same parameters as the OpenAI API.
  • Limits are 8 concurrent requests and 300 per minute on a full key; handle HTTP 429 with a retry.
  • A 1,000-token prompt with a 500-token reply costs $0.0004.

Setup in four lines

This is a fluxnsfw api python walkthrough for the text side of an image workflow: you send a short brief, and the model sends back a finished prompt or a structured list of them. Image generation itself happens elsewhere, since this API only produces text.

The service follows the OpenAI chat completions format. You need the official package, a key from the API key page, and three values: the base URL https://api.fluxnsfw.cc/v1, the model ID uncensored, and your key sent as a bearer token.

pip install openai
export FLUXNSFW_API_KEY="paste-your-key-here"

Keep the key in an environment variable and never commit it to a repository. The SDK adds the Authorization: Bearer header for you.

Your first request

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.fluxnsfw.cc/v1",
    api_key=os.environ["FLUXNSFW_API_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You write detailed image prompts for adult fiction art. Reply with the prompt only."},
        {"role": "user", "content": "A lighthouse keeper's cabin in a storm, painterly style."},
    ],
    temperature=0.8,
    max_tokens=300,
)

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

Only two endpoints exist: POST /v1/chat/completions for generation and GET /v1/models to list models. Calling client.models.list() is a quick way to confirm that your key and base URL are right before you write anything bigger.

The usage object tells you what a call cost. With $0.15 per 1M input tokens and $0.50 per 1M output tokens, a request with 1,000 input and 500 output tokens costs $0.00015 plus $0.00025, which is $0.0004. So 2,500 such calls cost $1.00.

Sampling parameters that pass through

temperature, top_p, stop, seed and the presence and frequency penalties are passed through to the model. For prompt writing, a temperature around 0.7 to 1.0 gives varied wording, while a lower value suits rewrites where you want the same content with cleaner phrasing. Setting seed helps when you want to compare two system prompts without sampling noise getting in the way.

You do not have to set max_tokens. Without it the reply can use the rest of the 100,000-token window, which is shared between your prompt and the completion. For short outputs, a cap is still a cheap safety net.

Streaming replies

Set stream=True and the API sends server-sent events. Usage figures arrive at the end of the stream.

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Give me three short moods for a foggy harbor scene."}],
    stream=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("\nTokens:", chunk.usage.total_tokens)

One detail matters for concurrency. A streamed request keeps its slot until the stream finishes, so if you abandon a stream half-read without closing it, that slot stays busy. Use the stream as a context manager or finish the loop.

JSON mode for lists of prompts

When a script needs structured output, ask for a JSON object. Describe the shape in the message as well, because JSON mode guarantees valid JSON syntax but not your field names.

import json

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": 'Return JSON like {"prompts": [{"title": "...", "text": "..."}]}.'},
        {"role": "user", "content": "Four prompt variants for a neon rooftop at night, adult noir fiction."},
    ],
)

data = json.loads(resp.choices[0].message.content)
for item in data["prompts"]:
    print(item["title"], "|", item["text"])

Wrap the json.loads call in a try block. If a reply is cut off by a low max_tokens, the JSON will be incomplete, and a retry with a higher cap fixes it.

Tool calling

Tools work as they do in the OpenAI API: pass tools and optionally tool_choice, read tool_calls from the reply, run your function, and send the result back as a message with role: "tool".

tools = [{
    "type": "function",
    "function": {
        "name": "save_prompt",
        "description": "Store a finished image prompt.",
        "parameters": {
            "type": "object",
            "properties": {"text": {"type": "string"}, "tags": {"type": "array", "items": {"type": "string"}}},
            "required": ["text"],
        },
    },
}]

messages = [{"role": "user", "content": "Write one prompt for a desert market at dusk and save it."}]
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]
    print("Saved:", call.function.arguments)
    messages.append(msg)
    messages.append({"role": "tool", "tool_call_id": call.id, "content": "ok"})
    final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
    print(final.choices[0].message.content)

Tool calls can also be streamed, with arguments arriving in pieces that you join before parsing. Models differ in how reliably they call tools, so test your schema on a few real inputs.

Running a batch with a thread pool

Prompt generation is often a loop over a few hundred ideas. Running them one by one is slow, and running too many at once triggers the concurrency limit. A small thread pool sized to your key is the practical middle.

from concurrent.futures import ThreadPoolExecutor

ideas = ["foggy harbor at dawn", "neon rooftop in rain", "desert market at dusk", "greenhouse after midnight"]

def make_prompt(idea):
    r = client.chat.completions.create(
        model="uncensored",
        messages=[
            {"role": "system", "content": "Write one detailed image prompt. Reply with the prompt only."},
            {"role": "user", "content": idea},
        ],
        max_tokens=200,
    )
    return idea, r.choices[0].message.content

with ThreadPoolExecutor(max_workers=6) as pool:
    for idea, text in pool.map(make_prompt, ideas):
        print(idea, "=>", text[:70])

Six workers leave a little headroom under the full-key limit of 8 concurrent requests. On a trial key, use 2. Spend scales linearly, so 400 prompts at the $0.0004 per call from the earlier example come to $0.16. Run ten first, read the usage numbers, and only then launch the full list.

One more habit pays off: write each result to disk as it arrives. If a long batch dies at item 300, you keep the first 299 and restart from there rather than paying for them twice.

Troubleshooting the common failures

  • 401 Unauthorized. The key is missing, mistyped or has a stray space or newline. Print its length, and check that the environment variable is set in the shell that runs the script.
  • 404 or a connection error. The base URL is wrong. It must end in /v1, and the SDK appends /chat/completions itself. Do not add that path twice.
  • Model not found. The model value must be exactly uncensored, in lowercase.
  • Empty or short replies. Check finish_reason. A value of length means max_tokens cut the reply, so raise the cap or remove it.
  • Request too large. The body limit is 8 MB. That is far more than text needs, but pasting a huge file into a prompt can hit it before the 100,000-token window does.
  • Slow first token on long prompts. A very long input takes longer to process. Trim history you do not need.

If a call fails and the cause is not obvious, keep the value of the X-Request-Id header and send it to the support page contact along with the time of the call.

Rate limits and error handling

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Going over returns HTTP 429, with the error code rate_limited for the per-minute cap or concurrency for too many requests at once. During temporary overload the API also answers 429 with a Retry-After: 5 header. The openai package retries a couple of times by default, and you can raise it.

import time
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.fluxnsfw.cc/v1",
    api_key=os.environ["FLUXNSFW_API_KEY"],
    max_retries=0,
)

def ask(text, tries=4):
    for attempt in range(tries):
        try:
            raw = client.chat.completions.with_raw_response.create(
                model="uncensored",
                messages=[{"role": "user", "content": text}],
            )
            print("Balance:", raw.headers.get("X-Balance-USD"), "Request:", raw.headers.get("X-Request-Id"))
            return raw.parse().choices[0].message.content
        except RateLimitError as err:
            wait = int(err.response.headers.get("Retry-After", 5))
            time.sleep(wait)
    raise RuntimeError("still rate limited")

Responses carry X-Request-Id, X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency. Log the request ID so support can trace a specific call. When running a batch, use a thread pool with at most 8 workers on a full key, or 2 on a trial key. Failed or refused requests are not charged, which keeps retries cheap.

The docs list the same limits and the full parameter set, and the pricing page shows top-up amounts if your balance runs low. New accounts can claim a $0.50 trial credit on the key page, which is plenty for every example here.

Questions and answers

Which model ID do I use?

Use uncensored as the model value. It is the only model, and GET /v1/models lists it.

Can I use the openai package without changes?

Yes. Set base_url to https://api.fluxnsfw.cc/v1 and pass your key as api_key. Streaming, JSON mode and tools use the usual parameters.

Does this API generate images?

No. It is text only, so it suits prompt drafting, rewriting and structuring, with image generation handled by another tool.

What do I do on a 429 error?

Wait and retry. Check the error code: rate_limited means too many requests per minute, and concurrency means too many at once. Respect Retry-After when present.

Is my data used for training?

No. Prompts are not used for training.

Your key is one form away

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

Start with trial credit

Email and password, key on screen right away.