Skip to main content

Thespis

CI Play the demo Play the manor mystery Watch the video MIT licence Python 3.12+

An AI toolkit for game developers. Its first module, Thespis Cast, gives NPCs minds of their own: they remember what happened, believe things that may be false, want things for reasons, and keep acting when the player isn't looking.

The game owns the truth. Every event goes into an append-only ledger. Each NPC builds beliefs from evidence, with a source and a confidence, and a belief can be wrong and later retracted. Numeric drives and trust decide what an NPC does. A language model only voices it, and every line it says must cite the ledger events and beliefs behind it, checked by code before anyone hears it.

The why-chain in The Crypt Road: Captain Brenna's line traced to the decision behind it and the beliefs it cites

The why-chain: Captain Brenna's line, traced to the decision behind it, the beliefs it cites and the ledger events at the root. Click the picture to watch the video.

Use it in your game

Your game keeps its own world and rules. It tells Thespis what happened and who saw it, and asks what an NPC does and says. Thespis keeps the minds: what each NPC believes and why, who they tell, and what they choose to do about it.

pip install thespis-sdk        # on PyPI as thespis-sdk; it imports as thespis

examples/quickstart is a village of three in one game file (game.toml): a baker, a miller and his sister, two ties and one decision. The player steals a loaf with the miller watching, and lies about it:

from pathlib import Path

from thespis.api import Game, Session, gateway_from_env

game = Game.load(Path(__file__).with_name("game.toml"))
s = Session.new(game, gateway=gateway_from_env())

# 1. Your game reports what happened, and who saw it. Thespis never decides what happened. Mara was in the back
#    room, so she isn't the event's target: only Wat saw it.
theft = {"pred": "stole_from", "a": "player", "b": "mara"}
s.observe("steal", "player", at="bakery", claim=theft, witnesses=["wat"])

# 2. Time passes in the minds: the story goes from Wat to Edda, then from Edda to Mara, weaker at each step.
s.tick(2)

# 3. The player lies. Mara believes a stranger only so far, and a theft has one thief.
s.observe("tell", "player", "mara", claim={"pred": "stole_from", "a": "wat", "b": "mara"}, said=True)

# 4. The player comes to Mara's counter. She chooses among the choices the game file gives her, and speaks.
s.update("player", loc="bakery")
line = s.decide("mara", "counter")
print(f"Mara: {line.text}  ({line.reason})")

# 5. Why: everything each of them believes, how sure, and the events behind it.
for npc in ("wat", "edda", "mara"):
    for b in s.inspect(npc)["beliefs"]:
        c, sure = b["claim"], b["opinion"]["b"]
        print(f"  {npc} {b['status']}: {c['a']} {c['pred']} {c['b']} at {sure:.2f}, from",
              ", ".join(f"{e['source']} ({e['event']}{', against' if e.get('against') else ''})" for e in b["evidence"]))

With no model at all, it prints:

Mara: Not you. I know what you did.  (refuse:player scores 4)
  wat active: player stole_from mara at 1.00, from witnessed (e0001)
  edda active: player stole_from mara at 0.90, from wat (e0002)
  mara active: player stole_from mara at 0.73, from edda (e0003)
  mara retracted: wat stole_from mara at 0.06, from player (e0004), edda (e0003, against)
  • The story weakens as it travels: Wat saw it, Edda has it from her brother, Mara from her friend.
  • A lie loses to a source trusted more, and costs the liar: Mara now believes less of anything else the player tells her.
  • No model is needed. Every line falls back to the game's own words. With a model (LLM_*, docs/models.md, or a local one offline), the model words the line, and code checks that it says only what Mara knows.
  • Other engines: thespis serve runs the same calls over HTTP beside your game, with a Godot addon and a Unity package.
  • Next: docs/getting-started.md walks through the game file and the calls a game makes.

The demo: The Crypt Road

A race to a relic in a crypt, five stops down one road. Insult your rival Kael, beat him in a duel and take his purse, and he remembers. Out of your sight he tells Captain Brenna, and she won't let you through the gate. Pay her fine, then frame Kael with a lie, and she detains him. You win the race, but Odo, a peddler who saw everything, tells the Captain the truth afterwards, and she remembers whose word she trusted.

Every NPC line in the client opens a why-chain: the line, the decision that produced it, the beliefs it cites, and the ledger event at the root, marked true or false.

How it works

