EN ▾
Get API key

AI Roleplay Web Story: Build One With an Uncensored API

An ai roleplay web story is a page where a reader types an action and a model continues the scene. This article shows how to build one on an OpenAI-compatible uncensored API, with streaming, JSON state and honest cost numbers.

Updated

Stage with masks and a glowing book streaming light toward a browser window, picturing an AI story page

Key points

  • Stream the narration over SSE so text appears as it is written, and keep the story state in a separate JSON call.
  • JSON mode returns a parseable object, useful for inventory, location and relationship values that your page renders.
  • Tool calling lets the model ask your code for a dice roll or a database lookup instead of inventing the result.
  • A 3,000-token chapter with 8,000 tokens of context costs about $0.0027, so 100 chapters come to under $0.30.

What an AI roleplay web story needs

Strip away the branding and every AI story page does the same loop. The reader sends text. Your server builds a prompt from a system message, the story so far and the new input. A model writes the next passage. The page shows it, and you store the result so the next turn has memory.

That loop is one HTTP call to POST /v1/chat/completions, and the rest is your own code. The part that separates a good story engine from a frustrating one is the model. General-purpose assistants often refuse or soften dark themes in fiction: villains who stay in character, violence in a war story, grief, cruelty, morally grey choices. A model tuned to answer without content refusals for lawful adult use lets the author decide what the story is about. The one hard line is that sexual content involving minors is never allowed.

The service here is OpenAI-compatible, so you do not need a special SDK. Any OpenAI client works once you point it at https://api.uncensoredstory.cc/v1 and use the model uncensored. It is text only, which is all a story page needs. If you want covers or portraits, those come from another tool.

Streaming the narration

Readers will not stare at a blank box for fifteen seconds. Streaming sends the passage in small pieces over server-sent events, so the first words show up almost at once and the page feels alive. Set stream: true and read the chunks as they arrive. Usage is reported at the end of the stream, so you can log what each turn cost.

from openai import OpenAI

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

history = [
    {"role": "system", "content": "You narrate a gritty fantasy story in second person. "
                                  "Write 2 to 4 paragraphs, then stop and wait for the player."},
    {"role": "user", "content": "I push open the door of the smugglers' tavern."},
]

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

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)

history.append({"role": "assistant", "content": reply})

In a browser you forward those chunks from your server with your own SSE or WebSocket route. Never put the API key in front-end JavaScript, because anyone can read it. Keep it on the server and let the browser talk to your endpoint.

One detail matters for multi-user sites. A streamed request holds its concurrency slot until the stream ends. A full key allows 8 requests at once and 300 per minute, so if a hundred readers click at the same moment you need a small queue in front of the API rather than a wall of failures.

Keeping story state with JSON mode

Free text is good for prose and bad for game state. If your page shows a health bar, an inventory list or the name of the current location, you want those as fields, not as sentences you have to parse. JSON mode is the tool. Pass response_format: {"type": "json_object"} and describe the shape you want in the prompt.

# client = OpenAI(base_url="https://api.uncensoredstory.cc/v1", api_key="YOUR_KEY")
import json

state_prompt = '''Read the passage and the previous state. Reply with one JSON object:
{"location": string, "inventory": [string], "health": integer, "mood_of_npc": string}'''

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": state_prompt},
        {"role": "user", "content": json.dumps({"previous": state, "passage": reply})},
    ],
    response_format={"type": "json_object"},
    temperature=0.2,
)

state = json.loads(resp.choices[0].message.content)

Two habits make this reliable. First, use a low temperature for the state call. Creativity is wanted in the narration and unwanted in the bookkeeping. Second, wrap json.loads in a try block and retry once on failure, because any model can occasionally produce a broken object. A retry costs a fraction of a cent.

Genre also changes the settings. A horror story benefits from a lower temperature and a firm system message that tells the narrator to build dread slowly. A comedy wants more variety, so push temperature up a little. If a scene keeps repeating the same gestures, a small presence penalty usually helps more than a higher temperature. Seed is passed through as well, which is handy while you test: with the same seed and settings you can compare two versions of a system prompt on the same input.

Splitting the work into two calls, one streamed narration and one small JSON update, also keeps the story voice clean. The narrator never has to emit brackets or field names in the middle of a paragraph.

Tool calls for dice and lookups

