Skip to main content

branching-story-kit (Python)

Zero-dependency branching narrative engine for interactive fiction, visual novels, and romance story apps — story-graph state tracking, gated choices, a persistent memory log, save/restore, a static validator, and a JSON Schema. Pure Python 3.10+, fully typed, MIT.

PyPI Python Zenodo DOI Harvard Dataverse DOI JSR GitHub Pages — live demo Ouba — iOS · Android · Web License: MIT dependencies: 0

Built in the open by Ouba Studio — the team behind Ouba, free reader-first interactive fiction on web, iOS, and Android, and the 2026 AI Story Apps Benchmark (open data on CERN Zenodo and Harvard Dataverse).

This is the Python port of the JavaScript/TypeScript package @ouba-studio/branching-story-kit (JSR · npm). Same manifest, same semantics, same save-file shape — a route played in Python plays identically in the browser.


Why branching-story-kit?

Most "interactive story" tooling is either a full game engine or a blank chat box. This kit is the small, boring, reliable layer in between: a JSON story graph with explicit state, so that what a reader did in turn 2 is still true in turn 15.

  • Zero dependencies — one module, stdlib only, Python 3.10+. dependencies = [].
  • Relationship & flag state — numeric effects add, everything else assigns; requires gates choices behind thresholds.
  • Persistent memory log — engine.remember("My cat's name is Marmalade.") records reader-planted facts with turn numbers so long sessions don't drift.
  • {{state}} interpolation in prose, with unknown placeholders left intact.
  • Free-text steering — set() + jump() let typed input branch the plot without leaving the manifest.
  • Save / restore — export_save() → StoryEngine.import_save() round-trips cursor, state, history, and memory.
  • Static validator + JSON Schema — catch broken next links before you publish; validate manifests in your editor or CI.
  • Fully typed — ships py.typed and inline annotations (StoryEngine, SceneView, ValidationResult).

Install

pip install branching-story-kit
uv add branching-story-kit
# or
poetry add branching-story-kit

No compiled extensions, no transitive dependencies, no network calls at import time.

Quickstart

from branching_story_kit import StoryEngine, validate_story

story = {
    "id": "the-midnight-bookshop",
    "start": "start",
    "initialState": {"spark": 1, "trust": 1, "item": "none"},
    "scenes": {
        "start": {
            "title": "Rain on Bellweather Lane",
            "body": "Your {{item}} waits on the counter.",
            "choices": [
                {"label": "Take the mug", "next": "warm", "effects": {"spark": 2, "item": "Cardamom Tea"}},
                {"label": "Compare notes", "next": "warm", "effects": {"trust": 2}},
            ],
        },
        "warm": {"title": "Between the Stacks", "body": "Trust={{trust}} Spark={{spark}}", "ending": True},
    },
}

assert validate_story(story).valid

engine = StoryEngine(story)          # one instance == one reader session
view = engine.current()              # SceneView with gated choices filtered
print(view.body)                     # "Your none waits on the counter."
print(view.labels)                   # ["Take the mug", "Compare notes"]

view = engine.choose(0)              # applies effects, advances, returns the new scene
print(view.body)                     # "Trust=1 Spark=3"
print(engine.turn)                   # 2
print(engine.export_save())          # JSON: cursor + state + history + memory

Gated choices

{
    "label": "Tell him you kept the letter he wrote to you last winter, too.",
    "next": "end_letter",
    "requires": {"trust": 4},        # hidden until trust >= 4
}

current() filters gated choices out for you, so a UI can render view.choices without re-implementing the rules. requires uses JavaScript-style numeric coercion, so "4" counts and garbage counts as zero.

Free-text steering

engine.set("customLine", "Stay until the last page, then walk me home.")
engine.remember("Reader chose to stay past closing.")   # turn-stamped memory
engine.jump("end_custom")                              # effects optional

remember() ignores blank facts and stamps each entry with {"turn": n, "fact": "..."} — the same shape the JS engine writes.

Save / restore

saved = engine.export_save()                     # compact JSON string
restored = StoryEngine.import_save(saved, story)  # cursor, state, history, memory

import_save() accepts a JSON string or an already-parsed dict, and raises SaveDataError (a ValueError) on malformed or inconsistent payloads — never a bare KeyError.

Static validation

result = validate_story(story)
if not result:                       # ValidationResult is falsy when invalid
    raise SystemExit(result.errors)  # e.g. "Scene 'a' links to missing scene 'ghost'"

The validator never raises: garbage input yields {"valid": False, "errors": [...]}. A JSON Schema for editors and CI ships as package data:

from pathlib import Path
import branching_story_kit

schema = Path(branching_story_kit.__file__).parent / "story.schema.json"

