EN ▾
Get API key

Uncensored Chat API in Python: Quick Start

You need the OpenAI Python SDK, a base URL and a key. Point the client at the endpoint, set the model to uncensored, and your existing chat code runs as it is.

Terminal streaming light ribbons into a chat bubble beside a coiled snake of light, representing a Python chat API

Updated

Key points

  • Install the openai package and change only base_url, api_key and the model name.
  • Streaming, JSON mode, tool calling and seed are supported through the normal SDK arguments.
  • Full keys allow 8 concurrent requests and 300 per minute, so cap your own concurrency.
  • Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, prepaid.

The short version

If you are looking for an uncensored chat api python setup, the work is smaller than it sounds. The service speaks the OpenAI chat completions protocol, so the official openai package already knows how to talk to it. You change three values: the base URL, the key and the model name. This is the whole program:

from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Describe a rainy harbor at night in three sentences."}],
)
print(resp.choices[0].message.content)

The model behind uncensored is a single open-weight model run by an independent provider and tuned to answer without content refusals for lawful adult use. It is not the official API of any model vendor and it is not a router. One hard limit applies: no sexual content involving minors, and requests that ask for it are not served.

The service is text only. There is no image, audio or video generation, no embeddings and no fine-tuning. The rest of this page covers the details that tend to bite in real code: streaming, structured output, tools, rate limits and long conversations.

Get a key and install the SDK

Setup is four steps.

  1. Create an account with Google, or with an email and password.
  2. Open the API key page. New users can claim $0.50 of trial credit there with one click, one per person. It needs no card and stays valid for 7 days.
  3. Copy the key into an environment variable instead of pasting it into source files.
  4. Install the SDK in a virtual environment.
python -m venv .venv
source .venv/bin/activate
pip install openai
export WAN_API_KEY="paste-your-key-here"

The trial key is limited to 2 concurrent requests and 60 requests per minute, which is plenty for testing a script. A full key, which you get after a top-up, allows 8 concurrent requests and 300 per minute. The API key page explains how to claim the trial, and the quickstart in the docs lists the endpoints. There are two: POST /v1/chat/completions and GET /v1/models.

Read the key from the environment in code, and keep the client in one module so every script shares the same settings:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.wanuncensored.com/v1",
    api_key=os.environ["WAN_API_KEY"],
)
MODEL = "uncensored"

print([m.id for m in client.models.list().data])

The last line calls GET /v1/models. It is a cheap way to confirm that the key and the URL are right before you debug anything else. A 401 means the key is wrong. A connection error usually means the base URL is missing the /v1 suffix.

Stream the reply token by token

For chat interfaces and long outputs, set stream=True. The server sends Server-Sent Events, and the SDK turns them into an iterator. Token usage arrives at the end of the stream, so you can log what a request cost without counting yourself.

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a blunt, concise writing partner."},
        {"role": "user", "content": "Write the opening paragraph of a noir story set on a ferry."},
    ],
    stream=True,
)

usage = None
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):
        usage = chunk.usage
print()
if usage:
    print("in:", usage.prompt_tokens, "out:", usage.completion_tokens)

One detail matters for throughput planning. A streamed request holds its concurrency slot until the stream ends. If your program opens eight streams and leaves two of them half-read, you are at the cap even though nothing is being generated. Always consume the iterator to the end or close it.

Parameters that pass through

Sampling settings go to the model unchanged, so what you know from other OpenAI-compatible endpoints applies. Here is how the common ones behave in practice.

ParameterUse it for
temperature0.2 to 0.5 for extraction and rewriting, 0.8 to 1.1 for fiction and brainstorming.
top_pTrim the unlikely tail. Change this or temperature, rarely both at once.
seedRepeatable test runs while you tune a prompt.
stopCut generation at a marker such as a closing tag or a speaker label.
presence and frequency penaltiesReduce loops in long creative output.
max_tokensOptional. Without it, the completion can use whatever is left of the 100,000-token window.

Because the window of 100,000 tokens covers the prompt plus the completion, a 90,000-token prompt leaves room for roughly 10,000 tokens of answer. Set max_tokens when you want a hard ceiling on cost per call, not because the API requires it.

JSON mode and tool calling

Structured output is where Python scripts usually get brittle, so use the built-in modes. JSON mode is enabled with response_format. Mention JSON in your prompt as well, and describe the keys you expect.

import json, os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply with JSON only: keys title, mood, tags (list of strings)."},
        {"role": "user", "content": "A lighthouse keeper finds a message in a bottle."},
    ],
    temperature=0.4,
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])

Tool calling follows the standard shape: pass tools, optionally tool_choice, read tool_calls from the reply, run your function and send the result back as a message with role: "tool". Tool calls also stream.

import json, os
from openai import OpenAI

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

tools = [{
    "type": "function",
    "function": {
        "name": "get_word_count",
        "description": "Count the words in a text",
        "parameters": {
            "type": "object",
            "properties": {"text": {"type": "string"}},
            "required": ["text"],
        },
    },
}]

messages = [{"role": "user", "content": "How many words are in: the tide came in slowly"}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)

messages.append(first.choices[0].message)
messages.append({
    "role": "tool",
    "tool_call_id": call.id,
    "content": str(len(args["text"].split())),
})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)

Parse tool arguments defensively. The model returns them as a string, and an open-weight model will occasionally produce malformed JSON. Wrap json.loads in a try block and, on failure, send the error back as the tool result so the model can correct itself.

Rate limits, 429 and concurrency

