EN ▾
Get API key
Get API key

API for Roleplay: Streaming, Tools and JSON Mode

Most roleplay apps start as a chat box and grow into something with dice, inventories and scene state. These are the API features that make that growth possible, with code you can run.

Updated:

Glowing dice, data streams and a light chest on a folding screen, representing roleplay API features

Key points

  • Streaming over SSE makes long replies feel instant.
  • Tool calling lets the model ask your code to roll dice or read a character sheet.
  • JSON mode returns machine-readable scene state for your UI.
  • Context is 100,000 tokens, with 8 concurrent requests and 300 per minute on a full key.

Features and what they do for a story

If you are choosing an api for roleplay, the feature list matters less than what each item lets you build. Here is the map for this one, which is OpenAI-compatible at https://api.roleplayapi.com/v1 with the model ID uncensored.

FeatureRoleplay use
Streaming (SSE)Text appears as it is written, so a long scene does not feel stalled
Tool callingDice rolls, inventory lookups, relationship scores, rule checks
JSON modeStructured scene state: location, mood, items, who is present
seed, temperature, top_p, penaltiesRepeatable tests and tuned character voice
100,000-token contextLong campaigns without constant trimming

It is a text API only. There is no image, audio or video generation, no embeddings and no fine-tuning, so plan those parts of your product elsewhere. The quickstart docs cover the basic request shape.

Streaming replies

Set stream: true and the response arrives as server-sent events. Each chunk carries a small delta of text, and usage arrives at the end.

from openai import OpenAI

client = OpenAI(
    base_url="https://api.roleplayapi.com/v1",
    api_key="YOUR_API_KEY",
)

stream = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are the narrator of a harbor mystery."},
        {"role": "user", "content": "I push open the door of the net loft."},
    ],
    stream=True,
    temperature=0.9,
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
print()

In a web front end, forward these deltas to the browser over your own SSE or WebSocket channel. In a terminal or bot, print or collect them as shown. If you only need the final text, drop the flag and read choices[0].message.content.

Tool calling for dice and rules

Language models are poor random number generators and worse at keeping score. Hand those jobs to code. You declare a function, the model decides when to call it, your code runs it, and you return the result as a role: "tool" message.

import json
import random
from openai import OpenAI

client = OpenAI(
    base_url="https://api.roleplayapi.com/v1",
    api_key="YOUR_API_KEY",
)

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll dice in NdS notation, for example 2d6, when an action is uncertain.",
        "parameters": {
            "type": "object",
            "properties": {"notation": {"type": "string"}},
            "required": ["notation"],
        },
    },
}]


def roll_dice(notation):
    count, sides = notation.lower().split("d")
    rolls = [random.randint(1, int(sides)) for _ in range(int(count or 1))]
    return json.dumps({"rolls": rolls, "total": sum(rolls)})


messages = [
    {"role": "system", "content": "You are a game master. Use roll_dice for any risky action."},
    {"role": "user", "content": "I try to jump the gap between the rooftops."},
]

first = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
reply = first.choices[0].message

if reply.tool_calls:
    messages.append(reply)
    for call in reply.tool_calls:
        args = json.loads(call.function.arguments)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": roll_dice(**args),
        })
    final = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools
    )
    print(final.choices[0].message.content)
else:
    print(reply.content)

Two practical notes. First, validate the arguments: a model can send "d20" or "2d", so wrap the parser in a try block and return an error string instead of crashing. Second, when you stream, tool calls also arrive in pieces. Join the argument fragments by their index before calling json.loads.

JSON mode for scene state

A UI wants fields, not paragraphs. With response_format: {"type": "json_object"} the model returns a valid JSON object. Mention JSON in the prompt as well, and describe the keys you expect.

import json
from openai import OpenAI

client = OpenAI(
    base_url="https://api.roleplayapi.com/v1",
    api_key="YOUR_API_KEY",
)

