Skip to content

tylevnovik/playbook

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

119 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Playbook

Playbook is a modern, responsive, and feature-rich Flutter application designed for managing interactive AI roleplay characters, world lore (World Books), and chat conversations. It offers full customization for API configurations, allowing you to connect to any OpenAI-compatible API endpoints.

English | ็ฎ€ไฝ“ไธญๆ–‡


Key Features

  • ๐ŸŽญ Character Management: Build, configure, and customize characters. Define their name, avatar, personality descriptions, prompt contexts, first messages, and system instructions. Features a dedicated Character Management view for better role separation.
  • ๐Ÿ“š World Book (Lore) Management: Create and manage world lore entries, terms, and backgrounds. Let your characters reference background information dynamically during conversations.
  • ๐Ÿ’ฌ Interactive Chat Room:
    • Immersive dialogue interface supporting full Markdown rendering.
    • Interactive input box with multi-profile tokenizer estimation and real-time validation.
    • Multi-session management with historical chat threads.
    • ๐Ÿ‘ฅ Multi-Character Group Chat & DM Mode: Run roleplays with multiple characters in a single chat room. The AI acts as a Dungeon Master (DM) and orchestrator, supporting scene narrations under [DM] and distinct character dialogues with [Character Name] prefixes.
    • ๐ŸŽญ Flexible Speaker Switching & Identity Skins: Seamlessly switch your identity before sending a message to speak as the player, Narrator/DM, or any character in your library.
    • ๐Ÿ“ Blank / Character-less Chat: Create conversations without pre-bound characters, allowing you to discuss general topics or bind characters and world books later.
    • ๐Ÿท๏ธ Auto-Title & Chat Renaming: Automatically generates relevant chat titles based on the first message and participants, with the ability to manually rename them.
    • ๐Ÿงน Recursive Message & Branch Deletion: Deleting a message recursively cleans up all subsequent branched replies, ensuring a clean history.
    • ๐Ÿง  Prompt Caching Friendly Context Optimization: Assembly order is optimized to place static layers (System, Summary) at the top, and dynamic layers (World Book context, Recent Messages) at the bottom. Features a message-count-based lock/debounce mechanism for matched World Book entries (locked for 4 message turns) to prevent prefix jitter and maximize prompt caching.
    • ๐Ÿ› ๏ธ Rich Message Context Actions: Rewrite messages from a specific character's perspective, edit messages, continue local selection, and pin a branch as the mainline.
  • ๐Ÿค SillyTavern Ecosystem Compatibility: Import/export SillyTavern-compatible Character Cards (PNG with embedded Exif metadata, or JSON V1/V2), World Info JSON configurations, Group configs, and Chat history logs (JSONL/JSON format).
  • ๐Ÿ‘ค Persona & User Identity Library: Manage multiple user Persona cards with custom avatar uploads (stored portably as data URIs). Switch sender identities dynamically in the input picker.
  • ๐ŸŽฏ Advanced World Book Triggering & Rules:
    • Fine-grained matching using secondary keywords, any/all match logic, case-sensitivity, whole-word matching, selective/constant modes, and trigger probabilities.
    • Support for scan depth constraints, delay-based activations, cooldown suppression, custom sticky retention durations, and customizable insertion positions (before or after recent chat history).
  • ๐Ÿ”€ Group Chat Advanced Scheduling: Control group speaker order and activation (natural, list, sequential), add automatic turn delays, manage queues, and inject custom depth prompts.
  • โš™๏ธ Advanced LLM Controls & Sampler Presets:
    • Configure advanced parameters: temperature, min_p, top_k, repetition_penalty, frequency_penalty, presence_penalty, and seed.
    • Customize token-level logit bias maps, reasoning effort, and logprobs/top logprobs.
    • Create, save, and apply reusable Sampler Presets.
  • ๐Ÿ› ๏ธ OpenAI-Compatible Tool Calling: Direct integration for native function calling. Expose controls for tool choice, parallel tool calls, and custom raw tools JSON payloads.
  • ๐Ÿ“Š Chat Stats & Automated Backups: Access detailed chat statistics summarizing token usage per-role and per-turn. Automatic background backups secure your chat JSON logs after message creation or regeneration.
  • ๐Ÿ–ผ๏ธ Media Asset Library: Upload and organize custom background assets, character sprites, and gallery attachments. Apply per-chat visual backgrounds and overlay character sprites on bubbles.
  • โšก Quick Replies & Variables: Quick Reply buttons with runtime macro/variable expansions (e.g. user, character) for fast input formatting.
  • ๐Ÿ”ฎ AI Worldview Extractor: Analyze large background texts or past chat histories to automatically parse and extract structured character profiles and world book lore entries, importing them to new/existing world books with one click.
  • ๐Ÿ“Œ Story State & Tracking: Add, edit, and toggle 6 categories of story state constraints (Character, Location, Event, Relationship, Taboo, Style) dynamically in the chat settings drawer to maintain plot consistency and writing rules.
  • ๐ŸŽจ Modern & Adaptive UI:
    • Material 3 Design with Dynamic Color theming (syncs with OS accent color).
    • Fully supports Dark Mode and Light Mode.
    • Responsive Layout: Seamlessly transitions between Mobile (navigation bar) and Desktop (collapsed/expanded sidebar layout).
  • ๐Ÿ’พ Data Independence & Portability: Export your entire database (characters, world books, chat histories, settings) or preferences snapshots to a single file, or import it back anytime.
  • ๐Ÿ“ก Offline Monitoring: Real-time connection checker with offline banner warning to ensure stable API requests.

