EN ▾
Get API key

Uncensored LLM API in Python With the OpenAI SDK

You do not need a special library to use an uncensored LLM API from Python. The official openai package works once you point it at a new base URL and key. This article gives tested patterns for chat, streaming, JSON mode, tools and error handling.

Updated

Abstract terminal with ribbons of light flowing through a gateway into chat bubbles, representing a Python API call

Key points

  1. Install openai, set base_url to https://api.ornith.cc/v1 and use model uncensored.
  2. Streaming, JSON mode and tool calling use the standard OpenAI parameters.
  3. A full key allows 8 concurrent requests, so cap your worker pool at 8.
  4. Handle HTTP 429 by reading the error code and the Retry-After header.

Setup and a first call

If you want an uncensored llm api python setup that takes a few minutes, the only prerequisites are a current Python 3, the openai package and an API key. The API is OpenAI-compatible, so the code is the same you would write for any chat completions endpoint, with two values changed.

pip install openai
export ORNITH_API_KEY="paste-your-key-here"

Get the key from the API key page. New accounts can claim $0.50 of trial credit there, which is plenty for everything in this article. Then make your first call:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.ornith.cc/v1",
    api_key=os.environ["ORNITH_API_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a blunt writing coach for adult fiction authors."},
        {"role": "user", "content": "Critique this opening line: The rain would not stop."},
    ],
    temperature=0.8,
)

print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens, resp.usage.completion_tokens)

The model ID is always uncensored. You can confirm what the server exposes with client.models.list(), which calls GET /v1/models. Keep the key in an environment variable or a secrets manager, never in the source file, and never in a repository, even a private one, since keys copied into git history are hard to remove completely.

Reading usage, cost and balance

Every response includes the token counts, and the HTTP headers carry extra information. To see headers, use the SDK's raw-response wrapper, then call parse() to get the normal object back.

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.ornith.cc/v1", api_key=os.environ["ORNITH_API_KEY"])

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Name three moods for a villain's monologue."}],
)
resp = raw.parse()

print("request id:", raw.headers.get("X-Request-Id"))
print("balance usd:", raw.headers.get("X-Balance-USD"))
print("req/min limit:", raw.headers.get("X-RateLimit-Limit-Requests"))
print("concurrency limit:", raw.headers.get("X-RateLimit-Limit-Concurrency"))

cost = resp.usage.prompt_tokens * 0.15 / 1_000_000 + resp.usage.completion_tokens * 0.50 / 1_000_000
print(f"this call cost about ${cost:.6f}")

The price is $0.15 per 1M input tokens and $0.50 per 1M output tokens, so the helper above matches the bill. Log X-Request-Id with every failure; it is the first thing support will ask for. The pricing page has worked examples if you want to budget before you build.

Streaming responses

For chat interfaces and long generations you want tokens as they arrive. Pass stream=True and iterate. The API uses server-sent events and reports usage at the end of the stream.

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.ornith.cc/v1", api_key=os.environ["ORNITH_API_KEY"])

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a short scene: two rival chefs share a lift."}],
    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("tokens:", usage.prompt_tokens, usage.completion_tokens)

Two details trip people up. First, the final chunk may have an empty choices list, so the guard in the loop matters. Second, a streamed request holds its concurrency slot until the stream ends. If your code opens a stream and then stops reading, the slot stays busy. Close the stream or finish the loop, and wrap long loops in try/finally.

JSON mode for structured output

When another program consumes the answer, ask for JSON. Set response_format to {"type": "json_object"} and say in the prompt what shape you want. The word JSON in the instructions helps the model comply.

import json
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.ornith.cc/v1", api_key=os.environ["ORNITH_API_KEY"])

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "Reply with JSON only: {\"name\": str, \"traits\": [str], \"age\": int}"},
        {"role": "user", "content": "Invent an adult tavern keeper for a fantasy novel."},
    ],
    response_format={"type": "json_object"},
    temperature=0.7,
)

character = json.loads(resp.choices[0].message.content)
print(character["name"], character["traits"])

JSON mode asks for a JSON object, but it does not enforce your schema. Validate the result before you trust it, for example with pydantic, and keep a fallback for the rare reply that misses a field. If the output is cut off by a token limit, the JSON will be incomplete, so leave max_tokens unset or generous when you ask for large objects.

Tool calling

Tool calling lets the model ask your code to run a function and read the result. The parameters are the same as in the OpenAI API: tools, tool_choice, and results returned with role: "tool".

import json
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.ornith.cc/v1", api_key=os.environ["ORNITH_API_KEY"])

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll a number of dice with a given number of sides.",
        "parameters": {
            "type": "object",
            "properties": {
                "count": {"type": "integer"},
                "sides": {"type": "integer"},
            },
            "required": ["count", "sides"],
        },
    },
}]

