EN ▾
Get API key
https://api.sdxlnsfw.cc/v1 $0.15 per 1M input tokens$0.50 Output tokens / 1M100,000 token context

Build a Roleplay Text Based Generator with an LLM API

A roleplay text based generator is a small loop: keep a character sheet, keep the history, send both to a model, show the reply. This guide builds one in Python against an OpenAI-compatible endpoint that does not refuse fiction for lawful adult use.

Updated

Stage with floating speech bubbles around a lantern, representing a looping roleplay text generator

What the generator needs

Most roleplay tools look complicated from the outside and turn out to be four parts. A character card says who the model plays. A scene state says where and when. A history holds what was said. And a caller turns all three into a request and prints the answer. The model keeps no memory between calls, so every turn you send everything it needs to stay in character.

For a generator that runs on your own code, the API choice matters for one reason above others: refusals. Mainstream hosted models often break character or decline themes that are ordinary in fiction, such as violence in a war story or romance between adult characters. The model behind this API is tuned to answer without content refusals for lawful adult use, so the story keeps moving. It is one open-weight model, run by an independent provider, and it only generates text.

Everything below works with any OpenAI SDK. You change the base URL to https://api.sdxlnsfw.cc/v1, use the key from the API key page and set the model to uncensored.

A minimal version in under 50 lines

This script runs a terminal roleplay. It streams the reply, appends both sides to the history and loops until you type /quit.

from openai import OpenAI

client = OpenAI(base_url="https://api.sdxlnsfw.cc/v1", api_key="YOUR_KEY")

SYSTEM = '''You are Mara, a weary harbor pilot in a fantasy port city.
Stay in character. Write in third person, past tense, 2 to 4 short paragraphs.
Never speak or act for the user's character. End on an open moment the user can answer.'''

history = [{"role": "system", "content": SYSTEM}]

while True:
    user = input("> ")
    if user.strip() == "/quit":
        break
    history.append({"role": "user", "content": user})

    stream = client.chat.completions.create(
        model="uncensored",
        messages=history,
        temperature=0.9,
        top_p=0.95,
        frequency_penalty=0.3,
        stream=True,
    )

    reply = ""
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            piece = chunk.choices[0].delta.content
            reply += piece
            print(piece, end="", flush=True)
    print()
    history.append({"role": "assistant", "content": reply})

That is a complete generator. The rest of this guide is about making it hold up over a long session and a real user base.

Write the system prompt like a character sheet

The system prompt does most of the work. A vague one, such as "be a pirate", produces generic output. A useful one fixes five things:

  • Identity and voice. Name, job, a habit of speech, one thing the character wants and one thing they hide.
  • Format. Person, tense, paragraph count. Models follow length rules better when you give a number.
  • Boundaries of control. Say plainly that the model never writes the user's actions or thoughts.
  • Setting rules. Things that are true in this world: magic costs something, the city has curfew, the ship has no radio.
  • Exit lines. What to do on an out-of-character request, for example text in double parentheses.

Put the stable facts first and keep them short. A 300-word card works better than a 3,000-word lore dump, because small details at the top of a long prompt get diluted. If the lore is large, store it in a file and inject only the entries relevant to the current scene.

For adult-oriented products, state the age rule in your own terms of use and in the card. Sexual content involving minors is a hard limit of this service and is never allowed, whatever the framing.

Keep the history under control

The window is 100,000 tokens for prompt and completion together. That is a lot of story, but you do not want to resend all of it every turn. Cost per turn is the full prompt, so a session that runs for hours gets more expensive and slower near the end.

A simple trimming rule is enough for most projects:

  1. Always keep the system message.
  2. Keep the last 20 to 30 messages verbatim.
  3. Replace everything older with a summary, written by the same model.

The summary call is just another request. Send the old messages with an instruction such as "Summarize this scene in 150 words. Keep names, promises, injuries and open threads." Insert the result as a second system message after the card. Update it every 15 or so turns.

def compress(history, keep=24):
    head, body = history[0], history[1:]
    if len(body) <= keep:
        return history
    old, recent = body[:-keep], body[-keep:]
    text = "\n".join(f"{m['role']}: {m['content']}" for m in old)
    s = client.chat.completions.create(
        model="uncensored",
        messages=[
            {"role": "system", "content": "Summarize this roleplay in 150 words. Keep names, promises, injuries, open threads."},
            {"role": "user", "content": text},
        ],
        max_tokens=300,
    )
    note = {"role": "system", "content": "Story so far: " + s.choices[0].message.content}
    return [head, note] + recent

