Apiaiuncensored/Uncensored AI API Example: A Starter Project
Uncensored AI API Example: A Starter Project
Here is a small starter you can copy: a project layout, a client with the key in the environment, a chat call, streaming and a retry loop that respects rate limits. Everything runs against an OpenAI-compatible endpoint.
Last updated
Summary
- The whole integration is a base URL, a key and the model ID uncensored.
- Keep the key in an environment variable or a .env file that is not committed.
- Handle HTTP 429 by reading its error code and the Retry-After header.
- Streaming holds a concurrency slot until it ends, so cap your parallel streams.

What the starter contains
This uncensored AI API example is a folder of six files. It does one useful thing: send a prompt, stream the answer and survive a rate limit. Copy it, then replace the prompt with your own logic. For the checks to make before you ship anything, read the production checklist.
starter/
.env.example
.gitignore
requirements.txt
client.py # shared client and retry helper
chat.py # one-shot call and streaming call
chat.mjs # the same in NodeThe API is OpenAI-compatible and serves one open-weight model, tuned to answer without content refusals for lawful adult use. It is an independent service, not the official API of any model maker. Sexual content involving minors is a hard limit. It is text only.
Get a key and set the environment
Sign up with Google, or with email and password. On the API key page you can create a key and claim $0.50 of trial credit with one click. It is valid for 7 days, needs no card and is limited to one per person. The key guide has the steps.
Create .env.example and commit it. Copy it to .env and fill in the real key, which stays out of git.
# .env.example
API_KEY=paste-your-key-here
API_BASE_URL=https://api.apiaiuncensored.com/v1# .gitignore
.env
.venv/
node_modules/# requirements.txt
openai>=1.0
python-dotenv>=1.0The Python client with retries
Put the client and the retry helper in one file so both scripts share them. The helper retries on rate limits and temporary overload, and it stops after a few attempts.
# client.py
import os
import time
from dotenv import load_dotenv
from openai import OpenAI, RateLimitError
load_dotenv()
client = OpenAI(
base_url=os.environ.get("API_BASE_URL", "https://api.apiaiuncensored.com/v1"),
api_key=os.environ["API_KEY"],
)
def with_retry(fn, tries=5):
for attempt in range(tries):
try:
return fn()
except RateLimitError as err:
retry_after = err.response.headers.get("retry-after")
wait = float(retry_after) if retry_after else 2 ** attempt
time.sleep(wait)
raise RuntimeError("rate limited after several retries")A 429 with the code rate_limited means you passed the requests-per-minute limit, which is 300 on a full key and 60 on a trial key. The code concurrency means too many requests at once: 8 on a full key, 2 on a trial key. Temporary overload sends 429 with Retry-After: 5, which the helper reads. See the docs for the full list.
One-shot and streaming calls
The chat script uses both modes. The system message sets the behavior, the user message is your input.
# chat.py
from client import client, with_retry
MESSAGES = [
{"role": "system", "content": "You are a direct, concise assistant."},
{"role": "user", "content": "Explain what a mutex is in three sentences."},
]
def one_shot():
resp = with_retry(lambda: client.chat.completions.create(
model="uncensored", messages=MESSAGES, temperature=0.7,
))
print(resp.choices[0].message.content)
print("tokens:", resp.usage.prompt_tokens, resp.usage.completion_tokens)
def stream():
chunks = with_retry(lambda: client.chat.completions.create(
model="uncensored", messages=MESSAGES, stream=True,
))
for c in chunks:
if c.choices and c.choices[0].delta.content:
print(c.choices[0].delta.content, end="", flush=True)
print()
if __name__ == "__main__":
one_shot()
stream()The retry wrapper covers the moment the request is accepted. If a stream breaks halfway, handle that in your own code by keeping the partial text and deciding whether to resume or restart. A streamed request occupies its concurrency slot until the stream ends, so do not open more parallel streams than your key allows.
The same starter in Node
The OpenAI Node package accepts the same two settings. A current Node LTS release is enough.
npm install openai dotenv// chat.mjs
import "dotenv/config";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: process.env.API_BASE_URL ?? "https://api.apiaiuncensored.com/v1",
apiKey: process.env.API_KEY,
maxRetries: 4,
});
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [
{ role: "system", content: "You are a direct, concise assistant." },
{ role: "user", content: "Explain what a mutex is in three sentences." },
],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
process.stdout.write("\n");The maxRetries option makes the SDK retry on its own; set it to what suits your latency budget.
To run it, save the file as chat.mjs, export the two variables or keep them in a .env file and start it with node chat.mjs. A typical first failure is a missing key, which the SDK reports as an authentication error; check that the variable is set in the same terminal. Another is an old Node version without top-level await support for ES modules, in which case upgrade Node or wrap the code in an async function.
Timeouts and logging before you grow
A script that works in a terminal can still fail under real load. Two small changes make the starter safer to extend: a timeout and request logging.
# client.py (additions)
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("llm")
client = OpenAI(
base_url=os.environ.get("API_BASE_URL", "https://api.apiaiuncensored.com/v1"),
api_key=os.environ["API_KEY"],
timeout=60.0,
)
def logged_chat(**kwargs):
raw = client.chat.completions.with_raw_response.create(**kwargs)
resp = raw.parse()
log.info("request_id=%s balance=%s in=%s out=%s",
raw.headers.get("x-request-id"),
raw.headers.get("x-balance-usd"),
resp.usage.prompt_tokens, resp.usage.completion_tokens)
return resp
resp = logged_chat(model="uncensored", messages=[{"role": "user", "content": "Say hello."}])Each log line carries the request ID, your remaining balance and the tokens used. When something looks wrong, that ID is what you quote to support. Keep the log free of prompt text unless you need it, since prompts may hold personal data.
Test it
Add one smoke test that sends a short prompt and checks that a reply came back, and one that sends an invalid key and expects an authentication error. Run both before every deployment. A third test can send ten parallel requests on a trial key and confirm that your retry helper copes with HTTP 429 and the concurrency code.
Check your balance and test with curl
Before you build further, confirm the key works with a plain request. The methods available are POST /v1/chat/completions, POST /v1/responses and GET /v1/models.
curl https://api.apiaiuncensored.com/v1/models \
-H "Authorization: Bearer $API_KEY"
curl -i https://api.apiaiuncensored.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"uncensored","messages":[{"role":"user","content":"Say hello."}]}'The -i flag prints headers. Look at X-Balance-USD for your remaining credit and at X-Request-Id, which you should log with errors so that a specific call can be traced. X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency show your limits.
Ideas for what to build next
- A command line chat with history saved to a JSON file.
- A writing assistant for fiction, with a character sheet in the system message.
- A batch tool that reads a CSV, sends each row with JSON mode and writes the results back.
- A tool-calling helper that looks up data from your own database.
For the second and third ideas, the model is tuned to answer without content refusals for lawful adult use, so your own validation and policy rules matter. It is text only, so plan other tools for images or embeddings.
When something fails: a quick diagnosis table
Most first-run problems come from a short list of causes. Check them in this order before you change any code.
| Symptom | Likely cause | Fix |
|---|---|---|
| Authentication error | Missing, mistyped or replaced key | Print whether the variable is set, without printing the key. If the key is lost or was replaced, regenerate it yourself on the API key page; the old key stops working at once. |
| Model not found | Wrong model ID | Use uncensored. GET /v1/models lists what the key can use. |
429 with rate_limited | More than the per-minute limit | Slow the loop. Limits are 300 per minute on a full key, 60 on a trial key. |
429 with concurrency | Too many requests or open streams at once | Cap parallel work at 8 on a full key or 2 on a trial key. |
| Request rejected for size | Body over 8 MB | Send less text, for example only the relevant part of a document. |
| Connection error or timeout | Wrong base URL or a network problem | Check that the URL ends in /v1 and has no extra slash or path. |
If a call still fails, note the X-Request-Id header from the response and the time, then write to the contact on the support page.
Next steps and cost
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, with no subscription. The three-sentence mutex answer above uses about 40 input tokens and 120 output tokens. That is 40 x $0.15 / 1M = $0.000006 plus 120 x $0.50 / 1M = $0.00006, so $0.000066 per run. The trial credit would cover thousands of runs.
To go further, add JSON mode with response_format, tool calling with tools, a request timeout and structured logging. When you are ready to pay, top-ups are any whole amount from $20 to $500, in crypto (USDT on TRC20 or USDC on Base), with a bonus from $50 up. Details are on the pricing page.
Before you deploy, read the docs once end to end. Pay attention to the parts about limits and error codes, because those shape the retry helper you will rely on. Keep the starter small; add features one at a time and test each with the trial key before you add a paid balance.
More guides
Common questions
Do I need a special SDK?
No. Use any OpenAI SDK. Change the base URL to https://api.apiaiuncensored.com/v1, use your key as the bearer token and set the model to uncensored.
Where should the API key live?
In an environment variable or an uncommitted .env file on your server, never in browser or mobile code.
How should I handle HTTP 429?
Read the error code and the Retry-After header, wait, and retry a limited number of times. Reduce parallel requests if the code is concurrency.
Does the starter work with the trial key?
Yes. Run requests one at a time, since the trial key allows 2 concurrent requests and 60 requests per minute.
Get your API key now
Register, retrieve your key, update the base URL. Simple setup.
Table of contents
- What the starter contains
- Get a key and set the environment
- The Python client with retries
- One-shot and streaming calls
- The same starter in Node
- Timeouts and logging before you grow
- Check your balance and test with curl
- Ideas for what to build next
- When something fails: a quick diagnosis table
- Next steps and cost
- More guides
Email + password gives immediate key access.