messages = [{"role": "user", "content": "Roll three six-sided dice 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:
    messages.append(msg)
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = {"rolls": [4, 2, 6][: args["count"]]}  # replace with real logic
        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 parse arguments defensively. It is a string, and a model can produce malformed JSON now and then. Catch json.JSONDecodeError and either ask the model to try again or return an error message in the tool result. When streaming, the tool call arrives in pieces in delta.tool_calls, and you join the argument fragments by index before parsing.

Handling 429 errors and running in parallel

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. Over a limit, the API returns HTTP 429 with the error code rate_limited for requests per minute or concurrency for too many at once. A temporary overload also gives 429, with Retry-After: 5.

The SDK retries a couple of times by default. For batch work, take control: turn the built-in retries off and write one small wrapper.

import os
import time
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.ornith.cc/v1",
    api_key=os.environ["ORNITH_API_KEY"],
    max_retries=0,
)

def ask(prompt, attempts=5):
    for n in range(attempts):
        try:
            r = client.chat.completions.create(
                model="uncensored",
                messages=[{"role": "user", "content": prompt}],
            )
            return r.choices[0].message.content
        except RateLimitError as e:
            wait = float(e.response.headers.get("Retry-After", 2 ** n))
            print("429", getattr(e, "code", None), "waiting", wait)
            time.sleep(wait)
    raise RuntimeError("gave up after repeated 429 responses")

prompts = [f"Write a one-line toast for guest number {i}." for i in range(40)]
with ThreadPoolExecutor(max_workers=8) as pool:   # 8 matches a full key's concurrency
    for answer in pool.map(ask, prompts):
        print(answer)

Match max_workers to your key: 8 for a full key, 2 for a trial key. For a 300-per-minute budget that is about five requests per second, so a pool of 8 is rarely the bottleneck unless answers are fast. If you see concurrency errors with a pool of 8, check for open streams that never closed.

Async version for web apps

If your code already runs inside FastAPI, aiohttp or any asyncio program, use AsyncOpenAI. It takes the same arguments as the sync client. The one thing you must add yourself is a cap on in-flight requests, because an unbounded asyncio.gather over a thousand prompts will walk straight into the concurrency limit.

import asyncio
import os
from openai import AsyncOpenAI

client = AsyncOpenAI(base_url="https://api.ornith.cc/v1", api_key=os.environ["ORNITH_API_KEY"])
gate = asyncio.Semaphore(8)  # use 2 on a trial key

async def ask(prompt):
    async with gate:
        r = await client.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": prompt}],
        )
        return r.choices[0].message.content

async def main():
    prompts = [f"Describe a market stall in one sentence, stall {i}." for i in range(30)]
    answers = await asyncio.gather(*(ask(p) for p in prompts))
    print(len(answers), "answers")

asyncio.run(main())

The semaphore is the whole trick. Tasks queue up inside your process, and only eight at a time reach the network. That is cheaper and calmer than sending everything and sorting out the 429 responses afterwards. If you also stream to browsers, remember that each open stream holds a slot, so a busy chat page can use up your budget by itself. Count live streams in the same semaphore rather than keeping a second counter.

Keeping a conversation without wasting tokens

The API is stateless. It does not remember earlier calls, so a chat application sends the message list again on every turn. That is simple, and it is also where most of the bill comes from, since each turn pays for all earlier turns as input tokens. A small class keeps the history under control.

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.ornith.cc/v1", api_key=os.environ["ORNITH_API_KEY"])

class Chat:
    def __init__(self, system, keep=12):
        self.system = {"role": "system", "content": system}
        self.turns = []
        self.keep = keep  # number of recent messages to resend

    def say(self, text):
        self.turns.append({"role": "user", "content": text})
        r = client.chat.completions.create(
            model="uncensored",
            messages=[self.system] + self.turns[-self.keep:],
        )
        reply = r.choices[0].message.content
        self.turns.append({"role": "assistant", "content": reply})
        return reply

bot = Chat("You play a sarcastic ship's computer in an adult sci-fi story.")
print(bot.say("Status report."))

Keeping only the last twelve messages is crude but effective. For long roleplay you can do better: when the history passes a size you choose, ask the model to summarise the oldest part into a short note, store that note in the system message, and drop the originals. The window is large at 100,000 tokens, so you rarely run out of room. You run out of budget first, which is why trimming pays off long before it is forced on you.

Sampling settings matter too. For creative writing, a temperature between 0.7 and 1.0 gives variety. For extraction or classification, drop it to 0 to 0.3 and set a seed so repeated runs match. The penalties, top_p and stop are passed through to the model, so settings you tuned elsewhere carry over as a starting point, though you should recheck them against the new output.

Pitfalls and a checklist

  • Wrong base URL. It must end in /v1. Without it, the SDK builds paths the server does not know.
  • Wrong model name. Use uncensored, not a vendor model name copied from another tutorial.
  • Oversized prompts. The window is 100,000 tokens for prompt plus completion, and a request body can be at most 8 MB. Trim history before you hit either.
  • Costs from resent history. Every turn pays again for the whole conversation. Summarise old turns when a session grows.
  • Environment variables in notebooks. If os.environ["ORNITH_API_KEY"] raises a KeyError, the kernel was started before you exported the variable.

Two rules apply to any content you generate. The service is for lawful adult use, for example fiction, roleplay and companion apps for adults, and sexual content involving minors is not allowed. Prompts are not used for training, but still keep personal data out of them unless you need it.

The quickstart documentation lists every supported parameter, including top_p, stop, seed and the penalties. Set a seed with a low temperature when you want to compare two prompt versions fairly. Once the examples above run for you, top up from $20 and remove the trial limits. Credit never expires, so there is no pressure to spend it by a deadline, and failed or refused requests are not charged while you debug.

01

Questions and answers

Which Python package do I need?

The official openai package. Set base_url to https://api.ornith.cc/v1, pass your key, and use the model ID uncensored. No other client library is required.

Does the Python SDK support streaming here?

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

How many requests can I run in parallel?

A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 concurrent and 60 per minute. Extra requests get HTTP 429.

Can I use async code?

Yes. AsyncOpenAI takes the same base_url and api_key arguments. Limit the number of in-flight tasks with a semaphore set to your concurrency limit.

Is tool calling supported?

Yes. Use tools and tool_choice, and return results as messages with role tool. Streamed tool_calls are supported too.

Your key is one form away

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