Prerequisites
You need a current Python 3 release, the OpenAI package and an API key. Install the package with pip install openai. For the key, sign up on the API key page. New users can claim $0.50 of trial credit with one click there, valid for 7 days, with no card required. The sign-in is Google or email with a password.
Export the key so it stays out of your source files: export UNCENSORED_API_KEY=your_key_here. Three values define the connection: base URL https://api.dolphinaisincensura.com/v1, model uncensored, and the key as a bearer token. The SDK handles the bearer header for you.
Your first request
A minimal call looks the same as any OpenAI call, apart from the base URL. This example sets a system prompt, asks for an answer in Spanish and limits the length.
from openai import OpenAI
client = OpenAI(
api_key="YOUR_KEY",
base_url="https://api.dolphinaisincensura.com/v1",
)
response = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a direct, helpful assistant. Answer in Spanish."},
{"role": "user", "content": "Explica que es una API compatible con OpenAI."},
],
temperature=0.7,
max_tokens=300,
)
print(response.choices[0].message.content)The /v1/chat/completions endpoint is the main one. The API also offers /v1/responses and GET /v1/models. A quick way to check that your key works is to list models and look for uncensored. Full endpoint notes are in the docs.
Keep the conversation going
The API keeps no state between calls, so a chat is just a list you grow. After each answer, append the assistant message to the list, then append the next user message, and send the whole list again. This is also why costs rise during a long chat: older turns are sent as input every time.
from openai import OpenAI
client = OpenAI(api_key="YOUR_KEY", base_url="https://api.dolphinaisincensura.com/v1")
messages = [{"role": "system", "content": "Eres un asistente breve y directo."}]
while True:
user = input("tu: ")
if not user:
break
messages.append({"role": "user", "content": user})
r = client.chat.completions.create(model="uncensored", messages=messages, max_tokens=300)
answer = r.choices[0].message.content
messages.append({"role": "assistant", "content": answer})
print("ia:", answer)For long sessions, trim the list to the system message plus the last several turns so the cost per request stays flat.
Streaming responses
Long answers feel faster when they appear as they are written. Set stream=True and iterate over the chunks. The API sends server-sent events and reports usage at the end.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["UNCENSORED_API_KEY"], base_url="https://api.dolphinaisincensura.com/v1")
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Escribe un poema corto sobre el mar."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()The check on chunk.choices matters. The last chunk can arrive with an empty choices list because it carries the usage data, and indexing into it would raise an error. One more point: a streamed request holds its concurrency slot until the stream ends, so always read it to the end or close it.
Handle errors and rate limits
A full key allows 8 concurrent requests and 300 requests per minute. The trial key allows 2 and 60. Past those numbers you get HTTP 429. The error code rate_limited means too many requests per minute, and concurrency means too many at once. A temporary overload also returns 429 with Retry-After: 5.
This helper retries on 429 and on connection problems, and logs the request ID on other API errors so you can quote it if you need help.
import os
import time
import openai
from openai import OpenAI
client = OpenAI(api_key=os.environ["UNCENSORED_API_KEY"], base_url="https://api.dolphinaisincensura.com/v1")
def ask(messages, retries=3):
for attempt in range(retries):
try:
return client.chat.completions.create(
model="uncensored", messages=messages, max_tokens=400
)
except openai.RateLimitError as e:
wait = float(e.response.headers.get("retry-after", 5))
print("429:", getattr(e, "code", None), "waiting", wait, "s")
time.sleep(wait)
except openai.APIConnectionError:
time.sleep(2 ** attempt)
except openai.APIStatusError as e:
print("API error", e.status_code, e.response.headers.get("x-request-id"))
raise
raise RuntimeError("still failing after retries")
result = ask([{"role": "user", "content": "Hola, que tal?"}])
print(result.choices[0].message.content)If you run many requests in parallel with threads or asyncio, put a semaphore of 8 around the call (2 on a trial key). Otherwise your code produces the 429 errors it then has to retry. Failed or refused requests are not charged.
Do not retry forever. Cap attempts, as the helper does, and surface a clear message when it still fails. If you see the same error from every request, check the key first: a revoked or regenerated key stops working at once, and the fix is to copy the new one from the API key page.
JSON mode and balance headers
When you need structured output, pass response_format={"type": "json_object"} and say in the prompt which keys you expect. The raw-response wrapper in the SDK gives you access to headers, which include X-Balance-USD, X-Request-Id and the rate-limit headers.
import json
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["UNCENSORED_API_KEY"], base_url="https://api.dolphinaisincensura.com/v1")
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[
{"role": "system", "content": "Reply only with a JSON object with keys title and tags."},
{"role": "user", "content": "Suggest a title and three tags for a story about a lighthouse."},
],
response_format={"type": "json_object"},
)
print("balance:", raw.headers.get("x-balance-usd"))
data = json.loads(raw.parse().choices[0].message.content)
print(data)Even in JSON mode, wrap the parse in a try block. If a response is cut off by max_tokens, the JSON will be incomplete.
What each call costs
The price is $0.15 per 1M input tokens and $0.50 per 1M output tokens. The response has a usage object with token counts, so cost is easy to compute in code: prompt_tokens * 0.15 / 1_000_000 + completion_tokens * 0.50 / 1_000_000.
Take the first example in this guide. Suppose it used 60 prompt tokens and 250 completion tokens. Input is $0.000009 and output is $0.000125, so the call costs $0.000134, which means about 7,400 calls per dollar. Chat history is the main driver in real apps, since every turn re-sends earlier messages. The pricing page has more worked examples and the top-up bonuses.
Next steps
Parallel calls with asyncio
If you process a batch of prompts, the async client keeps the code short. The semaphore holds the number of in-flight requests at your key's concurrency limit, so you do not trigger 429 errors with your own parallelism.
import asyncio
import os
from openai import AsyncOpenAI
client = AsyncOpenAI(api_key=os.environ["UNCENSORED_API_KEY"], base_url="https://api.dolphinaisincensura.com/v1")
sem = asyncio.Semaphore(8) # use 2 on a trial key
async def one(prompt):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
max_tokens=200,
)
return r.choices[0].message.content
async def main():
prompts = ["Define token.", "Define prompt.", "Define context window."]
for answer in await asyncio.gather(*(one(p) for p in prompts)):
print(answer)
asyncio.run(main())Each answer is billed by its own token counts, so a batch of 1,000 short prompts costs the sum of 1,000 small requests, not a flat fee.
Once the basics work, tool calling (tools, tool_choice) and JSON mode let you build agents and pipelines on the same client. For sampling, temperature, top_p, stop, seed and the penalty parameters are passed through. If you are still comparing providers, our piece on uncensored LLM API options sets the choices side by side.
Keep your use to lawful adult content. There is a hard limit on sexual content involving minors, and your own app should enforce it as well.
Two small habits make Python projects easier to live with. First, put the base URL, model name and key in one settings module so you change them in one place. Second, log the X-Request-Id value with each failure. If you ever contact support, that single value identifies the exact request. Keep a table of your own average token counts too; it makes the cost estimate on the pricing page concrete for your workload.
