Step 1: install the SDK and set the key
The service speaks the OpenAI chat completions protocol, so you do not need a special client. Install the official package and keep the key in an environment variable, never in source code.
pip install openai
export API_KEY="paste-your-key-here"
curl https://api.apertus.top/v1/models -H "Authorization: Bearer $API_KEY"
curl https://api.apertus.top/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
-d '{"model":"uncensored","messages":[{"role":"user","content":"ping"}]}'
The GET /v1/models call is the quickest way to confirm the key works, and the second call sends a one-word test chat. If you do not have a key yet, create one here. New users can claim $0.50 of trial credit with one click on the key page. It needs no card and is valid for 7 days.
Use a virtual environment (python -m venv .venv) so the package version stays pinned to the project. If you work in a notebook, set the variable before you start the kernel, or read it with getpass so it never lands in the saved file.
Step 2: send your first request
Point the client at the base URL and pass uncensored as the model. The rest is the same code you would write for any hosted LLM.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.apertus.top/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain what a context window is in two sentences."},
],
temperature=0.7,
max_tokens=200,
)
print(resp.choices[0].message.content)
print(resp.usage)
Three details help from the start. The messages list is the whole conversation, so the model only knows what you send. max_tokens is optional; leave it out and the reply can use the rest of the 100,000-token window. And resp.usage shows the tokens you were billed for, which is how you check costs while you build. The same endpoint also accepts seed, stop, top_p and the frequency and presence penalties.
Step 3: keep a conversation going
An LLM has no memory between calls. To build a chat, store each message and resend the list. This small loop keeps the history in a Python list:
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
history = [{"role": "system", "content": "Answer briefly."}]
while True:
text = input("you: ")
if text in ("q", "quit"):
break
history.append({"role": "user", "content": text})
resp = client.chat.completions.create(model="uncensored", messages=history)
answer = resp.choices[0].message.content
history.append({"role": "assistant", "content": answer})
print("llm:", answer)
Because each call resends the history, input tokens grow with every turn. For long sessions, drop or summarize old messages before the list nears the context limit.
A useful habit is to log resp.usage.prompt_tokens on every turn. You will see the number climb by roughly the length of each exchange, which tells you when trimming is due.
Step 4: stream the answer
Streaming prints words as they arrive, which feels faster in a terminal or a web UI. Set stream=True and iterate over the chunks. The stream uses server-sent events and ends with usage data.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "List five uses of a hash map."}],
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()
One rule to remember: a streamed request occupies one of your concurrent slots until the stream finishes, so always consume or close the stream.
Step 5: get JSON and call tools
JSON mode
When a program, not a person, reads the output, set response_format and describe the shape you want in the prompt.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[{"role": "user", "content":
'Return JSON with keys "title" and "tags" (a list) for a post about Python generators.'}],
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])
Tool calling
Pass tools and the model can ask your code to run a function. You run it and send back the result as a role: "tool" message.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
tools = [{"type": "function", "function": {
"name": "add",
"description": "Add two numbers",
"parameters": {"type": "object",
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
"required": ["a", "b"]}}}]
messages = [{"role": "user", "content": "What is 17.5 plus 24.25?"}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)
messages.append(first.choices[0].message.model_dump(exclude_none=True))
messages.append({"role": "tool", "tool_call_id": call.id, "content": str(args["a"] + args["b"])})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
In real code, check that tool_calls is not empty before indexing it. The model may answer directly.
Step 6: handle errors and rate limits
A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. Past that, the API returns HTTP 429 with the code rate_limited (too many per minute) or concurrency (too many at once). On temporary overload it also sends 429 with Retry-After: 5. The SDK raises RateLimitError, so wrap calls in a short retry loop.
import os, time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
def ask(prompt, tries=5):
for attempt in range(tries):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}])
return r.choices[0].message.content
except RateLimitError:
wait = 5 * (attempt + 1)
print("429, retrying in", wait, "s")
time.sleep(wait)
raise RuntimeError("gave up after retries")
print(ask("Name three Python web frameworks."))
For batch jobs, use a thread pool capped at 8 workers (2 on the trial key) so you stay under the concurrency limit instead of relying on retries. Responses also carry X-Request-Id and X-Balance-USD headers, handy for logs and for watching your balance. The docs list every parameter, and the XAI API page gives another OpenAI-compatible overview.
Async code and common errors
For web servers and many parallel calls, use the async client from the same package. It takes the same arguments and keeps a semaphore-sized pool of requests in flight, so you can stay under the concurrency limit.
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
sem = asyncio.Semaphore(8)
async def ask(prompt):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}])
return r.choices[0].message.content
async def main():
prompts = [f"Give one tip about Python, number {i}." for i in range(20)]
answers = await asyncio.gather(*(ask(p) for p in prompts))
print(len(answers), "answers")
asyncio.run(main())
If something fails, check these first:
- KeyError on API_KEY. The variable is not set in the shell that runs Python. Export it again or load it from a file.
- 404 or a connection error. The base URL is missing the
/v1suffix or has a typo. - Authentication error. The key has a stray space or newline, or you are sending it as the wrong header. The SDK sets
Authorization: Bearerfor you. - Model not found. The model ID is
uncensored, in lowercase. - Empty or cut-off reply. You set
max_tokenstoo low. Remove it or raise it.
What a script costs
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit with no subscription. Say a script classifies 1,000 support messages, sending about 500 input tokens and getting about 200 output tokens each.
- Input: 1,000 × 500 = 500,000 tokens × $0.15 / 1M = $0.075.
- Output: 1,000 × 200 = 200,000 tokens × $0.50 / 1M = $0.10.
- Total: $0.175.
Failed or refused requests are not charged, and credit never expires. Top-ups are any whole amount from $20 to $500, by crypto (USDT on TRC20, USDC on Base), with a bonus of 5% from $50, 10% from $100 and 15% from $200. Prompts are not used for training. See the pricing page for details.
