Quick start with curl
The smallest working JSON mode request looks like this. It uses the base URL https://api.uncensoredllmapi.com/v1, the model uncensored, and your key as a bearer token:
curl https://api.uncensoredllmapi.com/v1/chat/completions -H "Authorization: Bearer $UNCENSORED_API_KEY" -H "Content-Type: application/json" -d '{
"model": "uncensored",
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": "Reply only with a JSON object."},
{"role": "user", "content": "Create a tavern NPC with keys name, trade and rumour."}
]
}'
The assistant message in choices[0].message.content is a string containing a JSON object. You still have to parse it yourself. Do not skip the instruction in the prompt: JSON mode constrains the output to be an object, but it cannot guess which keys you want. Naming the keys, and ideally showing a one-line example, is what gives you a stable shape.
If you do not have a key yet, the API key page hands out $0.50 of trial credit with one click after sign-up. That credit needs no payment, lasts 7 days and is limited to one per person.
JSON mode in Python with validation
Treat model output like any other external input. Parse it, check it against a schema, and retry a limited number of times if it fails. Pydantic makes this short:
import json, os
from openai import OpenAI
from pydantic import BaseModel, ValidationError
client = OpenAI(
base_url="https://api.uncensoredllmapi.com/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
class Npc(BaseModel):
name: str
trade: str
rumour: str
SYSTEM = (
"Reply only with a JSON object with exactly these keys: "
"name, trade, rumour. Each value is a string."
)
def make_npc(setting, tries=3):
for _ in range(tries):
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"Setting: {setting}"},
],
temperature=0.7,
max_tokens=300,
)
choice = r.choices[0]
if choice.finish_reason == "length":
continue # cut off, so the JSON is incomplete
try:
return Npc(**json.loads(choice.message.content))
except (json.JSONDecodeError, ValidationError, TypeError):
continue
raise RuntimeError("no valid JSON after retries")
print(make_npc("a river port in a plague year"))
Three habits in that snippet are worth copying. The code checks finish_reason before parsing, because a reply that stops at max_tokens ends mid-object. It uses a moderate temperature, since high temperatures make malformed output more likely. And it caps retries, so a bad prompt cannot spin forever. Since failed or refused requests are not charged, the retry budget is a latency question rather than a cost one.
Common JSON mode mistakes
- Asking for JSON in the prompt but not in
response_format. The model will often comply, but it may wrap the object in prose or a code fence. Set both. - Setting
max_tokenstoo low. Estimate the longest valid answer and add margin. A long list of items can easily exceed 300 tokens. - Expecting a top-level array. JSON mode asks for an object. If you need a list, ask for
{"items": [...]}. - Stacking a stop sequence that appears in the JSON. The
stopparameter is passed through, and a stop string that appears inside a value will cut the reply short. - Using JSON mode with streaming and parsing each chunk. Collect the whole text first, then parse once at the end.
Sampling settings such as temperature, top_p, seed and the penalties are passed through. For extraction tasks, a low temperature around 0.2 and a fixed seed give the most repeatable output. For creative generation like the NPC above, a higher value is fine as long as you validate.
Tool calling: the full loop
Tool calling lets the model ask your code to do something and then continue with the result. The flow has four steps: you declare tools, the model replies with tool_calls, you run them, and you send the results back as messages with role: "tool".
import json, os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredllmapi.com/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
tools = [{
"type": "function",
"function": {
"name": "lookup_inventory",
"description": "Return the stock count for an item in the shop.",
"parameters": {
"type": "object",
"properties": {"item": {"type": "string"}},
"required": ["item"],
},
},
}]
def lookup_inventory(item):
stock = {"healing potion": 4, "rope": 12}
return {"item": item, "count": stock.get(item.lower(), 0)}
messages = [{"role": "user", "content": "Do you still have healing potions?"}]
for _ in range(4): # hard cap on tool rounds
r = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = r.choices[0].message
if not msg.tool_calls:
print(msg.content)
break
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = lookup_inventory(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
The arguments arrive as a JSON string, which you must parse, and the model can occasionally produce arguments that do not match your schema. Validate them before running anything with side effects. Never pass them to a shell, a SQL string or a file path without checks.
The tool_choice field lets you steer behaviour. Leave it at "auto" and the model decides. Name a specific function to force a call, which is useful when you want structured extraction through a tool schema instead of JSON mode.
Streaming tool calls in Node
With stream: true, tool calls arrive in pieces. Each chunk carries a fragment of the function name or the arguments string, indexed by position. You have to concatenate the fragments per index and parse only when the stream ends.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredllmapi.com/v1",
apiKey: process.env.UNCENSORED_API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
stream: true,
messages: [{ role: "user", content: "Check stock for rope." }],
tools: [{
type: "function",
function: {
name: "lookup_inventory",
description: "Return the stock count for an item.",
parameters: {
type: "object",
properties: { item: { type: "string" } },
required: ["item"],
},
},
}],
});
const calls = [];
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta;
for (const tc of delta?.tool_calls ?? []) {
const slot = (calls[tc.index] ??= { id: "", name: "", args: "" });
if (tc.id) slot.id = tc.id;
if (tc.function?.name) slot.name += tc.function.name;
if (tc.function?.arguments) slot.args += tc.function.arguments;
}
}
for (const c of calls) {
console.log(c.name, JSON.parse(c.args));
}
Remember that a streamed request holds one of your concurrency slots until the stream ends. A full key allows 8 concurrent requests and 300 per minute, a trial key 2 and 60. Hitting either gives HTTP 429 with the code concurrency or rate_limited. Usage totals are reported at the end of the stream, which is handy for logging cost.
JSON mode or a tool schema
Both give you structured data, so which one should you use? The deciding question is whether the model is producing data or choosing an action.
Use JSON mode when the output itself is the product: an NPC sheet, a list of tags, a classification with a confidence field. You control the whole prompt, you get one object back, and there is one request to pay for.
Use tools when the model has to decide whether to act, or when several different actions are possible. A schema per function documents the contract, tool_choice lets you force or allow a call, and the loop in the previous section handles multi-step work. The cost is an extra request per round, plus the tool definitions counted as input every time.
A practical middle path for extraction: declare one tool whose parameters are the fields you want, and set tool_choice to that function. You get argument JSON that follows your schema's shape without writing the key list into the prompt. Either way, validate the result before you trust it, and log the X-Request-Id value of any request that produced something unexpected.
What it costs
JSON and tool calls are billed like any other tokens: $0.15 per 1M input and $0.50 per 1M output. Tool definitions count as input on every request, and each tool result you send back adds to the next request's input.
Example: a tool-using assistant turn with a 600-token tool schema and prompt, a 150-token model call, then a second request containing 900 input tokens (the prior messages plus a tool result) and a 200-token reply.
- Request one: 600 input and 150 output. Input 600 x $0.15 / 1M = $0.00009. Output 150 x $0.50 / 1M = $0.000075. Subtotal $0.000165.
- Request two: 900 input and 200 output. Input 900 x $0.15 / 1M = $0.000135. Output 200 x $0.50 / 1M = $0.0001. Subtotal $0.000235.
- Total for the turn: $0.0004.
At that rate 1,000 turns cost $0.40. Credit is prepaid in whole amounts from $20 to $500 (bonus: +5% from $50, +10% from $100, +15% from $200), paid in crypto with USDT on TRC20 or USDC on Base. See the pricing page for current figures.
Where to go next
Reference for every request field is in the API documentation. If you are preparing an application for real traffic, the production checklist is the next page to read, and support can help if a request behaves unexpectedly. Keep your request ID, which comes back in the X-Request-Id header, to hand.
The service is text only and the context window is 100,000 tokens, including your tool definitions and results. Sexual content involving minors is not allowed, and that applies to structured and tool-driven output exactly as it does to plain chat.
