Unfiltered AI for game NPC dialogue and interactive fiction
Keep game authority in the engine: store each NPC’s state, validate proposed tool calls and preserve the allowed story transitions. This guide applies those rules to generated dialogue and shows how to estimate token costs.

UpdatedUnfiltered AI
Key points
- Dedicated inference providers like Unfiltered AI offer consistent uncensored behavior on a single model, avoiding the randomness of aggregator routing.
- Aggregators like OpenRouter provide access to multiple models but may vary in how strictly they apply content filters depending on the specific model version.
- Unfiltered AI uses an open-weight model on dedicated hardware with a 100k context window, priced at $0.15/$0.50 per million tokens.
- For strict NSFW or roleplay consistency, a dedicated uncensored LLM API eliminates the need for complex prompt engineering to bypass generic filters.
The game loop, drawn in words
Hold this diagram in your head. A player line enters the engine. The engine composes a prompt from three parts: fixed instructions, the NPC's current state record, and the recent dialogue. The prompt goes to the model. The model answers with text, with tool calls, or with both. Text goes to the screen. Tool calls go back to the engine, which validates them, mutates the state record, and returns a short result string so the model can finish its sentence. Then the loop waits for the player.
The important property is that the engine is the single source of truth. The model proposes; the engine decides. If the model says a character hands over a key but never calls the tool, the key stays in the inventory. That separation is what makes generated dialogue safe to wire into a game with rules. Everything below follows from it.
All requests use the standard chat-completions endpoint at https://api.unfilteredaiapi.com/v1 with the model id uncensored. Tools use the OpenAI function-calling format, so the same code works with the official client libraries.
Scope and an adults-only note
Interactive fiction for mature audiences is a legitimate use. The service does not refuse lawful adult content, dark themes or controversial subjects in fiction. It is meant for adults aged 18 and over, and your game should say so on its store page and gate access accordingly.
One line is fixed: sexual content involving minors is always blocked with a 403, in fiction and roleplay alike. Design for that explicitly. Give every character an adult age in the state record, and make your engine handle a 403 gracefully by ending the exchange rather than retrying.
Structured NPC state
Free-form character descriptions drift. A compact structured record does not. Keep it small, put it in the system message on every turn, and label it authoritative so the model treats it as fact rather than suggestion.
{
"name": "Brannoch",
"role": "ferry smuggler",
"mood": "wary",
"trust": 1,
"inventory": ["brass key", "flask of rum"],
"knows": ["the harbourmaster takes bribes", "a tunnel runs under the salt warehouse"],
"will_never": ["name his employer", "leave the dock before dawn"],
"location": "Gull Quay, pre-dawn"
}Each field earns its place. mood and trust steer tone. inventory bounds what can be given. knows limits what the NPC can reveal, so players cannot extract plot points the character has no reason to hold. will_never is a short list of hard refusals that give the character a spine. At roughly 120 tokens, the whole record costs almost nothing per turn.
Tool calls for game actions
Tools turn prose into state changes. The three below cover most dialogue-driven mechanics: shifting trust, transferring an item, and presenting choices. Notice that apply_tool clamps trust and rejects items the NPC does not hold; validation lives in code.
import json
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.unfilteredaiapi.com/v1", api_key=os.environ["API_KEY"])
TOOLS = [
{"type": "function", "function": {
"name": "adjust_trust",
"description": "Change how much this NPC trusts the player after what was just said.",
"parameters": {"type": "object", "properties": {
"delta": {"type": "integer", "minimum": -2, "maximum": 2},
"reason": {"type": "string"}},
"required": ["delta"]}}},
{"type": "function", "function": {
"name": "give_item",
"description": "Hand an item from the NPC's inventory to the player.",
"parameters": {"type": "object", "properties": {
"item": {"type": "string"}}, "required": ["item"]}}},
{"type": "function", "function": {
"name": "offer_choices",
"description": "Present up to three short dialogue options for the player to pick from.",
"parameters": {"type": "object", "properties": {
"choices": {"type": "array", "items": {"type": "string"}, "maxItems": 3}},
"required": ["choices"]}}},
]
def apply_tool(name, args, state, out):
if name == "adjust_trust":
state["trust"] = max(-3, min(5, state["trust"] + int(args.get("delta", 0))))
return f"trust is now {state['trust']}"
if name == "give_item":
item = args.get("item")
if item in state["inventory"]:
state["inventory"].remove(item)
out["items"].append(item)
return f"gave {item}"
return "refused: item not in inventory" # the engine, not the model, decides
if name == "offer_choices":
out["choices"] = args.get("choices", [])[:3]
return "choices shown"
return "unknown tool"
def npc_turn(state, history, player_line):
system = {"role": "system", "content": (
"You voice one NPC in an adults-only interactive story. Stay in character, "
"at most 80 words per reply, no narration of the player's actions. "
"Use tools for anything that changes the game; never claim an item was given without calling give_item.\n"
"NPC state (authoritative): " + json.dumps(state))}
history.append({"role": "user", "content": player_line})
out = {"text": "", "items": [], "choices": []}
for _ in range(4): # cap tool-call rounds
r = client.chat.completions.create(
model="uncensored", messages=[system] + history, tools=TOOLS,
temperature=0.8, max_tokens=300)
msg = r.choices[0].message
entry = {"role": "assistant", "content": msg.content}
if msg.tool_calls:
entry["tool_calls"] = [{"id": c.id, "type": "function",
"function": {"name": c.function.name, "arguments": c.function.arguments}}
for c in msg.tool_calls]
history.append(entry)
if msg.content:
out["text"] += msg.content
if not msg.tool_calls:
return out
for c in msg.tool_calls:
result = apply_tool(c.function.name, json.loads(c.function.arguments or "{}"), state, out)
history.append({"role": "tool", "tool_call_id": c.id, "content": result})
return out
state = json.loads(open("brannoch.json").read())
history = []
print(npc_turn(state, history, "I need to cross before sunrise. Name your price."))Two details deserve attention. First, tool-call rounds are capped at four, so a confused model cannot loop forever. Second, every tool call gets a matching tool message with the same tool_call_id; omit it and the next request is malformed. The result strings are short and factual, which lets the model acknowledge what happened without inventing consequences.
Branching without losing the plot
Let the engine own the story graph and let the model own the sentences. A node lists which NPC speaks, what gate must be passed, and where each choice leads. When the model calls offer_choices, you map each option to a node key; unmatched free text falls back to the current node.
{
"id": "quay_negotiation",
"npc": "brannoch",
"gate": {"trust_at_least": 2},
"on_choice": {
"pay_double": {"next": "crossing_fast", "set": {"gold": -40}},
"threaten": {"next": "quay_standoff", "trust_delta": -2},
"ask_about_tunnel": {"next": "warehouse_tunnel", "requires_fact": "tunnel"}
},
"fallback": "quay_negotiation"
}This keeps the narrative reachable and testable. You can walk the graph without a single API call, check that every next exists, and confirm that gated nodes require facts the player can actually discover. The model supplies variety inside each node, not the structure around it.
- Gates read the state record: trust thresholds, held items, known facts.
- Effects modify it: gold, trust, flags.
- Fallbacks keep the player in place when input is ambiguous.
Memory across a long playthrough
An NPC met ten hours ago should still remember an insult. Do not replay ten hours of dialogue. Store a two-sentence digest per NPC, update it when a conversation ends, and add it to the state record as a memories field. The mechanics of summarising and budgeting are covered in the 100k memory article, and the same trimming applies to each NPC's rolling dialogue.
If you serve a browser game, relay the stream through your own server as in the FastAPI article so the key never reaches the client.
Testing NPCs the way you test code
Dialogue from a model is probabilistic, but the rules around it are not, and that is where tests belong. Save the state record from earlier as brannoch.json, then write checks against the engine rather than against prose.
- Tool validation tests. Call
apply_tooldirectly with an item the NPC does not hold, a trust delta of 99, and malformed arguments. The state must stay legal in every case. - Graph tests. Load every node, confirm each
nexttarget exists, and walk a path from the first node to each ending without calling the API at all. - Replay tests. Record a real conversation once, including tool calls and results, then replay the tool messages against the engine to check that the final state matches what you expect.
- Soak tests. Run a scripted player through fifty lines at a low temperature and assert that the NPC never gives an item it lacks and never exceeds the trust bounds.
Lower the temperature to around 0.3 for those runs, then return to 0.8 for play. Fewer surprises while testing means a failure points at your code, not at sampling noise. When a bug does appear in live play, add the offending exchange to the replay set so it cannot return unnoticed.
A last habit: keep character voice in one short paragraph per NPC and the rules in the state record. Voice can be tuned freely by writers; rules are changed only with a code review. Mixing them in a single blob is how a rewrite of an NPC's personality accidentally gives away an item.
Cost math, with assumptions stated
Prices are $0.15 per million input tokens and $0.50 per million output tokens. The figures below are assumptions for planning, not measurements. Assume one NPC line costs: system instructions and state 350 tokens, recent dialogue 1,000 tokens, tool definitions 250 tokens, so 1,600 input tokens; reply 100 output tokens.
| Item | Calculation | Cost |
|---|---|---|
| Input per line | 1,600 x $0.15 / 1M | $0.0004 |
| Output per line | 100 x $0.50 / 1M | $0.0001 |
| One line | sum | $0.0005 |
| One session, 60 lines | 60 x $0.0005 | $0.03 |
| 10,000 sessions | 10,000 x $0.03 | $300 |
A tool-call round trip adds another request: roughly 1,700 input tokens plus 40 output, about $0.00047. If one line in three triggers a tool, add a third of that to the average. Ceiling checks matter too: at 300 requests a minute per key, a single key supports about 300 NPC lines a minute across all concurrent players, so large launches need queuing. Rates are summarised on the pricing page.
Questions and answers
Does the API support function calling for game actions?
Yes. Tools are accepted in the OpenAI format, so you declare functions, receive tool calls, and send results back as tool messages.
How much does an NPC conversation cost?
It depends on your prompts. With assumed 1,600 input and 100 output tokens per line, one line costs about $0.0005 at the published rates.
Can characters in my game be minors in sexual scenes?
No. Sexual content involving minors is always blocked with a 403, including in fiction. The service is for adults aged 18 and over.
How do I stop the NPC giving away plot secrets?
List what it knows and what it will never do in the state record, and enforce item and flag changes in your own code.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.