API

Name What it does
StoryEngine(story, initialState=None) Create a session. Raises InvalidStoryError on a manifest without start/scenes.
engine.current() SceneView snapshot: id, title, body, choices, ending, state (copied).
engine.turn Scene visits so far (the start scene counts as turn 1).
engine.scene_id / engine.sceneId Current cursor (the second is the JS-style alias).
engine.state Live reader state mapping.
engine.history Ordered list of visited scene ids.
engine.memory Turn-stamped memory log.
engine.interpolate(text) Replace {{key}} placeholders; unknown keys stay literal.
engine.set(key, value) Write one state value, return a copy of the state.
engine.remember(fact) Append a trimmed, turn-stamped fact; blanks ignored.
engine.choose(index) Take a visible choice by index; applies effects and advances.
engine.jump(scene_id, effects=None) Jump straight to a scene (free-text steering).
engine.export_save() Compact JSON of the whole session.
StoryEngine.import_save(save, story) Restore a session from JSON string or mapping.
validate_story(story) ValidationResult(valid, errors) — never raises.
apply_effects(state, effects) Standalone helper: numbers add, others assign.
interpolate(text, state) Standalone {{key}} interpolation.

Errors: BranchingStoryError (a ValueError) is the base of InvalidStoryError, UnknownSceneError, ChoiceError, and SaveDataError.

Play the demo — The Midnight Bookshop

A four-scene rivals-to-lovers branching romance with relationship meters, an inventory item, a trust-gated choice, a free-text steering moment, and four endings. It is the same manifest that powers the GitHub Pages showcase and the itch.io build.

pip install branching-story-kit
python examples/play.py          # interactive terminal play-through
python examples/play.py --all    # print every authored route

Or headlessly:

from branching_story_kit import StoryEngine
from examples.midnight_bookshop import story

engine = StoryEngine(story)
for scene in engine:             # engine is iterable: follows the first visible choice
    print(scene.title, scene.labels)

Development

pip install -e ".[test]"
pytest                           # 69 tests, 100% passing
python -m build                  # wheel + sdist in dist/

The test-suite covers the engine, gating, interpolation, effects, memory, save/restore, the validator, the demo story's four routes, and packaging metadata (including "must stay zero-dependency").

Compatibility with the JS package

Behaviour JS Python
Manifest shape {"start", "scenes", "initialState"} identical
requires gating Number(state) >= Number(min) _as_number() equivalent
Numeric effects add add (booleans assign, as in JS)
{{key}} interpolation unknown keys left literal identical (true/false lowercase)
Save payload keys storyId, sceneId, state, history, memory identical
choose(-1) out of bounds out of bounds (never wraps)

Citation

If you use branching-story-kit in your research, product, or game, please cite it:

@software{ouba_studio_2026_branching_story_kit,
  author  = {{Ouba Studio}},
  title   = {branching-story-kit: A zero-dependency branching narrative engine for interactive fiction, visual novels, and romance story apps},
  year    = {2026},
  doi     = {10.5281/zenodo.24514910},
  url     = {https://github.com/ouba-studio/branching-story-kit},
  license = {MIT}
}

License

MIT — © 2026 Ouba Studio.

Metadata

Release files for branching-story-kit 1.0.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 branching-story-kit 1.0.0
File Size Uploaded Provenance Actions
branching_story_kit-1.0.0.tar.gz 32.8 kB Without provenance Details for branching_story_kit-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for branching-story-kit 1.0.0
File Interpreter ABI Platform Actions
branching_story_kit-1.0.0-py3-none-any.whl Python 3 none any Details for branching_story_kit-1.0.0-py3-none-any.whl

Total release size: 48.7 kB

Release files / branching_story_kit-1.0.0.tar.gz

Download URL branching_story_kit-1.0.0.tar.gz
Size 32.8 kB
Tags Source
SHA-256 checksum
How to use checksums
656b9d0106072774a7035554d38e4dc1f465d2e1d17b094c90bbfb5e4f3482e0
BLAKE2b-256 checksum
How to use checksums
1522415b36165aed8362e8e12d57d9992e3de0c01f4f371ce2fd27a4b7de8ca4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / branching_story_kit-1.0.0-py3-none-any.whl

Download URL branching_story_kit-1.0.0-py3-none-any.whl
Size 15.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dc7f8ea615a4ad12754a30102b3a8b7e0ce77f768a9b7aa5dec4c4e3febf3860
BLAKE2b-256 checksum
How to use checksums
6de7d36d5ead72ba9b6c452f7cdaa2ba5027f8b0d9ea86e6e65229faf7025773
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for branching-story-kit 1.0.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

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