Models are poor at randomness. Ask one to roll a die and the numbers cluster around favourites. If your story has skill checks, let the code roll and let the model react. Tool calling does exactly that: you describe a function, the model decides when to call it, and you return the result as a message with role: "tool".

# client = OpenAI(base_url="https://api.uncensoredstory.cc/v1", api_key="YOUR_KEY")
tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll dice for a skill check and return the total.",
        "parameters": {
            "type": "object",
            "properties": {"sides": {"type": "integer"}, "count": {"type": "integer"}},
            "required": ["sides"],
        },
    },
}]

first = client.chat.completions.create(
    model="uncensored", messages=history, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message
if msg.tool_calls:
    call = msg.tool_calls[0]
    # run your own random roll here, then send it back
    history.append(msg)
    history.append({"role": "tool", "tool_call_id": call.id, "content": "17"})
    final = client.chat.completions.create(model="uncensored", messages=history, tools=tools)

The same pattern works for a lorebook. Define a function that looks up a character or a place in your database, and the model asks for facts instead of guessing them. That keeps a long campaign consistent when the world has more detail than fits in the prompt.

Memory over a long story

The window is 100,000 tokens for prompt plus completion. That is room for a novel's worth of early chapters, but sending everything every time costs money and slows the story down. A practical plan has three layers.

  1. Fixed block. The system message with the world rules, tone and the character sheet. It goes first on every call.
  2. Summary. Every ten or twenty turns, ask the model to compress the older turns into a few hundred tokens and replace them with that summary.
  3. Recent turns. The last few exchanges word for word, so the voice and the immediate scene stay sharp.

Plan for the reader who walks away and comes back a week later. Store the full log, the summary and the latest state object in your database, keyed by story and user. When they return, rebuild the prompt from those three pieces and the story continues without any server-side session. Because the API itself keeps nothing between calls, this is the only memory the story has, so back it up like any other user data.

With a summary in place, a prompt of 8,000 tokens carries more story than 40,000 tokens of raw log. Keep a hard rule in the system message about what the model must not contradict, such as names, ages and who knows which secret. Models drift on small facts in long chats, and a short fact sheet at the top is the cheapest fix.

What a story costs to run

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, with no subscription. Suppose each chapter turn sends 8,000 tokens of context and gets back about 3,000 tokens of narration:

  • Input: 8,000 x $0.15 / 1,000,000 = $0.0012
  • Output: 3,000 x $0.50 / 1,000,000 = $0.0015
  • Total per chapter: $0.0027

A hundred chapters cost $0.27. Add a small JSON state call of 1,500 input and 150 output tokens per turn and you add $0.000225 + $0.000075 = $0.0003, so the full turn is $0.0030 and a hundred turns are $0.30. The $0.50 trial credit, valid for 7 days with no payment needed, is enough to build and test an entire prototype. Failed or refused requests are not charged.

When you go live, top-ups start at $20 and go up to $500 in any whole amount, with a bonus of +5% from $50, +10% from $100 and +15% from $200. Payment is by crypto (USDT on TRC20, USDC on Base), and the credit never expires. See pricing for the full table.

Practical advice before you launch

Add a content rule of your own on top of the model's freedom. Say in your terms that the site is for adults, and keep the minors rule in your own moderation as well. Rate limit each reader on your side so one person cannot use the whole 300-requests-per-minute budget. Log the X-Request-Id header for every call so you can trace a bad turn later, and watch X-Balance-USD so the site does not go dark at midnight.

Prompts are not used for training, but your own database still holds your readers' stories. Treat that data the way you would any private writing. To get started, create a key and run the first call from the quickstart. For a wider look at what to compare between providers, the checklist on uncensored model APIs is a good next read.

Questions and answers

Can I use this for a public interactive fiction site?

Yes, as long as the use is lawful and for adults. Keep the key on your server, add your own per-reader rate limits, and never allow sexual content involving minors.

Does JSON mode work together with streaming?

Both are supported. In practice it is easier to stream the narration in one call and use a separate non-streamed JSON call for state.

How long can one story passage be?

The completion can use whatever is left of the 100,000-token window after your prompt. The max_tokens parameter is optional, so set it only if you want a cap.

Is this the official API of a well-known model?

No. It is one open-weight model run by an independent provider, not a router and not an official vendor API.

Your key is one form away

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