The limits are simple. A full key gets 300 requests per minute and 8 at once. A trial key gets 60 per minute and 2 at once. The request body can be up to 8 MB. Every response carries X-Request-Id, X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency, which is handy for logging and for a quick balance check without opening the dashboard.

Going over returns HTTP 429. The error code tells you which limit you hit: rate_limited for requests per minute and concurrency for too many requests in flight. A 429 can also mean temporary overload, in which case the response includes Retry-After: 5. Failed or refused requests are not charged, so retrying costs nothing extra.

For batch jobs, an asyncio semaphore keeps you under the concurrency cap with no tuning:

import asyncio, os
from openai import AsyncOpenAI, RateLimitError

client = AsyncOpenAI(base_url="https://api.wanuncensored.com/v1", api_key=os.environ["WAN_API_KEY"])
sem = asyncio.Semaphore(6)  # stay below the 8-request cap

async def ask(prompt: str) -> str:
    async with sem:
        for attempt in range(5):
            try:
                r = await client.chat.completions.create(
                    model="uncensored",
                    messages=[{"role": "user", "content": prompt}],
                    max_tokens=300,
                )
                return r.choices[0].message.content
            except RateLimitError as e:
                wait = float(e.response.headers.get("retry-after", 5))
                await asyncio.sleep(wait * (attempt + 1))
    raise RuntimeError("gave up after 5 attempts")

async def main():
    prompts = [f"Give me one image caption idea, variation {i}." for i in range(20)]
    results = await asyncio.gather(*(ask(p) for p in prompts))
    print(len(results), "done")

asyncio.run(main())

Six slots instead of eight leaves headroom for a second script running against the same key. The SDK also has its own automatic retries, so keep the loop modest rather than stacking long waits on top.

A small pipeline: prompts for a Wan workflow

This site is written for people who run Wan video generation and need a text model next to it. The text side can draft scene descriptions, expand a one-line idea into a detailed shot prompt, or rewrite a prompt that a filtered model refused. The video generation itself happens in your own tools. The API only returns text.

import os
from openai import OpenAI

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

SYSTEM = (
    "You write shot descriptions for a video generator. "
    "Output one paragraph: subject, setting, camera movement, lighting, mood. "
    "No dialogue, no on-screen text."
)

def shot_prompt(idea: str) -> str:
    r = client.chat.completions.create(
        model="uncensored",
        messages=[{"role": "system", "content": SYSTEM},
                  {"role": "user", "content": idea}],
        temperature=0.9,
        max_tokens=250,
    )
    return r.choices[0].message.content.strip()

print(shot_prompt("a fishing boat returning at dawn, slow dolly shot"))

Each call like this uses a few hundred tokens, which is a tiny fraction of a cent at the listed rates. The pricing page has the full breakdown, and the comparison in Seedance versus text models is useful if you are weighing where your budget goes in a video pipeline.

Keep long chats inside the 100k window

The context window is 100,000 tokens for the prompt and completion together. A chat loop that appends every turn will hit that limit eventually, and a long prompt also costs more on every later call because the whole history is billed as input each time.

A simple policy works well. Keep the system message, keep the last N turns verbatim, and replace older turns with a short summary that you ask the model to write. Use the prompt_tokens figure from the last response as your gauge, not a local estimate. When it passes about 70,000, compress. That leaves around 30,000 tokens for the next completion and for growth.

import os
from openai import OpenAI

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

def compress(history):
    old, recent = history[1:-6], history[-6:]
    if not old:
        return history
    text = "\n".join(f"{m['role']}: {m['content']}" for m in old)
    s = client.chat.completions.create(
        model="uncensored",
        messages=[{"role": "user", "content": "Summarize this conversation in under 300 words, keeping names and facts:\n" + text}],
        temperature=0.3,
    ).choices[0].message.content
    return [history[0], {"role": "system", "content": "Earlier summary: " + s}] + recent

Prompts are not used for training. Even so, keep real personal data out of test conversations, as you would with any hosted service. The privacy page has the policy text.

Troubleshooting checklist

  • 401 error: the key is missing or has a stray space. Print its length, never the key itself.
  • 404 or HTML back: the base URL is missing /v1.
  • Model not found: the model ID is uncensored, in lowercase, exactly.
  • 429 with code concurrency: too many requests in flight. Lower your semaphore or finish your streams.
  • Empty or short answers: check max_tokens, and check whether a stop sequence fired early.
  • Balance questions: read the X-Balance-USD header, or top up from $20 to $500 on the pricing page.

If something still looks wrong, send the X-Request-Id value from the failing response to the support page. That one string makes the request easy to find.

Questions and answers

Do I need a special Python library?

No. The official openai package works. Set base_url to the endpoint, pass your key and use model uncensored. Any other OpenAI-compatible client does the same.

Does it support streaming in Python?

Yes. Pass stream=True and iterate over the chunks. Usage is sent at the end of the stream, and the request holds a concurrency slot until the stream finishes.

Is there a free tier?

There is no permanent free tier. New users can claim $0.50 of trial credit with one click, valid for 7 days, with no card needed. After that you pay as you go from prepaid credit.

What happens if I hit a rate limit?

You get HTTP 429 with the code rate_limited or concurrency. Wait and retry, using the Retry-After header when present. Rejected requests are not charged.

Can I use it for anything?

It is meant for lawful adult use and answers without the usual content refusals. Sexual content involving minors is never allowed.

Your key is one form away

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

Get API key