OpenAI API Example: Python, Node and curl Code
Every snippet below is a complete OpenAI-style call that you can paste and run. The only changes from stock OpenAI code are the base URL, the key and the model ID.
Updated

No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).
Key points
- Set base URL to https://api.openainsfw.cc/v1 and model to uncensored; the OpenAI SDK needs nothing else.
- Streaming, JSON mode and tool calling use the same parameters as the OpenAI API.
- Full keys allow 8 concurrent requests and 300 per minute; a streamed request holds its slot until it ends.
- A 429 response carries a code of rate_limited or concurrency, plus Retry-After: 5 on temporary overload.
The smallest working example
Here is an open ai api example that targets a different server. Install the official Python SDK with pip install openai, export your key, and run this file. It sends one chat message and prints the reply plus the token usage.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.openainsfw.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a context window is in two sentences."},
],
temperature=0.7,
)
print(resp.choices[0].message.content)
print(resp.usage)
That is the whole change. Existing code written for the OpenAI SDK keeps working once base_url, api_key and model point here. The model ID is uncensored; this endpoint serves a single open-weight model, so there is nothing else to pick from. If you copied a snippet from a tutorial that names another model, replace that string and nothing more. The response object has the same shape as OpenAI's: the text is in choices[0].message.content, the finish reason sits next to it, and token counts are in usage.
Get a key and set the environment
Create an account with Google, or with email and password, then open the API key page. A new account can claim $0.50 of trial credit there with one click. It lasts 7 days, needs no payment, and is limited to one claim per person. Copy the key and keep it out of your source code:
export UNCENSORED_API_KEY="paste-your-key-here"
curl -s https://api.openainsfw.cc/v1/models -H "Authorization: Bearer $UNCENSORED_API_KEY"
# expected: a model list containing the ID "uncensored"
The second command calls GET /v1/models, which should list a single entry, uncensored. If it does, your key and network path work. The only other method is POST /v1/chat/completions, which the rest of this page uses. Anything that is not text chat, such as images, audio or embeddings, is not offered.
Authentication is a standard header, Authorization: Bearer <key>. The SDKs add it for you from the api_key argument.
The same call with curl
When something misbehaves, drop the SDK and use curl. It shows exactly what goes over the wire, which makes it the fastest way to separate a client bug from a server problem.
curl -s https://api.openainsfw.cc/v1/chat/completions -H "Authorization: Bearer $UNCENSORED_API_KEY" -H "Content-Type: application/json" -d '{
"model": "uncensored",
"messages": [
{"role": "user", "content": "Give me three names for a fantasy tavern."}
],
"max_tokens": 200,
"temperature": 0.9
}'
Add -i to see response headers. You will find X-Request-Id (quote it if you contact support), X-Balance-USD with your remaining credit, and the rate limit headers X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency. max_tokens is optional here. If you omit it, the completion can use whatever is left of the 100,000-token window after your prompt.
Node.js example
The official openai package for Node takes the same two settings. Use an ES module (a .mjs file or "type": "module" in package.json).
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.openainsfw.cc/v1",
apiKey: process.env.UNCENSORED_API_KEY,
});
const resp = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Write a two-line poem about rain." }],
temperature: 0.8,
});
console.log(resp.choices[0].message.content);
console.log(resp.usage);
The property is spelled baseURL in JavaScript and base_url in Python. That small difference is behind a surprising number of "it still calls the wrong server" reports. If your calls seem to go elsewhere, print the client's base URL first.
Streaming responses
For a chat interface you want tokens as they are produced. Set stream: true and read the chunks. The server uses SSE, the same format as OpenAI, and the final chunk includes usage so you can log what the request cost.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.openainsfw.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Describe a rainy harbour town in 120 words."}],
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()
print(usage)
Remember that a streamed request occupies one of your concurrency slots until the stream ends. A client that opens a stream and never reads it to the end will block its own slot. Always consume the stream or close it.
JSON mode
When another program reads the output, ask for a JSON object. Pass response_format and also say in the prompt that you want JSON, because the instruction and the format flag work best together.
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.openainsfw.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "Reply with a JSON object only."},
{"role": "user", "content": "Extract name and city: 'Maria lives in Lisbon.'"},
],
response_format={"type": "json_object"},
temperature=0,
)
data = json.loads(resp.choices[0].message.content)
print(data)
Keep json.loads inside a try block in production code. JSON mode makes valid output the normal case, but a reply cut off by max_tokens can still end mid-object.
Tool calling
Tool calling lets the model ask your code to run a function. You describe the tool, the model returns a tool_calls entry with arguments, you run the function, and you send the result back as a role: "tool" message. This example uses a made-up weather lookup.
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.openainsfw.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What is the weather in Oslo?"}]
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.model_dump(exclude_none=True))
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = {"city": args["city"], "temp_c": 4, "sky": "overcast"}
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)
Two habits save debugging time. First, always check msg.tool_calls before assuming the model answered directly, because it may decide no tool is needed. Second, parse arguments defensively: they arrive as a JSON string, and a model can occasionally produce malformed or unexpected values, so validate before you act on them. Tool calls can also be streamed, with the pieces arriving across chunks, if your interface needs it.
Multi-turn chat and sampling settings
The API keeps no memory between calls, so a conversation is a list you grow yourself. Append each user message and each reply, and send the whole list every time. The model sees only what is in messages.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.openainsfw.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
messages = [{"role": "system", "content": "You are a patient writing coach."}]
for question in ["Suggest a premise for a short mystery.", "Make the detective a retired baker."]:
messages.append({"role": "user", "content": question})
resp = client.chat.completions.create(
model="uncensored",
messages=messages,
temperature=0.8,
top_p=0.95,
seed=42,
stop=["###"],
)
answer = resp.choices[0].message.content
messages.append({"role": "assistant", "content": answer})
print(answer, "\n---")
The sampling settings are passed through to the model. temperature controls randomness, so use 0 to 0.3 for extraction and 0.8 to 1.0 for fiction. top_p trims the unlikely tail of word choices. seed makes repeated runs more alike, which helps when you compare prompts. stop ends the reply when a string appears, and the frequency and presence penalties push the model away from repeating itself. Change one setting at a time, or you will not know which one helped.
Because every call carries the full list, cost grows with chat length. Each reply also reports its token counts in resp.usage, so print those while you test and you will see the growth directly.
Common mistakes and quick fixes
Most failed first attempts come from a short list of causes. Check these before you suspect the server.
- 401 or an authentication error. The key is missing, has a stray space or newline, or the environment variable is not exported in the shell that runs your script. Print
len(os.environ["UNCENSORED_API_KEY"])to confirm it loaded. - The request goes to the wrong host. If you leave out the base URL, the SDK silently calls its default server. Set the URL on the client, or in the
OPENAI_BASE_URLenvironment variable that recent SDK versions read. - A path ending in /v1/v1. The base URL already ends with
/v1. Do not add it again when you build raw HTTP requests, and do not drop it when you use an SDK. - Model not found. The only model ID is
uncensored, in lowercase. Names from other providers will not work here. - Unsupported feature. Image, audio and embedding calls are not offered, so code that calls them needs a different provider for that part.
- Stuck streams. A loop that breaks out early without closing the stream keeps its concurrency slot. Use the stream as a context manager or finish iterating.
When you still cannot find the cause, run the same payload through curl, copy the X-Request-Id header from the response, and send both to support.
Errors, limits and retries
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. The maximum request body is 8 MB. Go over a limit and the API answers HTTP 429 with an error code that tells you which one:
rate_limited: too many requests per minute. Slow the loop or spread the work.concurrency: too many requests at once. Cap your worker pool at 8 (or 2 on a trial key).- A 429 with
Retry-After: 5is a temporary overload. Wait the five seconds and send it again.
The OpenAI SDKs retry some failures by themselves. You can raise or lower that with the max_retries client option. For batch jobs, a simple semaphore sized to your concurrency limit works better than relying on retries. Failed or refused requests are not charged, so a retried call does not double-bill you.
Next steps: the docs quickstart covers the first request in five minutes, and the pricing page lists the per-token rates, $0.15 per 1M input and $0.50 per 1M output. Prompts are not used for training. The one fixed rule on content is that nothing involving minors in a sexual context is ever allowed.
More guides
Questions and answers
What do I change to use the OpenAI SDK with this API?
Three values: the base URL (https://api.openainsfw.cc/v1), your API key, and the model ID uncensored. Everything else in your OpenAI code, including streaming and tools, stays as it is.
Which endpoints are available?
POST /v1/chat/completions for chat and GET /v1/models to list the model. There is no image, audio or embeddings endpoint.
Does it support streaming and function calling?
Yes. Streaming works over SSE with stream: true, and tool calling uses tools, tool_choice and role tool messages as in the OpenAI API. JSON mode is supported through response_format.
How large can a prompt be?
The context window is 100,000 tokens for prompt plus completion, and the request body can be up to 8 MB.
What happens when I hit a rate limit?
You get HTTP 429 with the error code rate_limited or concurrency. On temporary overload the 429 also includes a Retry-After: 5 header.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.