Metadata-Version: 2.5
Name: thespis-sdk
Version: 0.5.0
Summary: NPC minds for games: they remember, believe things that may be false, gossip, and act for reasons. The game owns the truth; a language model, if any, only voices it.
Project-URL: Homepage, https://github.com/coderback/Thespis
Project-URL: Documentation, https://github.com/coderback/Thespis/blob/main/docs/getting-started.md
Project-URL: Changelog, https://github.com/coderback/Thespis/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/coderback/Thespis/issues
Project-URL: Demo, https://thespis-production.up.railway.app
Author: Timothy Oluwatobi Ojebiyi
License-Expression: MIT
License-File: LICENSE
Keywords: beliefs,game-ai,game-development,godot,gossip,llm,npc,unity
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Games/Entertainment
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: httpx>=0.27
Provides-Extra: otel
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.27; extra == 'otel'
Provides-Extra: serve
Requires-Dist: fastapi>=0.115; extra == 'serve'
Requires-Dist: uvicorn[standard]>=0.30; extra == 'serve'
Provides-Extra: server
Requires-Dist: cryptography>=43; extra == 'server'
Requires-Dist: fastapi>=0.115; extra == 'server'
Requires-Dist: psycopg[binary,pool]>=3.2; extra == 'server'
Requires-Dist: uvicorn[standard]>=0.30; extra == 'server'
Description-Content-Type: text/markdown

# Thespis

[![CI](https://github.com/coderback/Thespis/actions/workflows/ci.yml/badge.svg)](https://github.com/coderback/Thespis/actions/workflows/ci.yml)
[![Play the demo](https://img.shields.io/badge/demo-play%20live-f0a03a)](https://thespis-production.up.railway.app)
[![Play the manor mystery](https://img.shields.io/badge/second%20game-manor%20mystery-8e6c3a)](https://thespis-production.up.railway.app/manor/)
[![Watch the video](https://img.shields.io/badge/video-2%20min-red?logo=youtube&logoColor=white)](https://youtu.be/WD7oslaKQO4)
[![MIT licence](https://img.shields.io/badge/licence-MIT-blue)](https://github.com/coderback/Thespis/blob/main/LICENSE)
[![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-3776ab?logo=python&logoColor=white)](https://github.com/coderback/Thespis/blob/main/pyproject.toml)

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.

- **Play it:** <https://thespis-production.up.railway.app>. Press **Watch the 60-second story**, or play it yourself.
- **A second game on the same core:** <https://thespis-production.up.railway.app/manor/>, The Manor Mystery, a
  detective scene where a maid lies to protect herself and the inspector catches her. Press **Watch the case solved**,
  or solve it yourself.
- **Video:** <https://youtu.be/WD7oslaKQO4> (2 minutes, with subtitles).
- **Numbers:** [results.md](https://github.com/coderback/Thespis/blob/main/results.md), measured on the hosted engine.

[![The why-chain in The Crypt Road: Captain Brenna's line traced to the decision behind it and the beliefs it cites](https://raw.githubusercontent.com/coderback/Thespis/main/docs/images/crypt-road-why-chain.jpg)](https://youtu.be/WD7oslaKQO4)

*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.

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

[examples/quickstart](https://github.com/coderback/Thespis/blob/main/examples/quickstart) is a village of three in one game file
([game.toml](https://github.com/coderback/Thespis/blob/main/examples/quickstart/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:

<!-- quickstart:start -->
```python
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"]))
```
<!-- quickstart:end -->

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](https://github.com/coderback/Thespis/blob/main/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](https://github.com/coderback/Thespis/blob/main/sdk/godot/README.md) and a [Unity package](https://github.com/coderback/Thespis/blob/main/sdk/unity/README.md).
- **Next:** [docs/getting-started.md](https://github.com/coderback/Thespis/blob/main/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

```mermaid
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](https://github.com/coderback/Thespis/blob/main/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](https://github.com/coderback/Thespis/blob/main/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](https://github.com/coderback/Thespis/blob/main/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](https://github.com/coderback/Thespis/blob/main/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](https://github.com/coderback/Thespis/blob/main/docs/models.md)).

A game whose world lives in an engine supplies only the TOML: [docs/protocol.md](https://github.com/coderback/Thespis/blob/main/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](https://github.com/coderback/Thespis/blob/main/examples/tavern/game.toml) is a complete game.
[sdk/godot](https://github.com/coderback/Thespis/blob/main/sdk/godot/README.md) is the Godot 4 addon and [sdk/unity](https://github.com/coderback/Thespis/blob/main/sdk/unity/README.md) 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](https://thespis-production.up.railway.app/manor/) 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](https://raw.githubusercontent.com/coderback/Thespis/main/docs/images/manor-lie-why-chain.jpg)](https://thespis-production.up.railway.app/manor/)

*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](https://github.com/coderback/Thespis/blob/main/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](https://www.gameaipro.com/GameAIPro3/GameAIPro3_Chapter37_Simulating_Character_Knowledge_Phenomena_in_Talk_of_the_Town.pdf) (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](https://versu.com/wp-content/uploads/2014/05/versu.pdf) (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](https://viv.sifty.studio/introduction/) (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](https://arxiv.org/abs/2304.03442) (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](https://arxiv.org/html/2606.16014v1) (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](https://github.com/coderback/Thespis#run-it-locally). What changed in each release:
[CHANGELOG.md](https://github.com/coderback/Thespis/blob/main/CHANGELOG.md). Licence: [MIT](https://github.com/coderback/Thespis/blob/main/LICENSE).
