Install and make the first call
You need Python 3.8 or newer and the official OpenAI package. Install it with pip install openai, create an API key on the API key page, and keep the key in an environment variable instead of in source code. On macOS or Linux that is export UNCENSORED_API_KEY="your-key".
This is not OpenAI's service. It is a separate, OpenAI-compatible endpoint that serves one open-weight model, so the SDK works unchanged as long as you swap the base URL and key. Here is the smallest useful script:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unfilteredchatgpt.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a direct writing assistant for adult fiction."},
{"role": "user", "content": "Give me three opening lines for a noir story set in a flooded city."},
],
temperature=0.9,
)
print(resp.choices[0].message.content)
print(resp.usage)
The call is chat.completions.create, the same method you would use with any OpenAI-style service. The only things that identify this provider are the base_url and the model name uncensored. If the call fails with a 401, the key is wrong or missing. If it fails with a connection error, check that the base URL ends in /v1 and has no trailing path.
Check that the model is reachable
Before you debug a larger program, confirm the connection with the second endpoint the API offers, GET /v1/models. The SDK wraps it as client.models.list().
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unfilteredchatgpt.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
ids = [m.id for m in client.models.list()]
print(ids)
assert "uncensored" in ids, "model uncensored not listed"
You should see uncensored in the output. If the list loads, your key, your network path and your base URL are all fine, and any later problem is in your request body. The two endpoints, POST /v1/chat/completions and GET /v1/models, are the whole surface. There is no image, audio or embeddings route, so code that calls those will fail no matter how you configure the client.
The docs page has the same first request in curl form if you want to rule out Python as the cause.
Stream tokens as they arrive
Long replies feel slow if you wait for the full text. Set stream=True and print each piece as it comes in. The API sends server-sent events and reports token usage at the end of the stream.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unfilteredchatgpt.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a 300-word scene on a night train."}],
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("\n", chunk.usage)
The guard on chunk.choices matters, because the final chunk that carries usage can arrive with an empty choices list. One more detail for production: a streamed request holds its concurrency slot until the stream ends. If your code opens a stream and never reads it to the end, that slot stays busy and you will start seeing 429 errors with the code concurrency.
Ask for structured JSON
For scripts that feed another program, JSON mode saves you from parsing prose. Pass response_format={"type": "json_object"} and say in the prompt that you want JSON, with the keys you expect.
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unfilteredchatgpt.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply only with JSON using the keys name, motive and secret."},
{"role": "user", "content": "Invent a suspect for a murder mystery set in a lighthouse."},
],
temperature=0.7,
)
suspect = json.loads(resp.choices[0].message.content)
print(suspect["name"], "-", suspect["motive"])
Still wrap json.loads in a try block in real code. JSON mode makes valid output likely, but a reply cut off by a stop sequence or a token limit can still be incomplete, and a failed parse should trigger a retry rather than a crash.
Tool calling
Tool calling follows the standard OpenAI shape. You describe functions in tools, the model replies with a tool_calls entry, you run the function, and you send the result back as a message with role: "tool".
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unfilteredchatgpt.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
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 character."}]
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]
args = json.loads(call.function.arguments)
result = {"roll": 14, "sides": args["sides"]} # replace with a real function
messages.append(msg)
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)
else:
print(msg.content)
Always check that tool_calls exists before reading it, since the model may choose to answer directly. Validate the arguments before you act on them, because they come from generated text.
Handle 429 errors and run requests in parallel
Limits are simple. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent requests and 60 per minute. Go over and you get HTTP 429 with the code rate_limited for requests per minute, or concurrency for too many at once. On temporary overload the API also returns 429 with a Retry-After: 5 header. Treat all three as a signal to wait and try again.
The SDK already retries some failures, and you can raise the count with max_retries. For batch jobs, cap your worker count at the concurrency limit so you do not trigger the errors in the first place:
import os
import time
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI, RateLimitError
client = OpenAI(
base_url="https://api.unfilteredchatgpt.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
max_retries=0,
)
def ask(prompt):
for attempt in range(5):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError as e:
wait = int(e.response.headers.get("Retry-After", 5))
time.sleep(wait * (attempt + 1))
raise RuntimeError("gave up after 5 tries")
prompts = [f"Write one tagline for a ghost story, variation {i}." for i in range(20)]
# 8 workers for a full key, 2 for a trial key
with ThreadPoolExecutor(max_workers=8) as pool:
for out in pool.map(ask, prompts):
print(out)
The wait grows with each attempt, which keeps a busy moment from turning into a retry storm. If you see the same error with every worker, lower max_workers before you change anything else. The production checklist covers timeouts and logging in more depth.
Track cost and balance in code
Billing is per token: $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. Failed or refused requests are not charged. Each response has an X-Balance-USD header, and the SDK exposes headers through with_raw_response:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unfilteredchatgpt.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "Name five villains for a fantasy campaign."}],
)
resp = raw.parse()
u = resp.usage
cost = u.prompt_tokens / 1_000_000 * 0.15 + u.completion_tokens / 1_000_000 * 0.50
print("request id:", raw.headers.get("X-Request-Id"))
print("balance:", raw.headers.get("X-Balance-USD"))
print(f"this call: ${cost:.6f}")
As a worked example, a job of 500 requests with 1,500 input tokens and 600 output tokens each uses 750,000 input tokens and 300,000 output tokens in total. Input costs 0.75 x $0.15 = $0.1125 and output costs 0.3 x $0.50 = $0.15, so the whole job is $0.2625. Log X-Request-Id with every call so that support can trace a specific request. Rates are on the pricing page.
Top-ups run from $20 to $500 in any whole amount, with +5% from $50, +10% from $100 and +15% from $200, paid by crypto (USDT on TRC20, USDC on Base). New users can claim $0.50 of trial credit with one click on the API key page, valid for 7 days with no payment needed, which is enough to run every example here several times.
Keep a multi-turn chat going
The API is stateless. It does not remember earlier requests, so a chat is just a list of messages that you grow and resend each time. That is also why input tokens add up in long sessions: every turn pays again for the whole history. A small loop shows the pattern, with a simple cap so the list does not grow without limit.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unfilteredchatgpt.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
history = [{"role": "system", "content": "You are the narrator of a text adventure for adults."}]
while True:
user = input("you> ").strip()
if not user:
break
history.append({"role": "user", "content": user})
r = client.chat.completions.create(model="uncensored", messages=history, temperature=0.9)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
print(reply)
# keep the system message plus the last 40 messages
if len(history) > 41:
history = history[:1] + history[-40:]
Cutting by message count is the simplest rule. A better one counts tokens and drops the oldest turns first once the history passes a budget you pick, well below the 100,000-token window. Many story and companion apps also keep a short running summary of old events in the system message, so the model keeps the plot while the raw text is dropped. That trade saves money and keeps replies on topic.
If your app serves many users at once, use AsyncOpenAI with the same base_url and key. Create the client once at startup and share it across requests, and put a semaphore of 8 around your calls so a burst of traffic queues in your own code instead of being rejected with a 429.
Common problems and fixes
- 401 unauthorized. The key is missing or has a typo. Print
bool(os.environ.get("UNCENSORED_API_KEY"))to check the variable is set in the shell that runs Python. - 404 or HTML in the response. The base URL is missing
/v1or has an extra path segment. - Model not found. The model ID must be exactly
uncensored, in lowercase. - Request too large. The body limit is 8 MB, and the context window is 100,000 tokens for prompt plus completion. Trim old chat turns first.
- Replies stop mid-sentence. If you set
max_tokens, raise it or remove it. It is optional, and the completion may use the rest of the window. - Unexpected refusal. The model answers without content refusals for lawful adult use, but it will never write sexual content involving minors. That limit is fixed.
When something still looks wrong, print the response status and the X-Request-Id header, then send that ID to the support page contact. A request ID lets someone find your exact call instead of guessing from a description, which usually shortens the fix from days to a single reply.