Tech Stack


Getting Started

Prerequisites

Make sure you have Flutter SDK installed on your system (stable channel recommended).

Installation

  1. Clone the repository:

    git clone https://github.com/tylevnovik/playbook.git
    cd playbook
  2. Get dependencies:

    flutter pub get
  3. Run code generation: This project uses build_runner and injectable for dependency injection and serialization. Run the following command to generate the required configuration files:

    flutter pub run build_runner build --delete-conflicting-outputs
  4. Run the application:

    • Run on connected device (Mobile, Desktop, or Web):
      flutter run
    • For Release build:
      flutter build apk  # For Android APK
      flutter build windows  # For Windows Desktop
      flutter build web  # For Web app

Context Construction Flow

To maintain character consistency, world lore integrity, and adhere to active story states in long-context conversations, Playbook implements a detailed context assembly pipeline and token budget manager. Upon each LLM call, the system dynamically constructs the prompt payload using the following workflow:

graph TD
    Start["1. User Sends Message (Trigger SendChatMessage)"] --> InitBudget["2. Initialize Token Budget<br/>budget = contextWindow - maxTokens"]
    
    InitBudget --> GenSystem["3. Build System Prompt<br/>(Supports systemPromptOverride or character prompt presets)"]
    GenSystem --> SubSystemBudget["Deduct Budget: budget -= TokenEstimator(systemPrompt)"]
    
    SubSystemBudget --> FetchSummary{"4. Has Conversation Summary?"}
    FetchSummary -- Yes --> BuildSummary["Generate summary system message"]
    BuildSummary --> SubSummaryBudget["Deduct Budget: budget -= TokenEstimator(summary)"]
    SubSummaryBudget --> FetchStoryState
    
    FetchSummary -- No --> FetchStoryState{"5. Has Active Story States?"}
    
    FetchStoryState -- Yes --> FormatStoryState["Group and concat states by category"]
    FormatStoryState --> BuildStateContext["Generate story_states_context system message"]
    BuildStateContext --> SubStateBudget["Deduct Budget: budget -= TokenEstimator(statesContext)"]
    SubStateBudget --> FetchWorldBook
    
    FetchStoryState -- No --> FetchWorldBook{"6. Has Linked World Books (worldBookIds)?"}
    
    FetchWorldBook -- Yes --> ExtractRecent["Scan recent messages based on scan_depth"]
    ExtractRecent --> MatchEntries["Match Keywords & Trigger Logic (any/all)"]
    MatchEntries --> ScoreEntries["Score, Sort, and Apply Delay/Cooldown Filters"]
    ScoreEntries --> LockEntries["Locking & Retention<br/>(Apply custom sticky turns, delay & cooldown)"]
    LockEntries --> SplitPos["Split by Insertion Position<br/>(Before vs. After History)"]
    SplitPos --> AddBefore["Format & Add 'Before' entries (world_context)"]
    AddBefore --> SubWbBudget["Deduct Budget: budget -= TokenEstimator(worldContext)"]
    SubWbBudget --> FillRecentMessages
    
    FetchWorldBook -- No --> FillRecentMessages["7. Backwards-traverse recent messages"]
    
    FillRecentMessages --> FormatSpeaker["Apply Regex Replacement Rules & Speaker Prefixes"]
    FormatSpeaker --> FitMessages{"Does budget allow?"}
    FitMessages -- Yes --> AddMessage["Add to payload & update budget"]
    AddMessage --> NextMessage{"Have earlier messages?"}
    NextMessage -- Yes --> FormatSpeaker
    NextMessage -- No --> CheckAfterWorldBook
    FitMessages -- No --> CheckAfterWorldBook{"8. Has 'After' World Book entries?"}
    
    CheckAfterWorldBook -- Yes --> AddAfter["Format & Add 'After' entries (world_context_after)"]
    AddAfter --> SubWbAfterBudget["Deduct Budget: budget -= TokenEstimator(worldContextAfter)"]
    SubWbAfterBudget --> OutputList
    
    CheckAfterWorldBook -- No --> OutputList["9. Build final ordered message list & send payload with Sampler controls, Logit Bias & Tool settings"]
