Pure-Python examples mirroring examples/ in the Rust workspace. Each example is a single self-contained .py file.
Create and activate a Python venv (one-time), then build & install the extension:
# 1. Create a venv (only needed the first time)
python3 -m venv .venv
# 2. Activate it (every new shell)
source .venv/bin/activate # macOS / Linux / WSL
# .\.venv\Scripts\Activate.ps1 # Windows PowerShell
# 3. Install build deps + build the extension into the venv
pip install maturin
cd bonsai-py && maturin develop --release && cd ..After that, just source .venv/bin/activate + python bonsai-py/examples/<name>.py in any new shell.
simple_npc_ai.py — console NPC
NPC runs and shoots until action points are exhausted, then rests and dies. Demonstrates WhileAll, blackboard mutation via @dataclass, structural-match callback.
python bonsai-py/examples/simple_npc_ai.pyrace_timeout.py — Race between work and timeout
A simulated long-running job (random 200–1200 ms on a threading.Thread) races a 600 ms timeout. The callback polls the work's queue.Queue non-blockingly. Demonstrates Race, asyncio main loop + threading worker, the unsendable-BT constraint.
python bonsai-py/examples/race_timeout.pygraphviz_demo.py — tree visualization
Builds an attack-drone tree (mix of plain-string and @dataclass(frozen=True) payload actions) and prints the graphviz DOT representation. Paste the output into https://dreampuf.github.io/GraphvizOnline/ to render it.
python bonsai-py/examples/graphviz_demo.py
python bonsai-py/examples/graphviz_demo.py > tree.dotvisualizer_smoke.py — live web visualizer
Drives a deliberately rich 27-node tree at ~400 ms/tick with a 5-step status rotation and per-leaf phase offset; the browser shows continuous color animation. Demonstrates BT.with_telemetry(port), reset_bt(), and every major factory.
python bonsai-py/examples/visualizer_smoke.pyThen open http://127.0.0.1:8910/ in a browser. Ctrl-C to stop.
boids_console.py — shared BT across N agents
Builds one Behavior tree and binds it to 10 independent BT instances (each with its own Boid dataclass blackboard). Updates positions every tick for 30 frames. Demonstrates the shared-subtree pattern, real-time-loop dt, WhenAll for parallel updates.
python bonsai-py/examples/boids_console.pyasync_drone.py — multi-job mission
Drone mission: takeoff → check battery → fly (or fall back to land) → land → repeat. Each long-running step runs on a background thread; the BT polls per-job queues. Prints the tree's graphviz() at the start, then runs the mission for ~8 seconds.
python bonsai-py/examples/async_drone.pyDemonstrates Select for prioritized fallback, multi-job orchestration via per-job channels, asyncio + threading.