EN ▾
Base URL https://api.uncensoredaiapis.com/v1Model uncensored
Get API key
Uncensored AICode examples

Uncensored AI API code examples in Python, Node.js and cURL

This page collects copy-paste code for the uncensored AI API, which speaks the OpenAI chat completions format. You will find first calls in Python, Node.js and cURL, streaming with the SDK and with raw fetch, function calling, retry logic for 429 and 503, multi-turn state, and cost control with max_tokens.

Uncensored AI API code examples in Python, Node.js and cURL

Updated

Key points

  • Use the official openai SDK with base_url set to https://api.uncensoredaiapis.com/v1 and model "uncensored"; no custom client is needed.
  • Streaming returns SSE chunks, and a final usage chunk arrives automatically with an empty choices list.
  • Retry only 429 and 503 (upstream_busy); 400, 401, 402 and 403 need a fix, not a retry.
  • The API is stateless: resend history each turn, and cap output with max_tokens (optional; if unset, the response can run to the end of the window).

First call: Python, Node.js and cURL

The examples use https://api.uncensoredaiapis.com/v1, model uncensored, and POST /v1/chat/completions or GET /v1/models. Send your current key in the Authorization: Bearer <key> header. If needed, create an account, request eligible trial credit and check that the displayed balance is ready before running requests.

The examples read the key from an environment variable named API_KEY. Export it once in your shell and none of the snippets need editing. Never paste a key into source code or ship it in browser JavaScript; call the API from your backend.

export API_KEY="paste-your-key-here"

Python, using the official openai package (v1 or newer). The only differences from a stock OpenAI setup are base_url and the model name.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.uncensoredaiapis.com/v1",
    api_key=os.environ["API_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a two-line villain monologue."}],
    max_tokens=200,
)
print(resp.choices[0].message.content)
print(resp.usage)

Node.js, using the openai npm package (v4 or newer) as an ES module.

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.uncensoredaiapis.com/v1",
  apiKey: process.env.API_KEY,
});

const resp = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Write a two-line villain monologue." }],
  max_tokens: 200,
});
console.log(resp.choices[0].message.content);
console.log(resp.usage);

And plain cURL, which is the quickest way to check that a key works:

curl https://api.uncensoredaiapis.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [{"role": "user", "content": "Write a two-line villain monologue."}],
    "max_tokens": 200
  }'

The response has the usual OpenAI shape: choices[0].message.content for the text and a usage object with prompt and completion token counts, which you can multiply by the per-token prices to track spend. See the docs for the full parameter list.

Streaming (SSE) with the SDK

Set stream: true and the API returns server-sent events instead of one JSON body. Both official SDKs turn that into an iterator, so your code loops over chunks and prints each delta. A final chunk carrying token usage is added automatically; you do not need to request it. That chunk has an empty choices list, so guard the index before reading it.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.uncensoredaiapis.com/v1",
    api_key=os.environ["API_KEY"],
)

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Describe a rainy harbor town in 120 words."}],
    max_tokens=300,
    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 chunk.usage:
        print("\n\nusage:", chunk.usage)

The Node.js version uses for await:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.uncensoredaiapis.com/v1",
  apiKey: process.env.API_KEY,
});

const stream = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Describe a rainy harbor town in 120 words." }],
  max_tokens: 300,
  stream: true,
});

for await (const chunk of stream) {
  const text = chunk.choices?.[0]?.delta?.content;
  if (text) process.stdout.write(text);
  if (chunk.usage) console.log("\n\nusage:", chunk.usage);
}

Streaming does not change pricing. You pay for the same input and output tokens; you simply see the first words sooner, which matters for chat and roleplay interfaces where waiting for a full 500-token reply feels slow.

Streaming with raw fetch

If you would rather not depend on the SDK, for example in an edge function or a small script, you can read the stream yourself. The wire format is plain SSE: each event is a line starting with data: followed by a JSON chunk, and events are separated by blank lines. Network chunks do not align with event boundaries, so you must buffer and split on newlines. The example below runs on Node 18 or newer (save it as stream.mjs) and also works in any runtime with the standard fetch and ReadableStream.

const res = await fetch("https://api.uncensoredaiapis.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "uncensored",
    messages: [{ role: "user", content: "Tell a 100-word ghost story." }],
    max_tokens: 250,
    stream: true,
  }),
});

if (!res.ok) {
  throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}

const decoder = new TextDecoder();
let buffer = "";

for await (const bytes of res.body) {
  buffer += decoder.decode(bytes, { stream: true });
  const lines = buffer.split("\n");
  buffer = lines.pop(); // keep the incomplete tail for the next round

  for (const line of lines) {
    if (!line.startsWith("data:")) continue;
    const data = line.slice(5).trim();
    if (data === "[DONE]") continue;
    const chunk = JSON.parse(data);
    const text = chunk.choices?.[0]?.delta?.content;
    if (text) process.stdout.write(text);
    if (chunk.usage) console.log("\n\nusage:", chunk.usage);
  }
}