scene = "Maren wipes the bar, watching the door. Rain on the windows. Two strangers whisper in the corner."

result = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Return JSON with keys: location, time_of_day, mood, characters_present (list)."},
        {"role": "user", "content": scene},
    ],
    temperature=0.2,
)

state = json.loads(result.choices[0].message.content)
print(state["mood"], state["characters_present"])

A common design uses two calls per turn: one streamed call writes the story text for the player, and a second low-temperature JSON call updates the state shown in the sidebar. At these prices the second call costs little.

Sampling controls and repeatable tests

The API passes temperature, top_p, stop, seed and the repetition penalties through to the model. For storytelling, a temperature near 0.9 gives variety. For state extraction, go to 0.2 or lower. Use stop to cut the output when the model starts to speak for the player, for example at the player's name plus a colon.

When you are tuning a character prompt, fix the seed and change one thing at a time. Without a fixed seed, you cannot tell whether a better reply came from your edit or from luck.

Putting it together: one turn of a game

A typical turn in an app built on these features follows the same order every time, and it helps to write it down before coding.

  1. Receive the player's action. Add it to the message list.
  2. Ask the model for a reply with tools enabled. If it returns a tool call, run it in your code and send the result back as a role: "tool" message. Loop until the model answers in plain text. Cap the loop at three or four rounds, in case it keeps calling.
  3. Stream the final text to the player. The tool rounds should not be streamed. Only the last answer matters to the reader.
  4. Run the state call. Send the new scene text to a low-temperature JSON request and store the result.
  5. Trim the history. Drop old messages, or replace them with a summary, before the next turn.

Keep game rules in code, not in the prompt. If a rule says a character with 0 health cannot act, check it in your program and tell the model the outcome. A prompt can be argued with by a persuasive player; a function cannot.

Handle failure paths as well. A rate limit response means you should wait and retry. A malformed tool argument means you should send the error text back as the tool result, so the model can correct itself. A truncated reply usually means max_tokens was set too low. None of these are charged when the request itself fails, so retries are cheap.

Limits and cost for a roleplay app

A full key allows 8 concurrent requests and 300 per minute; the trial key allows 2 and 60. If you run an app for many players, put a queue in front of the API and keep each player to one request in flight. Context is 100,000 tokens including the completion, and the maximum body is 8 MB.

Price is $0.15 per 1M input tokens and $0.50 per 1M output tokens. A turn with 4,000 prompt tokens and a 300-token reply costs:

  • Input: 4,000 × $0.15 / 1,000,000 = $0.0006
  • Output: 300 × $0.50 / 1,000,000 = $0.00015
  • Total: $0.00075

That is $0.75 per 1,000 turns. Add a 150-token JSON state call with a 1,500-token prompt and the extra cost is $0.000225 plus $0.000075, about $0.0003. Failed or refused requests are not charged.

Top-ups run from $20 to $500 by crypto (USDT on TRC20, USDC on Base), with +5% from $50, +10% from $100 and +15% from $200. Details sit on the pricing page, and you can claim $0.50 of trial credit with one click on the API key page after sign-up.

Scope and content rules

The model is a single open-weight model run by an independent provider, tuned to answer without content refusals for lawful adult use. It is not an official API of any other vendor. Sexual content involving minors is never allowed, and prompts are not used for training. If you came looking for Grok, the Grok API uncensored integration guide covers that topic; this service is not the official API of xAI or any other vendor.

Questions and answers

Does the API support tool calling with streaming?

Yes. Streamed responses include tool_calls in pieces, and you join the argument fragments before parsing them as JSON.

How do I get structured output?

Set response_format to {"type": "json_object"} and describe the keys you want in the prompt.

How much memory can a story have?

The context window is 100,000 tokens for prompt plus completion. Most apps send far less to keep each turn cheap.

Can I use the OpenAI SDK?

Yes. Change the base URL to https://api.roleplayapi.com/v1, use your key, and set the model to uncensored.

Your key is one form away

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