flowchart LR
    P["Player verb"] --> R["Game rules"]
    R -->|"appends"| L[("Ledger: what really happened")]
    L -->|"seen, told, gossiped"| B["Each NPC's beliefs: source, confidence, can be false"]
    B --> D["Drives and trust"]
    D --> U["Utility brain scores the allowed actions"]
    U -->|"the ones close to the best"| S["State pack: beliefs, events, allowed actions. Never the truth"]
    S --> C{"Cache"}
    C -->|"miss"| M["Language model"]
    C -->|"hit"| V
    M --> V{"Validator"}
    V -->|"passes"| A["Action and a line citing ledger ids"]
    V -->|"fails"| F["The code's choice and a template line"]
    A --> R
    F --> R
  • Ledger: append-only ground truth (thespis/ledger.py). Nothing edits or deletes an event. Claims are typed: a predicate, who it's about and whom it names, and optionally where and when it held and whether it's denied.
  • Beliefs: each NPC's evidence for or against a claim, with its source and confidence (thespis/beliefs.py), fused into a subjective-logic opinion: belief, disbelief and uncertainty. Independent sources add up; testimony counts against a claim, and a belief is retracted once disbelief outweighs belief. When an NPC stops trusting someone, everything that source told it is re-weighed. Truth is never stored with a belief; it's derived from the ledger, so a belief can be false.
  • Drives decide, the model words it: the utility brain scores every allowed action from the NPC's drives and trust, and takes the best. The model is told only what the NPC is doing, with no other options and no scores, and writes the line. Offered a choice, it took the strongest pull 86 times in 86 (docs/cast-review.md), so with the model on, every route ends exactly as with it off.
  • State pack and validator (thespis/expression.py): the model sees only what the NPC knows, never whether it's true, with its beliefs and events under short references (b1, e1, ...). Each call's JSON schema lists exactly the references its pack holds, and a model with structured outputs can't step outside it. A reply is rejected unless the line is 1 to 160 characters, it cites at least one reference, every one is in the pack, and it names no one the NPC doesn't know about. A rejected reply, a timeout or no model at all falls back to a template line.
  • Claim check (thespis/claims.py, off by default for now; see Deploy): the validator checks form; this checks meaning. A line with consequences (an accusation, an arrest, testimony, a deal, Sable's answer, Lady Vane on the case, the narrator) has its claims extracted by a model in the game's own vocabulary, and code checks each one against the ledger and what the speaker could know. A line that leaks, hallucinates or contradicts its speaker falls back, as does a lie that doesn't state the claim its action asserts. If the extractor doesn't answer, the line falls back too.
  • Model gateway (thespis/gateway.py): any OpenAI-compatible endpoint, including Azure. A primary, then a backup, then the fallback, within 4 seconds each, with no retries.
  • Cache and replay: every reply that passes is cached, keyed by the model, the prompt version, the call type and the state pack, so the same moment says the same thing again with no model call. REPLAY=1 serves only from the cache and the fallback.
  • The tick: each phase, the player acts; the Captain and Kael decide; gossips pass on what they believe; everyone moves; fear fades. NPCs decide on where everyone stood when the phase began.
  • Core and adapter: thespis/ knows nothing about this game; games/crypt_road/ is one adapter on it. A test fails if the core ever imports from a game. examples/minimal_client.py uses the core alone, in about 30 lines.
  • Persistence: SQLite, an insert-only ledger table plus a snapshot per session, so a restart loses nothing.
  • The Dungeon Master: after each phase the model tells the player what happened, including what they couldn't see, citing the events it uses. Code sifts the ledger for the story's threads (revenge brewing, a lie told, a lie exposed) and shows the live one under the telling. If a telling fails the validator, the code-built telling stands.
  • Live persona editing: in the inspector's Minds tab, change an NPC's persona and its next line follows it. The edit belongs to that game, so other players and the demo cache are untouched.
  • Haggling: offer Brenna any bribe. Code sets her price from her trust in you (15 to 30 coins, never under 20 while she distrusts you); under it she refuses a lowball (under half her price) and counters anything else, and the model words it.

Numbers

From results.md: every scripted route, played on the hosted engine with GPT-6 Luna. The last two rows are model-judged: GPT-5.4 nano read 50 of Luna's lines beside the state packs they came from (tools/judge.py).

Measure Value
NPC turns played by code alone, with no model call 87%
Model replies blocked by the validator 0 of 91
Model call latency on the host, p50 / p95 1131 ms / 1704 ms
An action that calls the model, p50 / p95 1.6 s / 2.2 s
An action that doesn't 34 ms
Cost per run, every call to the model $0.00071
Routes ending as the rules model predicts 10 of 10
Lines stating only what the NPC knew (model-judged) 43 of 50
Lines in character (model-judged) 50 of 50

Which models and why: docs/models.md.

What a game supplies

The core owns the mind loop; a game supplies its content and the rules only it has.

The core (thespis/) The game (games/<game>/)
Perception: who knows each event (perception.py) One rule: what an NPC sees (sees)
State packs, line delivery, the narrator (voice.py) A Voice: its cast, validator, words and setting
Declared actions and the decision among them (affordances.py) Its NPCs' actions, their utilities and effects
The phase as a pipeline, with walks and gossip (tick.py) Its steps, in its order
Beliefs as opinions, revision, contradictions (beliefs.py) What contradicts what, and its trust ladder if not the default
Verbs, refusals and the Mind per action (play.py) Its verbs and what they do
Claim checks (claims.py) Its claim vocabulary
Content loading (cast.py) cast.toml: personas, template lines, event sentences, situations
Choices as data, compiled to affordances (considerations.py) [[npc.<id>.choices.<moment>]]: conditions and utilities

Any model can speak: OpenAI-compatible endpoints, Anthropic, or a local model on the player's own GPU for offline play, measured as accurate as the cloud in live Rehearsal (docs/models.md).

A game whose world lives in an engine supplies only the TOML: docs/protocol.md covers the calls (observe, decide, react, narrate, tick, snapshot, restore) in the library (thespis.api) and over /v1 HTTP (python -m thespis serve), and examples/tavern/game.toml is a complete game. sdk/godot is the Godot 4 addon and sdk/unity the Unity package. Each one's example plays the tavern offline through a sidecar or online through a server, with no change to the scene.

Same core, a different game: the manor mystery

The Manor Mystery is a three-room detective scene on the same core, with its own adapter (games/manor/) and none of the Crypt Road's code. Lady Vane's signet ring went missing before you arrived; the ledger knows Sable took it and that Pell saw her leave the study. Ask Sable where she was and she lies. Her lie is an action the rules choose once she's frightened enough: the model words it, the line cites the claim it states, and the ledger logs it false, so the inspector marks it. Ask Pell, have Lady Vane question him, and his testimony breaks the alibi. Accuse Sable before evening to win.

The manor mystery: Sable's lie in the why-chain, beside the house with the hall in darkness

Sable's lie, traced: her line, the action she chose (to lie rather than dodge), the statement the ledger logged false, and what she really knew. Click the picture to play.

In the browser it plays like The Crypt Road. The house is a pixel-art cutaway drawn in code, where only the room you're in is lit and the afternoon turns to evening in the windows. People walk between rooms and speak in typed bubbles, Sable sweats as her fear rises, a red LIE stamp lands when a statement is logged false, and Pell walks into the hall to testify. Press Watch the case solved for the solve with captions (about a minute), or solve it yourself. The case notes after every move are built from the ledger with no model calls, and the inspector is The Crypt Road's: Minds, Beliefs, Ledger and Why.

The only change the core needed was that one feature, NPC deception as a validated action (thespis/deception.py). python tools/manor_solve.py <host> solves it by script. Rules and API: docs/manor.md.

What's new, and what isn't

NPCs whose beliefs can be false against ground truth have existed in symbolic systems for a decade, so that isn't our claim. What's new is putting that model under a language model that may only choose code-validated actions and must cite ledger events in what it says. That makes an NPC's lies and mistakes checkable rather than hallucinated.

Prior work What it does What it lacks next to Thespis
Talk of the Town (Ryan et al., 2015) Per-character beliefs that can be false, with sources and decaying strength; lies and misremembering No language model, no validated action set, not a reusable framework
Versu (Evans and Short, 2013) Individual and false beliefs, actions from social practices, a drama manager No language model, no ledger, no confidence-weighted gossip
Viv (Ryan, Sifty) A domain-agnostic engine: a chronicle, witnessed memories, gossip, plans and story sifting No language model; we found no confidence, false beliefs or retraction
Generative Agents (Park et al., 2023) Language-model memory, reflection, planning and information spreading No ground truth or confidence; the model drives agents with no validated action set
Orchestrated Reality (2026) An append-only event journal, plan-diff-validate-apply, deny-first permissions No per-NPC beliefs or gossip

What we claim: the model has no write path to memory, since only the game writes the ledger and beliefs; every line cites ids the validator checked; and NPCs can be wrong, act on it, and be corrected by testimony.

More

Running the repository locally, its tools, Rehearsal and the hosted demo are in the README on GitHub. What changed in each release: CHANGELOG.md. Licence: MIT.

Metadata

Release files for thespis-sdk 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for thespis-sdk 0.6.0
File Size Uploaded Provenance Actions
thespis_sdk-0.6.0.tar.gz 225.5 kB With provenance Details for thespis_sdk-0.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for thespis-sdk 0.6.0
File Interpreter ABI Platform Actions
thespis_sdk-0.6.0-py3-none-any.whl Python 3 none any Details for thespis_sdk-0.6.0-py3-none-any.whl

Total release size: 407.7 kB

Release files / thespis_sdk-0.6.0.tar.gz

Download URL thespis_sdk-0.6.0.tar.gz
Size 225.5 kB
Tags Source
SHA-256 checksum
How to use checksums
345b0a8c0f1062605d315f479181762afd8d11c658f8e8bdcbbf98f97100115d
BLAKE2b-256 checksum
How to use checksums
3aded938105d8909760f0c1a3719029097289cb4f60bc153a2d09c93ab2ca794
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / thespis_sdk-0.6.0-py3-none-any.whl

Download URL thespis_sdk-0.6.0-py3-none-any.whl
Size 182.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
77de14cbcef60db0bf0356c9602cf87c6aba4f97abdbc83006cf4f5eb784bb47
BLAKE2b-256 checksum
How to use checksums
1f0a4c166496066e8e1aaf3c988f2d01be678f9ef00691fb42c5f229f93514f8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Security for thespis-sdk 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for thespis_sdk-0.6.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page