Check res.ok before you start reading. Errors such as 401, 402 or 403 arrive as a normal JSON body with an error object, not as an event stream, so parsing them as SSE would silently produce nothing. In a browser you can use the same logic with res.body.getReader(), but remember that a browser must call your own backend, never this API directly with a secret key.

Function calling with tools and tool_choice

Tool calling uses the OpenAI format. You describe functions in tools, the model answers with tool_calls instead of text when it wants one run, you execute the function yourself, and you send the result back as a message with role: "tool" and the matching tool_call_id. A second request then returns the final natural-language answer. tool_choice controls the behaviour: "auto" lets the model decide, "none" forbids tools, and an object such as {"type": "function", "function": {"name": "get_order_status"}} forces that function.

import json
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.uncensoredaiapis.com/v1",
    api_key=os.environ["API_KEY"],
)

def get_order_status(order_id: str) -> dict:
    # Replace with a real lookup.
    return {"order_id": order_id, "status": "shipped", "eta_days": 2}

tools = [{
    "type": "function",
    "function": {
        "name": "get_order_status",
        "description": "Look up the shipping status of an order by its id.",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "string"}},
            "required": ["order_id"],
        },
    },
}]

messages = [{"role": "user", "content": "Where is order A-1042?"}]

first = client.chat.completions.create(
    model="uncensored",
    messages=messages,
    tools=tools,
    tool_choice="auto",
    max_tokens=500,
)
msg = first.choices[0].message

if msg.tool_calls:
    messages.append(msg)  # keep the assistant turn that contains tool_calls
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_order_status(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })
    final = client.chat.completions.create(
        model="uncensored",
        messages=messages,
        tools=tools,
        max_tokens=500,
    )
    print(final.choices[0].message.content)
else:
    print(msg.content)

The same loop in Node.js:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.uncensoredaiapis.com/v1",
  apiKey: process.env.API_KEY,
});

const getOrderStatus = ({ order_id }) => ({ order_id, status: "shipped", eta_days: 2 });

const tools = [{
  type: "function",
  function: {
    name: "get_order_status",
    description: "Look up the shipping status of an order by its id.",
    parameters: {
      type: "object",
      properties: { order_id: { type: "string" } },
      required: ["order_id"],
    },
  },
}];

const messages = [{ role: "user", content: "Where is order A-1042?" }];

const first = await client.chat.completions.create({
  model: "uncensored", messages, tools, tool_choice: "auto", max_tokens: 500,
});
const msg = first.choices[0].message;

if (msg.tool_calls?.length) {
  messages.push(msg);
  for (const call of msg.tool_calls) {
    const result = getOrderStatus(JSON.parse(call.function.arguments));
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
  }
  const final = await client.chat.completions.create({
    model: "uncensored", messages, tools, max_tokens: 500,
  });
  console.log(final.choices[0].message.content);
} else {
  console.log(msg.content);
}

Two practical notes. First, arguments is a JSON string produced by a language model, so always wrap json.loads in error handling in production and validate the fields before touching a database. Second, the tool definitions count as input tokens on every request, so keep descriptions short and send only the tools relevant to the current step.

Retries with backoff on 429 and 503

Two errors are worth retrying. A 429 means you exceeded the limit of 300 requests per minute for your key. A 503 with the code upstream_busy means the service is momentarily saturated; waiting a few seconds is the intended response. Do not retry 400 (fix the request), 401 (fix the key), 402 no_credit (top up the balance), or 403 content_blocked (the request will be blocked again). Errors share one JSON shape, {"error":{"code":...,"message":...}}, so you can log the code directly.

The OpenAI SDKs already retry connection errors, 429 and 5xx a couple of times by default, and you can raise that with max_retries. If you want control over the delays, disable the built-in retries and wrap the call yourself, using exponential backoff with jitter so parallel workers do not retry in lockstep.

import os
import random
import time
from openai import OpenAI, APIStatusError, APIConnectionError

client = OpenAI(
    base_url="https://api.uncensoredaiapis.com/v1",
    api_key=os.environ["API_KEY"],
    max_retries=0,  # we handle retries ourselves
)

RETRYABLE = {429, 503}

def chat_with_retry(messages, max_attempts=5, **kwargs):
    for attempt in range(max_attempts):
        try:
            return client.chat.completions.create(
                model="uncensored", messages=messages, **kwargs
            )
        except APIStatusError as e:
            if e.status_code not in RETRYABLE or attempt == max_attempts - 1:
                raise
        except APIConnectionError:
            if attempt == max_attempts - 1:
                raise
        delay = min(30, 2 ** attempt) + random.uniform(0, 1)
        time.sleep(delay)