Loading

Project Structure

lib/
โ”œโ”€โ”€ app.dart                               # Main Application entry widget
โ”œโ”€โ”€ main.dart                              # App entry main() function
โ”œโ”€โ”€ core/                                  # Common/Core modules
โ”‚   โ”œโ”€โ”€ constants/                         # Global constants & key mapping
โ”‚   โ”œโ”€โ”€ di/                                # Dependency injection setup (injectable)
โ”‚   โ”œโ”€โ”€ error/                             # Failure and exception definitions
โ”‚   โ”œโ”€โ”€ localization/                      # Multi-language l10n logic
โ”‚   โ”œโ”€โ”€ theme/                             # ThemeData & color palettes
โ”‚   โ””โ”€โ”€ utils/                             # Helpers (Token Estimator, File Saver, Connection Checker)
โ”œโ”€โ”€ data/                                  # Data layer implementation
โ”‚   โ”œโ”€โ”€ datasources/                       # Local DB, SharedPreferences, API export services
โ”‚   โ”œโ”€โ”€ models/                            # Data models & serializations
โ”‚   โ””โ”€โ”€ repositories/                      # Repository implementations
โ”œโ”€โ”€ domain/                                # Domain layer (interfaces & core models)
โ”‚   โ”œโ”€โ”€ entities/                          # Plain entity classes (Character, Chat, Message, StoryState, WorldBook, LlmConfig)
โ”‚   โ””โ”€โ”€ repositories/                      # Repository abstract contracts
โ””โ”€โ”€ presentation/                          # Presentation layer (UI & state)
    โ”œโ”€โ”€ common/                            # Common widgets (Responsive, Sidebar, Scaffolds)
    โ”œโ”€โ”€ router/                            # Routing configuration (go_router)
    โ””โ”€โ”€ features/                          # Feature blocks
        โ”œโ”€โ”€ character/                     # Character Creator/Edit page and BLoC
        โ”œโ”€โ”€ chat/                          # Chat Interface, Bubble, Input, Drawer, and BLoC
        โ”œโ”€โ”€ extractor/                     # AI Worldview Extractor page and BLoC
        โ”œโ”€โ”€ home/                          # Home screen Grid and BLoC
        โ”œโ”€โ”€ settings/                      # Config panel, Theme/Data settings, and BLoC
        โ””โ”€โ”€ splash/                        # Splash loading page

Roadmap / TODO

  • Prompt Caching Friendly Context Refactoring:
    • Reorder the payload assembly in BuildPrompt by moving highly static layers (e.g., core System instructions and conversation Summary) to the absolute top, and placing frequently changing segments (e.g., dynamic World Context and Recent Messages) at the bottom. This ensures high Cache Hit Rates in long chats, reducing latency and cost.
    • Implement a lock/debounce mechanism for matched World Book entries to prevent frequent context-prefix jitter.
  • SillyTavern Compatibility & Advanced LLM Orchestration:
    • Implement full compatibility for SillyTavern character cards (V1/V2 PNG/JSON) and World Info imports/exports.
    • Build advanced user persona library with custom avatar support.
    • Upgrade World Book trigger engine (secondary keywords, scan depth, delay, cooldown, sticky retention, insertion positions).
    • Expose advanced sampler configurations, custom sampler presets, logit bias maps, and OpenAI-compatible tool calling.
    • Add group chat advanced scheduling (modes, auto delay, queue depth injection).
    • Support multi-profile token estimation, regex text replacement rules, media asset libraries, and automatic background backups.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A modern, responsive Flutter application for managing interactive AI roleplay characters, world lore (World Books), and chat conversations with custom API configurations.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors