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.
- ๐ญ 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, andseed. - Customize token-level logit bias maps, reasoning effort, and logprobs/top logprobs.
- Create, save, and apply reusable Sampler Presets.
- Configure advanced parameters: temperature,
- ๐ ๏ธ 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.
- Framework: Flutter (SDK ^3.12.0)
- State Management: flutter_bloc (BLoC pattern)
- Database: sqflite (with FFI support on Desktop & Web)
- Dependency Injection: get_it & injectable
- Routing: go_router
- Networking: dio
- Theme: dynamic_color
- Rich Text Rendering: flutter_markdown
Make sure you have Flutter SDK installed on your system (stable channel recommended).
-
Clone the repository:
git clone https://github.com/tylevnovik/playbook.git cd playbook -
Get dependencies:
flutter pub get
-
Run code generation: This project uses
build_runnerandinjectablefor dependency injection and serialization. Run the following command to generate the required configuration files:flutter pub run build_runner build --delete-conflicting-outputs
-
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
- Run on connected device (Mobile, Desktop, or Web):
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"]
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
- Prompt Caching Friendly Context Refactoring:
- Reorder the payload assembly in
BuildPromptby moving highly static layers (e.g., coreSysteminstructions and conversationSummary) to the absolute top, and placing frequently changing segments (e.g., dynamicWorld ContextandRecent 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.
- Reorder the payload assembly in
- 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.
This project is licensed under the MIT License - see the LICENSE file for details.