No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).
Get API keyThe shortest working example
To run an llm model in python without managing GPUs, you call a hosted endpoint from the official OpenAI SDK. This API is OpenAI-compatible, so the only changes from a standard OpenAI script are the base URL, your key, and the model ID uncensored. The model is one open-weight text model run by an independent provider, tuned to answer without content refusals for lawful adult use.
Install the SDK with pip install openai and put your key in an environment variable named API_KEY.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.ltxnsfw.top/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Give me three names for a fictional port city."}],
)
print(resp.choices[0].message.content)
print(resp.usage)
If that prints text and a usage object, the connection works. You can get a key from the key page. New users can claim $0.50 of trial credit there with one click, valid for 7 days, and no payment details are needed.
Setting up the client properly
Keep the key out of your code. Read it from an environment variable or a secrets store, as above, and add any .env file to .gitignore. The endpoint accepts Authorization: Bearer <key>, which the SDK sends for you.
It is worth confirming which models the endpoint serves. The API implements GET /v1/models, so the SDK's list call works:
from openai import OpenAI
import os
client = OpenAI(base_url="https://api.ltxnsfw.top/v1", api_key=os.environ["API_KEY"])
for m in client.models.list():
print(m.id) # expect: uncensored
The API supports two methods: POST /v1/chat/completions and GET /v1/models. It has no embeddings, image, audio or fine-tuning endpoints, so code that calls those on the OpenAI client will fail here. Plan to keep another service for them.
Keeping a conversation
The API is stateless. The model remembers nothing between calls, so you send the conversation each time as a list of messages. A system message sets behavior, then user and assistant messages alternate.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.ltxnsfw.top/v1", api_key=os.environ["API_KEY"])
messages = [{"role": "system", "content": "You are a terse assistant for a fiction writer."}]
def ask(text):
messages.append({"role": "user", "content": text})
r = client.chat.completions.create(
model="uncensored",
messages=messages,
temperature=0.8,
top_p=0.95,
)
answer = r.choices[0].message.content
messages.append({"role": "assistant", "content": answer})
return answer
print(ask("Suggest a twist for a story about a lighthouse keeper."))
print(ask("Make it darker, but keep it to two sentences."))
Every call resends the whole list, so the input token count grows with each turn. The context window is 100,000 tokens for prompt plus completion, and you pay input rates on the history each time. Trim old turns or replace them with a short summary once a chat gets long. Sampling parameters such as temperature, top_p, stop, seed and the presence and frequency penalties are passed through to the model. Set seed when you want repeatable output while testing.
Streaming tokens as they arrive
For anything interactive, stream. The server sends chunks over SSE and the SDK exposes them as an iterator.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.ltxnsfw.top/v1", api_key=os.environ["API_KEY"])
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a 120 word scene set in a night market."}],
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", chunk.usage)
Usage is delivered at the end of the stream. One detail matters for concurrency: a streamed request holds its slot until the stream finishes. If your loop breaks early, close the stream so the slot is released.
Structured output and tool calls
When another program consumes the reply, ask for JSON mode. The reply content is a JSON string you can parse. Mention JSON in the prompt as well, and describe the fields you want.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.ltxnsfw.top/v1", api_key=os.environ["API_KEY"])
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply with JSON: {\"title\": str, \"tags\": [str]}"},
{"role": "user", "content": "Describe a story about a clockmaker."},
],
)
data = json.loads(r.choices[0].message.content)
print(data["title"], data["tags"])
Tool calling follows the OpenAI format. You describe functions in tools, the model answers with tool_calls, you run the function and return the result as a message with role: "tool".
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.ltxnsfw.top/v1", api_key=os.environ["API_KEY"])
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll a die with the given number of sides",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer"}},
"required": ["sides"],
},
},
}]
messages = [{"role": "user", "content": "Roll a twenty-sided die for me."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
result = {"value": 17} # run your real function here
messages.append(first.choices[0].message)
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)
Check that tool_calls is present before indexing it, since the model may answer directly. Arguments arrive as a JSON string, so run json.loads on them and handle bad JSON, because any LLM occasionally produces it.
Async batches within the limits
Batch jobs are where limits start to matter. A full key allows 8 concurrent requests and 300 requests per minute. The trial key allows 2 and 60. An asyncio semaphore keeps you inside the concurrency limit, and the SDK's retry setting covers short bursts.
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(
base_url="https://api.ltxnsfw.top/v1",
api_key=os.environ["API_KEY"],
max_retries=5,
)
sem = asyncio.Semaphore(8) # use 2 on a trial key
async def summarize(text):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Summarize in one sentence: " + text}],
max_tokens=80,
)
return r.choices[0].message.content, r.usage
async def main(items):
return await asyncio.gather(*(summarize(t) for t in items))
results = asyncio.run(main(["First text...", "Second text...", "Third text..."]))
for text, usage in results:
print(text, usage.total_tokens)
Pick the semaphore size from your key. Eight slots is the ceiling on a full key, and setting it to exactly eight leaves no room for a second script using the same key at the same time. If you run more than one job, give each a smaller share, for example four and four. Requests per minute is a separate limit of 300 on a full key and 60 on a trial key, so a very fast batch of tiny requests can hit it even with few requests in flight. In that case spread the calls out, or accept a few retries.
Over a limit the API returns HTTP 429. The error code rate_limited means too many requests per minute, and concurrency means too many at once. During temporary overload it also returns 429 with Retry-After: 5. The SDK retries 429 responses with backoff by default, a small number of times, and max_retries raises that. If you still hit the ceiling, lower the semaphore or add a pause between batches. Failed or refused requests are not charged.
Handling errors in your own code
Retries inside the SDK cover short problems. For everything else, catch exceptions and decide what to do. The SDK raises specific classes, and the rate limit one is the one you will meet first.
import os, time
import openai
from openai import OpenAI
client = OpenAI(base_url="https://api.ltxnsfw.top/v1", api_key=os.environ["API_KEY"], max_retries=0)
def complete(prompt, tries=4):
delay = 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 openai.RateLimitError:
time.sleep(delay) # Retry-After is 5 seconds on overload
delay *= 2
except openai.APIConnectionError:
time.sleep(2)
raise RuntimeError("gave up after %d tries" % tries)
print(complete("Name three fictional rivers."))
This wrapper disables the built-in retries so that your own loop is in charge. Pick one approach and stay with it, because stacking both multiplies your wait times. A 429 means slow down, not stop. Failed or refused requests are not charged, so retrying does not cost you extra for the failed attempts.
Problems that look like bugs
Some failures are not errors in your Python at all. A response that ends mid-sentence is often a max_tokens value that is too low. A long conversation that suddenly fails has probably outgrown the 100,000 token window. A script that works for one request and breaks under a thread pool has hit the concurrency limit. An 8 MB request body limit is rarely reached, but pasting whole files into prompts can get there. Print resp.usage and the X-Request-Id value when you debug, and you can usually tell which one you have.
Testing without surprises
Model output varies from run to run, which makes tests flaky. Pass a fixed seed and a low temperature in tests that compare text, and write assertions about structure instead of exact wording: the JSON parses, the required keys exist, the reply is shorter than a limit. Keep a small set of prompts as regression tests, and run them whenever you change your system message. Use the trial credit for this at first, since a hundred short test calls cost a fraction of a cent each.
It also helps to put the client behind one function in your own code. That way the base URL, key and model name live in a single place, and swapping or adding another provider later means editing one module rather than hunting through the project.
Counting the cost
Price is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. Every response carries a usage object, so cost is a one-line calculation. As an example, a script that makes 1,000 requests with 1,000 input and 300 output tokens each uses 1,000,000 input tokens ($0.15) and 300,000 output tokens ($0.15), so it costs $0.30 in total.
For a long job, keep a running total in your script: add the cost of each response to a counter and print it every hundred calls. It takes three lines, and it tells you early if a prompt change doubled your input size. With the trial credit of $0.50 you can run roughly 1,600 calls of that size before it is gone, which is more than enough to profile a new script.
The response headers include X-Request-Id for debugging and X-Balance-USD for your remaining credit, so you can stop a batch when the balance gets low. Top-ups start at $20, with a bonus from $50, and credit never expires. See the pricing page for tiers and the docs for the full parameter list. Prompts are not used for training, and the one content rule that cannot be changed is that nothing involving minors is allowed.
