The Engineering Challenge: Why Decalove Was Architected
Traditional visual novels rely on static branching trees—exponential content explosion limits scope. Pure LLM chat interfaces lack structural coherence, state persistence, and the “game feel” of authored pacing. Decalove – AI-Directed Visual Novel Game solves this by introducing an AI Agent Story Engine that owns the narrative state machine, generating beats ahead of player progress so seams never show.
The core architectural mandate: the engine owns state, the model proposes content. This inversion of control—moving logic out of the prompt and into a typed Python/FastAPI layer—enables deterministic debugging, regression testing, and sub-second latency for a visual novel experience.
- Decoupled Architecture: Pure Python Ren’Py client ↔ Async FastAPI backend via REST/WebSocket.
- AI Director State Machine: Computes pacing, tension, and character stances from live game state before LLM invocation.
- Vector Semantic Memory: pgvector/Chroma retrieval injects only relevant character memories into context windows.
- Beat-Ahead Generation: Background workers pre-fetch narrative beats, masking LLM latency entirely.
- Dual Input Modalities: Authored choices and natural language prose normalized to canonical intents.

Core Architecture & Technical Stack Deep-Dive
High-Level System Topology
┌─────────────────┐ HTTPS / WS ┌──────────────────────┐
│ Ren'Py Client │ ◄─────────────────► │ FastAPI Backend │
│ (Python 3.12) │ JSON / MsgPack │ (Python 3.12) │
└─────────────────┘ └──────────┬───────────┘
│
┌──────────────────────────────┼──────────────────────────────┐
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ PostgreSQL │ │ ChromaDB │ │ OpenRouter │
│ (Relational │ │ (Vector Mem) │ │ (LLM API) │
│ State) │ │ │ │ │
└───────────────┘ └───────────────┘ └───────────────┘
▲ ▲ ▲
└──────────────────────────────┼──────────────────────────────┘
│
┌──────┴──────┐
│ Redis / │
│ Celery │
│ (Beat Queue)│
└─────────────┘
Client Layer: Ren’Py as a Pure Python Runtime
Decalove strips Ren’Py down to its rendering and input loop. No Ren’Py script logic (.rpy) drives narrative—only UI presentation. The client maintains a local optimistic state for instant feedback, reconciling with authoritative server state via ETag-based snapshots. This eliminates “rubber-banding” during network hitches.
- Rendering: Atlas-packed sprites, WebP backgrounds, lazy-loaded via Ren’Py’s image predictor.
- Input Normalization: Choice clicks →
{type: "choice", id: "opt_3"}; Prose →{type: "prose", text: "...", embedding: [...]}. - Offline Buffer: IndexedDB queue persists player input during disconnects; replayed on reconnect.
Backend Layer: FastAPI Story Engine
The backend is a stateless request handler + stateful background workers. FastAPI serves two contracts:
- Synchronous:
POST /beat/next— returns the next authored beat (p50 < 120ms from cache). - Asynchronous:
POST /director/plan— enqueues aBeatGenerationJobfor the next+1 beat.
Core modules (director/, memory/, world/, characters/) are pure Python packages with zero Ren’Py dependencies, enabling headless CI testing.
AI Director: The Deterministic State Machine
The Director is not an LLM prompt. It is a typed Python class (DirectorEngine) that computes:
- Pacing Score (0–1): Beats-per-minute target derived from session length, arc phase, and player dwell time.
- Tension Vector: Multi-dimensional (romantic, conflict, mystery, comedy) weights from recent beats and flags.
- Character Stances: Per-character
RelationshipDeltaandEmotionalStateenums (e.g.,GUARDED,VULNERABLE,PLAYFUL).
These outputs constrain the LLM prompt via a structured BeatDirective Pydantic model, guaranteeing the model cannot “hallucinate” pacing violations.
Vector Semantic Memory: Retrieval-Augmented Narrative
Every character utterance and player action is embedded (OpenAI text-embedding-3-small, 1536-dim) and upserted into ChromaDB with metadata: {character_id, beat_id, arc, day, location, emotional_valence}.
- Query: On beat generation, retrieve
top_k=5memories per character filtered bycharacter_idandcosine_similarity > 0.72. - Context Budget: Memories compressed via
summarize_memories()utility to fit a 1,200 token budget. - Forgetting Curve: TTL-based decay (half-life 14 in-game days) simulates organic memory fade.
Key Features Breakdown & Practical Benefits
1. Beat-Ahead Generation Pipeline
A Celery worker pool consumes BeatGenerationJob tasks. Each job:
- Snapshots current
GameState(PostgreSQL row lockSELECT ... FOR UPDATE SKIP LOCKED). - Runs
DirectorEngine.compute_directive(). - Assembles prompt:
SystemPrompt + WorldBible + CharacterCards + Directive + Memories + RecentBeats. - Calls OpenRouter (primary:
anthropic/claude-3.5-sonnet; fallback:openai/gpt-4o-mini). - Validates response against
BeatSchema(Pydantic). On failure: retry withtemperature -= 0.1(max 3 retries). - Persists beat; pushes WebSocket
beat_readyevent to client.
Benchmark: End-to-end p95 = 2.1s (cold LLM), p50 = 840ms (warm). Client perceives 0ms wait because beat N+1 is generated while player reads beat N.
2. Dual Input: Choices & Natural Language Prose
Prose input flows through an Intent Classifier (fine-tuned DistilBERT, 66
Leave a Reply