Flux Uncensored API in Python: Text Workflow Setup
This page shows a flux uncensored api python setup for text: install the openai package, point it at one base URL, and call the model ID uncensored. Streaming, JSON mode, tools and retries are covered.
Updated
Key points
- Install the openai package, set the base URL and your key, and use the model ID uncensored.
- Streaming, tool calling and JSON mode work through the standard chat completions call.
- A full key allows 8 concurrent requests and 300 per minute, so cap your worker pool at 8.
- Handle HTTP 429 by reading the error code and the Retry-After header.

Quick start in under ten lines
If you searched for a flux uncensored api python example, the short version is that nothing special is needed. The service speaks the OpenAI chat format, so the official openai package works once you change two values: the base URL and the key. This is a text API only. It does not return images, so it fits the writing side of a Flux-style workflow, such as expanding prompts, drafting scenes or tagging captions.
Install the package and export your key:
pip install --upgrade openai
export API_KEY="paste-your-key-here"
Then make a first call:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.fluxuncensored.cc/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write two sentences describing a foggy harbour at dawn."}],
)
print(resp.choices[0].message.content)
print(resp.usage)
The model ID is always uncensored. You can list it with GET /v1/models, which is a handy way to confirm that your key and base URL are right before debugging anything else. You need a key first; the API key page explains sign-up and the one-click trial credit.
A word on how this fits a Flux-style pipeline. Image tools take a prompt and return a picture, and the quality of the picture often depends on how well the prompt is written. A Python script can ask the text model for ten variations of a base idea, save them to a file, and hand each one to the image step. Another common use is the reverse: take a caption you already have and ask for tags, a title and a one-line summary. Both are plain chat completion calls, and both are cheap enough to run over thousands of items. The model is tuned to answer without content refusals for lawful adult use, which matters for fiction and roleplay projects where a general assistant may decline or soften a request.
Keep the key and URL in configuration
Hard-coded keys end up in repositories. Read both values from the environment and fail early if one is missing. A small module that builds the client once also stops you creating a new connection pool on every call.
# llm.py
import os
from openai import OpenAI
BASE_URL = os.environ.get("LLM_BASE_URL", "https://api.fluxuncensored.cc/v1")
def make_client() -> OpenAI:
key = os.environ.get("API_KEY")
if not key:
raise RuntimeError("Set API_KEY before running")
return OpenAI(base_url=BASE_URL, api_key=key, timeout=120.0, max_retries=0)
client = make_client()
MODEL = "uncensored"
Setting max_retries=0 hands retry control to you. The SDK retries on its own by default, and that can hide rate limit problems while quietly consuming your per-minute budget. We will add explicit retries below.
Streaming replies
For anything a person watches, such as a chat window or a story generator, stream the reply. Set stream=True and iterate over the chunks. The response uses server-sent events, and token usage arrives at the end of the stream.
from llm import client, MODEL
stream = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Outline a short mystery in five beats."}],
stream=True,
)
parts = []
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
parts.append(piece)
print(piece, end="", flush=True)
usage = getattr(chunk, "usage", None)
print()
print("usage:", usage)
Two details matter here. First, always close or fully consume a stream. A streamed request holds its concurrency slot until the stream ends, so a half-read stream in a loop will eventually block your own new requests. Second, the last chunk may have an empty choices list, which is why the code checks it before indexing.
JSON mode for pipelines
When another script consumes the output, ask for JSON. Pass response_format={"type": "json_object"} and say in the prompt what shape you want. The prompt matters as much as the flag.
import json
from llm import client, MODEL
resp = client.chat.completions.create(
model=MODEL,
response_format={"type": "json_object"},
temperature=0.8,
messages=[
{"role": "system", "content": 'Reply only with JSON: {"variations": [{"title": str, "description": str}]}'},
{"role": "user", "content": "Three scene ideas for a rainy night market. Keep each description under 40 words."},
],
)
data = json.loads(resp.choices[0].message.content)
for item in data["variations"]:
print(item["title"], "-", item["description"])
Wrap json.loads in a try block in real code and retry once on a parse error. If a reply is cut off because it reached the end of the context window, the JSON will be incomplete, so check finish_reason as well. Sampling controls such as temperature, top_p, stop, seed and the penalties are passed through to the model. A fixed seed with a low temperature gives you more repeatable output for tests.
Tool calling
Tool calling follows the OpenAI shape: you describe functions in tools, the model returns tool_calls, you run them, and you send the results back as messages with role: "tool". Streamed tool_calls are supported too.
import json
from llm import client, MODEL
tools = [{
"type": "function",
"function": {
"name": "save_prompt",
"description": "Store a finished image prompt",
"parameters": {
"type": "object",
"properties": {
"text": {"type": "string"},
"aspect": {"type": "string", "enum": ["square", "wide", "tall"]},
},
"required": ["text", "aspect"],
},
},
}]
messages = [{"role": "user", "content": "Write one prompt for a lighthouse in a storm and save it as wide."}]
first = client.chat.completions.create(model=MODEL, 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)
print("saving:", args)
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps({"ok": True})})
final = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
print(final.choices[0].message.content)
Always validate the arguments before you act on them. The model proposes a call, and your code decides whether to run it. The docs page lists the full set of supported fields.
Multi-turn chat and async use
The API holds no conversation state. For a chat, keep a list of messages in your own code and send the whole list each time, appending the assistant reply after every call. That list is also your cost driver, because input tokens are billed on every request. A simple rule is to keep the system message, the last ten or so turns, and a short summary of anything older.
If your program already runs an event loop, such as a web server or a Discord bot, use AsyncOpenAI in place of the blocking client. The constructor takes the same base_url and api_key arguments, and calls are awaited. Put an asyncio.Semaphore(8) around the call so that bursts of user messages queue inside your process and never reach the concurrency limit. Streaming works the same way, with async for over the stream.
One more habit saves time: call client.models.list() at startup. If it succeeds, the base URL and key are correct. If it raises an authentication error, you find out before the first user does. Tests should use a short prompt, a low max_tokens and a fixed seed, so each run costs a fraction of a cent and gives comparable output.
Limits, 429 errors and retries
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. The request body can be up to 8 MB, and the context window is 100,000 tokens covering prompt plus completion. Over a limit the API answers HTTP 429. The error code tells you which limit you hit:
rate_limited: too many requests in the last minute.concurrency: too many requests running at once.- A 429 with a
Retry-After: 5header means temporary overload. Wait that long and try again.
Here is a retry helper and a worker pool sized to the concurrency limit:
import time
from concurrent.futures import ThreadPoolExecutor
from openai import RateLimitError
from llm import client, MODEL
def ask(prompt: str, tries: int = 5) -> str:
for attempt in range(tries):
try:
r = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError as e:
wait = 5
retry_after = getattr(e.response, "headers", {}).get("retry-after")
if retry_after:
wait = float(retry_after)
time.sleep(wait * (attempt + 1))
raise RuntimeError("still rate limited")
prompts = [f"Describe scene number {i} of a train station at night." for i in range(40)]
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(ask, prompts))
print(len(results), "done")
Keeping max_workers at 8 or below stops you from hitting the concurrency limit yourself. Responses carry X-Request-Id, X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency. Log the request ID with every error, because it is the first thing support will ask for. To read headers in the SDK, call client.chat.completions.with_raw_response.create(...) and use .headers.
Cost and common pitfalls
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, paid from prepaid credit with no subscription. Failed or refused requests are not charged. A request with 1,200 input tokens and 400 output tokens costs 1,200 x $0.15 / 1,000,000 = $0.00018 for input plus 400 x $0.50 / 1,000,000 = $0.0002 for output, so $0.00038 in total. Forty of those cost $0.0152. The pricing page covers top-ups and bonuses.
Common problems in Python projects:
- 401 errors. The key is missing or has a stray space or newline. Print its length, not its value.
- 404 errors. The base URL is missing
/v1, or the model name is misspelt. Useuncensoredexactly. - Slow loops. Sequential calls waste the 8 slots you have. Use the thread pool above or
AsyncOpenAIwith a semaphore of 8. - Growing bills in chat apps. You resend the whole history on every turn. Trim old messages or summarise them.
Prompts are not used for training, and the one hard content rule is no sexual content involving minors.
Finally, log token usage per call from the start. Read resp.usage.prompt_tokens and resp.usage.completion_tokens, add them to a running total, and write the total at the end of each batch run. Spotting a prompt that is ten times longer than expected is far easier from a log line than from a balance that dropped overnight.
More guides
Questions and answers
Do I need a special Python library?
No. The standard openai package works. Set base_url to the API address, pass your key, and use the model ID uncensored.
Can I use async code?
Yes. Use AsyncOpenAI with the same base_url and key, and limit concurrency to 8 with a semaphore so you stay inside the full-key limit.
Does this API generate images?
No. It is text only. It suits prompt writing, captions, scene outlines and structured data, not image, audio or video generation.
What happens if I hit a rate limit?
You get HTTP 429 with the code rate_limited or concurrency. Wait, then retry, and honour the Retry-After header when it is present.
How do I try it without paying?
Sign up, then claim the $0.50 trial credit with one click on the API key page. It needs no card and is valid for 7 days, with limits of 2 concurrent requests and 60 per minute.
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.
$0.15per 1M input tokens
$0.50Output tokens / 1M
100,000token context
$0.50trial credit
300requests per minute