What a session costs

Take a session of 60 turns. Assume the average prompt is 6,000 tokens, because the history grows, and each reply is 250 tokens.

  • Input: 60 × 6,000 = 360,000 tokens, at $0.15 per 1M = $0.054.
  • Output: 60 × 250 = 15,000 tokens, at $0.50 per 1M = $0.0075.
  • Total: $0.0615, a little over six cents.

With the trimming rule above, the average prompt stays closer to 3,000 tokens, which halves the input part. A $20 top-up covers over 300 sessions of the first kind: 20 divided by 0.0615 is about 325. The pricing page lists the bonus on larger top-ups, and the trial gives you $0.50 to try all of this first, enough for about eight sessions of that size.

Payment on this site is crypto only, in USDT on TRC20 or USDC on Base. Failed or refused requests are not charged.

Settings that keep characters in voice

Sampling settings change the feel of a story more than most people expect. These are good starting points; adjust them in small steps.

SettingStart atEffect
temperature0.8 to 1.0Higher gives livelier prose and more risk of drift.
top_p0.9 to 0.95Cuts the unlikely tail of word choices.
frequency_penalty0.2 to 0.5Reduces repeated phrases across a long scene.
presence_penalty0 to 0.3Nudges the story toward new topics.
stopa user name tagPrevents the model from writing the user's next line.

All of these are passed through to the model. If a character starts to sound like everyone else, lower the temperature and tighten the voice line in the card. If replies loop on the same sentence openings, raise the frequency penalty. A fixed seed helps when you compare two versions of a prompt on the same input.

Test your prompts before users do

A character that works in your first three messages can fall apart at message forty. Build a small test script that replays the same fixed conversation against each version of your system prompt, with a set seed and the same sampling settings. Read the outputs side by side. You are looking for four things: does the voice stay stable, does the model ever write the user's lines, does the length rule hold, and does the last paragraph leave the user something to answer.

Add a few hostile inputs to the test set. A user who types a one-word message, a user who pastes a whole page, and a user who tries to make the model break its character with an out-of-character request are all normal. Decide in advance what you want to happen in each case, and write that into the card. For example, "If the user writes in double parentheses, answer briefly out of character, then return to the scene."

Keep test runs cheap. Limit each reply with max_tokens to 300 and run a dozen prompts. At 6,000 input tokens and 300 output tokens, one test reply costs 6,000 × 0.15 + 300 × 0.50 = 1,050 millionths of a dollar, so a hundred of them cost about ten cents.

Ship it: streaming, limits and errors

For a web or Discord front end, keep stream: true. Users see text after a moment instead of waiting for a full reply. A streamed request occupies its concurrency slot until the stream ends, and a full key allows 8 concurrent requests and 300 requests per minute. A bot serving many channels needs a small queue, or one worker per slot.

When you exceed a limit the API returns HTTP 429 with the code rate_limited or concurrency. On temporary overload it returns 429 with Retry-After: 5. Honor that header and retry once or twice with a short pause. The docs list the headers, including X-Request-Id, which is worth logging for support questions on the support page.

Two last points. Do not put your key in browser code; call the API from a server. And tell your users what the service does with their text: prompts are not used for training here, and your own privacy page should say what you store.

Questions and answers

Does the model stay in character over long sessions?

Mostly, if you keep the character card at the top, trim old history into a short summary and avoid very long prompts. The window is 100,000 tokens, but shorter prompts are cheaper and tend to stay more focused.

Can I use this with SillyTavern or other front ends?

Front ends that accept an OpenAI-compatible endpoint can use it. Enter the base URL https://api.sdxlnsfw.cc/v1, your key and the model name uncensored.

Does it generate images for the scene?

No. The service is text only. You can pair it with a separate image tool, but images are not part of this API.

Is any content off limits?

Yes. Sexual content involving minors is never allowed. Other lawful adult fiction is the intended use.

Your key is one form away

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

Key points

  • The core is a system prompt, a message list and one chat completions call per turn.
  • Trim history to a token budget; the window is 100,000 tokens, but cost grows with every resent turn.
  • A 60-turn session with about 6,000 input tokens per turn costs roughly $0.06.
  • Stream replies, mind the concurrency limit, and keep the hard rule: nothing involving minors.

Start with trial credit

Email and password, key on screen right away.