Uncensored AIHow to Use an AI Image API
Chat Completions API in Python: Stream and Handle Errors
This chat completions api python walkthrough takes you from install to a production-minded client: first request, streaming, tool calls, JSON mode and error handling. Every example targets an OpenAI-compatible endpoint with the model ID uncensored.
Updated

01Uncensored AI
Key points
Text APIs handle prompt construction, script writing, and metadata extraction independently of image generation models.
OpenAI-compatible endpoints allow direct integration using standard SDKs without custom protocol development.
Streaming support enables real-time token delivery, essential for interactive prompt refinement workflows.
Token pricing is usage-based, with specific limits on context windows and request rates.
Install and make the first request
You need Python 3.8 or newer and the OpenAI package. Create a key on the API key page; the one-click trial gives $0.50 of credit with no payment needed.
pip install openai
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiimage.com/v1",
api_key="YOUR_KEY",
)
response = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "What is a mutex?"},
],
temperature=0.7,
)
print(response.choices[0].message.content)
print(response.usage)
This sends POST /v1/chat/completions. Messages are a list of dicts with a role of system, user, assistant or tool. The reply is in choices[0].message.content, and usage reports prompt and completion tokens so you can compute cost: $0.15 per 1M input and $0.50 per 1M output.
Use environment variables, not hard-coded keys
Keep the key out of source control. The SDK reads OPENAI_API_KEY and OPENAI_BASE_URL from the environment if you do not pass them, which makes the same script work against different endpoints.
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ.get("LLM_BASE_URL", "https://api.uncensoredaiimage.com/v1"),
api_key=os.environ["LLM_API_KEY"],
timeout=120,
max_retries=0,
)
Setting max_retries=0 turns off the SDK's automatic retries so that you control the retry policy yourself, as shown in the error section below. A generous timeout is sensible for long completions, since the context window is 100,000 tokens and replies can be long.
Streaming
For chat interfaces, stream tokens as they arrive. Set stream=True and iterate. Ask for usage so the final chunk carries token counts.
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Explain TCP slow start briefly."}],
stream=True,
stream_options={"include_usage": 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)
if chunk.usage:
usage = chunk.usage
print()
print("tokens:", usage.prompt_tokens, usage.completion_tokens)
The transport is server-sent events. One thing to remember: a streamed request holds one of your concurrent slots until the stream ends. A full key has 8 slots, a trial key has 2. If you abandon a stream, close it so the slot frees up.
Conversation state
The API is stateless. You resend the history each turn. Append the assistant reply, then the next user message.
history = [{"role": "system", "content": "You are a helpful tutor."}]
def chat(user_text):
history.append({"role": "user", "content": user_text})
r = client.chat.completions.create(model="uncensored", messages=history)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("Define recursion."))
print(chat("Now give a Python example."))
History is billed as input on every call, so long chats cost more per turn. Trim the oldest messages once you pass a limit you choose, and keep the system prompt.
JSON mode and tool calls
JSON mode
Pass response_format={"type": "json_object"} and tell the model in the prompt which keys you want. Parse the result and handle failure, because the model can still produce malformed output.
import json
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Return JSON with keys city and country for Lyon."}],
response_format={"type": "json_object"},
)
data = json.loads(r.choices[0].message.content)
print(data)
Tool calling
tools = [{
"type": "function",
"function": {
"name": "get_time",
"description": "Current time in a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
msgs = [{"role": "user", "content": "What time is it in Tokyo?"}]
r = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
call = r.choices[0].message.tool_calls[0]
msgs.append(r.choices[0].message)
msgs.append({"role": "tool", "tool_call_id": call.id, "content": "14:05"})
final = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
print(final.choices[0].message.content)
In real code, check that tool_calls is not empty before indexing, since the model may answer directly. Results go back as role: "tool" messages.
Sampling parameters that are passed through
These parameters go to the model unchanged: temperature, top_p, stop, seed, frequency_penalty and presence_penalty. A few practical settings:
- Extraction and code: temperature 0 to 0.3, so answers stay stable between runs.
- Creative writing and roleplay: temperature 0.8 to 1.0, with a mild presence penalty if the text loops.
- Reproducible tests: fix
seedand keep the other settings the same. Treat repeatability as best effort, not a guarantee. - Cutting off output: use
stopwith a marker string, for example a line your format ends with.
Change one setting at a time and compare on a fixed set of prompts. Changing temperature and penalties together makes it hard to tell what helped.
Errors, limits and retries
Treat three cases separately. A 429 with code rate_limited means you exceeded requests per minute (300 on a full key, 60 on a trial key). A 429 with code concurrency means too many requests at once (8 and 2). A 429 with a Retry-After: 5 header means temporary overload, so wait and try again. Failed or refused requests are not charged.
import time, random
from openai import APIStatusError, APIConnectionError, RateLimitError
def complete(messages, tries=5):
for attempt in range(tries):
try:
return client.chat.completions.create(model="uncensored", messages=messages)
except RateLimitError as e:
wait = float(e.response.headers.get("Retry-After", 5))
time.sleep(wait + random.random())
except APIConnectionError:
time.sleep(2 ** attempt)
except APIStatusError as e:
if e.status_code >= 500:
time.sleep(2 ** attempt)
else:
raise
raise RuntimeError("gave up after retries")
For parallel work, cap concurrency in your own code rather than relying on retries. A ThreadPoolExecutor(max_workers=8) or an asyncio.Semaphore(8) matches a full key. Requests over 8 MB are rejected, which only matters if you embed large documents in the prompt.
Track cost and balance
Every response includes X-Request-Id, X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency. To read headers with the SDK, use the raw response:
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "ping"}],
)
print(raw.headers.get("X-Balance-USD"), raw.headers.get("X-Request-Id"))
response = raw.parse()
print(response.choices[0].message.content)
You can also call GET /v1/balance. Log the request ID with every error; it is the quickest way to get help from the support page. Top-ups run from $20 to $500 with bonuses from $50, paid in crypto (USDT on TRC20 or USDC on Base); see pricing.
If you prefer to test with raw HTTP first, the curl guide shows the same call, and the docs list all endpoints. For code-focused prompts, see uncensored AI for coding. Remember this is a text-only API: it does not generate images, even though the site name might suggest it.
More guides
02Uncensored AI
Questions and answers
Do I need a special library?
No. The official openai Python package works once you set base_url and api_key. Use model uncensored.
What is the maximum context?
The context window is 100,000 tokens, prompt plus completion. max_tokens is optional, so a completion can use the remaining space.
How do I tell the two 429 errors apart?
Read the error code. rate_limited means too many requests per minute, concurrency means too many at once. A Retry-After: 5 header marks temporary overload.
Is max_tokens required?
No. It is optional. Set it when you want to cap reply length and cost.
Uncensored AIuncensoredaiimage.com
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.