Spaces:
Running
Download README.md from cereeenn120/StoryChatBot: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/spaces/cereeenn120/StoryChatBot/resolve/main/README.md
- Command line
-
hf download hf://spaces/cereeenn120/StoryChatBot/README.md
-
curl -L -o README.md https://huggingface.co/spaces/cereeenn120/StoryChatBot/resolve/main/README.md
title: StoryChatBot
emoji: π¬
colorFrom: yellow
colorTo: purple
sdk: docker
pinned: true
short_description: An Ensemble Story Chatbot
StoryChatBot
A browser-based ensemble story app with a standalone frontend and a small Python HTTP server. The UI and API do not use Gradio.
Features
- Story groups β Choose a category and group, then play a group character or create an original role
- Narrator-led stories β The model opens the story automatically and narrates an ensemble cast
- Three-layer memory β Session-isolated history, rolling summary, and long-term story facts
- Standalone UI β Main menu, story setup, chat, configurations, load story, and requests screens
- Content-aware model choices β Hide mature model variants while mature content is disabled
- Session save files β Load and download JSON conversation saves
- Character dialogue markers β In-world speech uses a stable speaker-and-quote format for later UI parsing
- Requests form β Frontend-only request draft; email delivery is not connected yet
Project structure
CharacterChatBot/
βββ app.py # Starts the standalone web server
βββ server.py # HTTP API and static frontend server
βββ Dockerfile # Hugging Face Docker Space setup
βββ requirements.txt
βββ frontend/ # HTML, CSS, and browser-side app
β βββ index.html
β βββ styles.css
β βββ app.js
βββ characters/ # Category / character group / character JSON
β βββ tv_series/
β βββ addams_family/
β βββ wednesday_addams.json
βββ engine/ # Core logic (no UI dependencies)
β βββ chat.py # LLM streaming generator
β βββ prompt_builder.py # System prompt and character library
β βββ static_files.py # Bounded static JSON/text cache
β βββ memory.py # Three-layer memory system
β βββ memory_controls.py # Manual facts and source exclusions
β βββ memory_jobs.py # Bounded background extraction
β βββ parser.py # Action/thought response parser
β βββ suggestions.py # Reply suggestion generator
β βββ persona.py # User persona management
β βββ relationship.py # Independent relationship axes
βββ prompts/ # Prompt templates (plain text)
βββ memory/sessions/ # Auto-created, isolated by browser session
βββ assets/ # Matching category / group / character image folders
βββ tv_series/
βββ addams_family/
βββ wednesday_addams/
βββ body_01.jpg # Character library image
βββ body_02.webp # Optional additional body images
βββ portrait_01.png # Chat message avatar
Character library organization
Characters are stored under a media category and a franchise or character group. The sidebar filters in three steps: category, group, then character. Current categories include Movies, TV Series, Video Games, and Anime and Manga. Add more top-level categories as the library grows.
characters/<category>/<group>/<character_id>.json
assets/<category>/<group>/<character_id>/
For example, Wednesday Addams lives at characters/tv_series/addams_family/wednesday_addams.json. Its image folder can hold multiple numbered images: body_01.jpg, body_02.webp, and portrait_01.png. body_01 is used in the Character library sidebar; portrait_01 is used beside messages in chat. If a portrait is absent, the chat avatar falls back to the first body image.
Each character JSON stores library_category and character_group display labels as well as the legacy categories array. Directory names use lowercase snake case. Keep the JSON id equal to the filename stem; conversations and save files continue to refer to this stable ID.
Adding a new character
- Create
characters/<category>/<group>/{character_id}.json:
{
"id": "my_character",
"name": "My Character",
"categories": ["My Franchise"],
"library_category": "TV Series",
"character_group": "My Franchise",
"description": "One-line description shown in the selector.",
"identity": {
"role": "Their role or profession",
"background": "Brief backstory"
},
"personality": ["trait1", "trait2", "trait3"],
"speech_style": {
"tone": ["calm", "precise"],
"formality": "formal",
"sentence_style": "short_to_medium",
"uses_humor": false,
"uses_rhetorical_questions": false,
"avoids_excessive_enthusiasm": true
},
"behavior": {
"shows_emotions": true,
"deflects_uncomfortable_topics_with_humor": false
},
"world": {
"universe": "Original",
"setting": "Where they live",
"description": "World context for the LLM."
},
"roleplay": {
"action_format": "<action>{content}</action>",
"thought_format": "<thought>{content}</thought>",
"break_character": false
},
"system_prompt": "Character-specific fine-tuning. This adds to global rules, not replaces them.",
"greeting": "The character's opening line when the chat starts.",
"example_dialogues": [
{
"situation": "Optional context",
"user": "Example user message",
"character": "Example character response"
}
],
"visuals": {
"avatar": "assets/tv_series/my_franchise/my_character/body_01.jpg",
"portrait": "assets/tv_series/my_franchise/my_character/portrait_01.webp"
}
}
Add images under the matching
assets/<category>/<group>/<character_id>/folder. Name library imagesbody_01.jpg,body_02.webp, etc.; name the chat avatarportrait_01.png(additional numbered variants are supported). PNG, JPG, JPEG, and WebP are supported. If no portrait exists, the first body image is used in chat. Character images are stored directly in Git so they work in checkouts without Git LFS.Restart the app. The character will appear in its category and character group on the New chat screen.
Local setup
Requires Python 3.10+.
git clone https://huggingface.co/spaces/your-username/CharacterChatBot
cd CharacterChatBot
pip install -r requirements.txt
export HF_TOKEN=hf_your_token_here
python app.py
Open http://127.0.0.1:7860 after the server starts. Chat requests need an HF_TOKEN
environment variable; browsing the library and editing configurations do not.
HuggingFace Space deployment
- Push your changes to the Space repository. The Docker Space reads
Dockerfile. - Go to Settings β Variables and secrets β New secret.
- Add
HF_TOKENwith your Hugging Face API token to enable chat inference. - The Space restarts automatically and picks up the secret.
Memory system
Each browser session has its own per-character snapshot under
memory/sessions/{session_id}/{character_id}.json. The session ID is created in
the browser and validated by the local HTTP server; uploaded saves cannot choose
their storage path.
Switching characters restores that session's complete visible conversation.
Clearing the chat clears its transcript, summary, facts, exclusions, and relationship state. Retry and
undo update the same history the model uses; changing already-summarized content
invalidates its derived memory.
The complete transcript is retained for display and export. Once the unsummarized history exceeds 20 messages (not 20 user/assistant pairs), a batch of about 10 older messages is summarized after the answer is displayed. When extraction falls behind, a batch can grow to 40 messages (plus one to keep a reply with its user turn). This periodic model call also extracts long-term facts and relationship developments. Subsequent prompts contain the cumulative summary, up to 40 automatic facts plus 60 manually pinned facts, relationship context, and the remaining recent messages. Extraction runs in a background pool with at most two jobs across the app and one per conversation. The chat request completes without waiting for extraction. There is no growing job queue: if the pool is busy, messages remain intact and scheduling is tried after a later response. The same retry policy applies to extraction errors.
Before committing, a worker checks a separate memory revision, its original transcript prefix, and the summary it started from. Appending completed turns does not invalidate extraction; only derived fields are merged into the newer conversation. Edits, resets, imports, and memory/relationship setting changes still invalidate pending work. Memory-only updates do not advance the transcript revision. A response being streamed can therefore append to the current snapshot without losing a summary that finished in the meantime. Recent model context has a fallback limit of 40 messages and 24,000 characters so a slow or failed summary cannot make it grow without bound. Older unsummarized turns can temporarily be omitted, and an oversized final message is clipped with an explicit marker. These limits apply to recent history, not the system prompt or current user input. The full transcript remains available for display, later summarization, and export. Invalid relationship observations are discarded without discarding an otherwise valid summary.
Storage is isolated by browser session, not an authenticated user account.
Refreshing the page or opening a new browser session starts fresh; use Save /
Load to resume later. Legacy shared memory/{character_id} files are never
loaded automatically because their owner is unknown. Existing version 1.0 and 2.0 save
files can still be imported explicitly into the current session.
Save files use version 3.0 and include the full visible transcript, persona, summary, facts and their sources, summary position, memory exclusions, and relationship options and events. Imports validate the entire file before writing: known character ID, supported version, text-only user/assistant messages, memory importance and provenance, relationship events, field lengths, and a 4 MB file limit. Exports have unique filenames. Each snapshot is replaced atomically; in-process revision checks protect concurrent writes in the standard single-process server. Deployments with multiple app processes would require a shared transactional store instead of this file backend.
Translation is off by default in both the UI and backend. The main model streams in the selected language. If translation is enabled explicitly, the displayed translation is also the persisted conversation, so reload and subsequent context match what the user saw.
Reply suggestions remain opt-in through the Suggest replies button. Their single model call receives the selected language and the applied user persona. On failure, four neutral fallback suggestions are returned in the selected UI language without another model call. Changing language, persona, character, or conversation clears the old suggestion buttons.
Memory controls and editing
Open Memories to add a fact with Remember, or select a saved fact to Update selected or Forget selected. Manual facts are pinned and automatic extraction cannot overwrite them. Editing or forgetting invalidates pending extraction, clears the summary for rebuilding, and excludes the fact's recorded source messages and verbatim echoes from future model context. The visible transcript remains unchanged. Other automatic facts and relationship events sharing those sources are removed too.
Forgetting is source-based, not guaranteed semantic erasure: paraphrases elsewhere or separately pinned facts can still contain the information. Exact normalized re-extraction is blocked; explicitly remembering the same text removes that block.
The chat toolbar can copy a message, regenerate the latest answer, or undo the last exchange. These actions update the same conversation snapshot that the model uses. Previous replies are not saved as alternate branches.
Relationship state
Trust, familiarity, romantic closeness, and sexual attraction develop independently. Romance and attraction are tracked by default for each character in a session; disabling an axis clears its recorded developments. Low trust or familiarity does not prevent romance or attraction, and no fixed relationship route is enforced. The state describes the character's attitude toward the user persona and does not assume reciprocal feelings or override the character's personality and motivations.
Relationship state is added to the character context without numeric scores. Changes are extracted with periodic memory summaries, and source-linked events allow edits and retries to roll back affected developments. Save files preserve this state.
Static file cache
Character JSON and the system, reply-suggestion, and memory-extraction prompt files are cached in process RAM (up to 64 entries, least recently used eviction). Each access checks file metadata; edits and atomic replacements refresh the entry. Missing or invalid files raise errors instead of silently reusing old content. Character data is deep-copied for each caller to avoid shared mutations. The cache is protected by a lock for chat and background worker access.
Conversation history, personas, summaries, and user memories are not cached here. This saves local file reads and JSON parsing only; model calls and token usage remain unchanged. Restarting the process clears the cache.
Configuration
Available models and languages live in engine/models.py. The browser stores
language, model, translation, and mature-content choices locally; the default
model is also defined there for new browser sessions.
The Requests screen is a frontend-only draft form. It does not send email or transmit the request.