resp = chat_with_retry(
    [{"role": "user", "content": "Give me three names for a tavern."}],
    max_tokens=100,
)
print(resp.choices[0].message.content)

The equivalent with raw fetch in Node.js:

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function chatWithRetry(body, maxAttempts = 5) {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const res = await fetch("https://api.uncensoredaiapis.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ model: "uncensored", ...body }),
    });

    if (res.ok) return res.json();

    const retryable = res.status === 429 || res.status === 503;
    if (!retryable || attempt === maxAttempts - 1) {
      throw new Error(`HTTP ${res.status}: ${await res.text()}`);
    }
    const delay = Math.min(30000, 2 ** attempt * 1000) + Math.random() * 1000;
    await sleep(delay);
  }
}

const data = await chatWithRetry({
  messages: [{ role: "user", content: "Give me three names for a tavern." }],
  max_tokens: 100,
});
console.log(data.choices[0].message.content);

If you hit 429 regularly, the better fix is usually a small client-side concurrency cap (a semaphore or a queue with five to ten workers) rather than longer sleeps. At 300 requests per minute you can sustain five requests per second, which is plenty for most apps.

Multi-turn conversation state

The API is stateless. It does not remember earlier requests, so every call must include the history you want the model to see. Keep a list of messages, append the user turn, call the API, append the assistant reply, and repeat. A system message at index 0 holds the persona or instructions and is sent every time.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.uncensoredaiapis.com/v1",
    api_key=os.environ["API_KEY"],
)

messages = [
    {"role": "system", "content": "You are a dry-witted ship's AI. Keep replies under 80 words."}
]

def say(text: str) -> str:
    messages.append({"role": "user", "content": text})
    resp = client.chat.completions.create(
        model="uncensored", messages=messages, max_tokens=300
    )
    reply = resp.choices[0].message.content
    messages.append({"role": "assistant", "content": reply})
    return reply

print(say("We just lost the main engine. Options?"))
print(say("Which of those is the least risky?"))

Because the whole history is re-sent, input cost grows with each turn. The context window is 100,000 tokens and covers the prompt and the completion together, so a very long session will eventually return a 400 error when the prompt itself exceeds the limit, while prompt + max_tokens beyond it just ends the reply at the end of the window. Common strategies are to drop the oldest user and assistant pairs while always keeping the system message, or to ask the model to summarise older turns into one short message and replace them. Store the history in your own database keyed by conversation id so that a restart does not lose the thread. For examples of long sessions with realistic cost estimates, see the use cases page.

Controlling cost with max_tokens

Pricing is $0.15 per million input tokens and $0.50 per million output tokens, billed from a prepaid balance. Output is about 3.3 times as expensive as input, and max_tokens is an optional cap on output for a single request. If you do not set it, the response can run to the end of the window. Setting it deliberately is the simplest cost control you have.

Worst-case arithmetic helps. If you do not cap the output, a response can run to the end of the window, so the output alone could cost up to 100,000 × $0.50 / 1,000,000 = $0.05. If you set max_tokens to 300 for a chat reply, the worst case drops to $0.00015. A typical turn with 1,500 input tokens and 300 output tokens costs about $0.000225 plus $0.00015, which is under $0.001.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.uncensoredaiapis.com/v1",
    api_key=os.environ["API_KEY"],
)

INPUT_PER_M = 0.25
OUTPUT_PER_M = 1.00

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Summarise the plot of Hamlet in 5 sentences."}],
    max_tokens=250,
)

u = resp.usage
cost = u.prompt_tokens * INPUT_PER_M / 1_000_000 + u.completion_tokens * OUTPUT_PER_M / 1_000_000
print(f"in={u.prompt_tokens} out={u.completion_tokens} cost=${cost:.6f}")
print("finish_reason:", resp.choices[0].finish_reason)

Watch finish_reason. A value of length means the reply hit your cap and was cut off; if that happens often, raise the cap or ask for shorter output in the prompt, since a cap alone truncates rather than makes the model concise. Pair the cap with instructions such as a target word count, and log usage for every call so you can see real averages instead of guessing. Your free trial credit and balance details are on the pricing page.

Questions and answers

Do I need a special SDK for this uncensored AI API?

No. The official openai Python package (v1+) and openai npm package (v4+) work. Set base_url to https://api.uncensoredaiapis.com/v1, pass your key, and use the model id uncensored.

Does streaming include token usage?

Yes. With stream: true the API adds a final chunk that carries usage automatically. That chunk has an empty choices array, so check that choices exists before reading the delta.

Which errors should my code retry?

Retry 429 (rate limit, 300 requests per minute per key) and 503 upstream_busy with exponential backoff and jitter. Do not retry 400, 401, 402 or 403 because the same request will fail again.

Is conversation history stored for me between calls?

No. Each request is independent, so you send the full messages list every time. The context window is 100,000 tokens for prompt and completion combined.

Your key is one form away

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