# 🧠 Context-Aware Response Generator **Feature Added:** October 11, 2025 **Status:** ✅ Complete and Tested --- ## Overview The Context-Aware Response Generator allows storytellers to generate AI responses that take into account multiple characters' actions and messages simultaneously. This is a powerful tool for creating cohesive narratives that incorporate everyone's contributions. --- ## Key Features ### 1. **Multi-Character Selection** 🎭 - Select one or more characters to include in the context - Visual indicators show which characters have pending messages - "Select All Pending" quick action button - Character selection with checkboxes showing message count ### 2. **Two Response Types** 📝 #### Scene Description (Broadcast) - Generates a narrative that addresses all selected characters - Can be used as a scene narration (broadcast to all) - Perfect for environmental descriptions or group events #### Individual Responses (Private) - Generates personalized responses for each selected character - **Automatically parses and distributes** responses to individual characters - Sends privately to each character's conversation - Clears pending response flags ### 3. **Smart Context Building** 🔍 The system automatically gathers and includes: - Current scene description - Recent public actions (last 5) - Each character's profile (name, description, personality) - Recent conversation history (last 3 messages per character) - Optional additional context from storyteller ### 4. **Response Parsing** 🔧 For individual responses, the system recognizes multiple formats: ``` **For Bargin:** Your response here **For Willow:** Your response here or For Bargin: Your response here For Willow: Your response here ``` The backend automatically: 1. Parses each character's section 2. Adds to their private conversation history 3. Clears their pending response flag 4. Sends via WebSocket if connected --- ## How to Use ### As a Storyteller: 1. **Open the Generator** - Click "▶ Show Generator" in the storyteller dashboard - The section expands with all controls 2. **Select Characters** - Check the boxes for characters you want to include - Or click "Select All Pending" for quick selection - See selection summary below checkboxes 3. **Choose Response Type** - **Scene Description:** For general narration or environmental descriptions - **Individual Responses:** For personalized replies to each character 4. **Configure Options** - Select LLM model (GPT-4o, GPT-4, etc.) - Add optional context/guidance for the AI 5. **Generate** - Click "✨ Generate Context-Aware Response" - Wait for AI generation (a few seconds) - Review the generated response 6. **Use the Response** - For scenes: Click "Use as Scene" to populate the scene textarea - For individual: Responses are automatically sent to characters - You'll get a confirmation alert showing who received responses --- ## Technical Implementation ### Backend Endpoint **POST** `/sessions/{session_id}/generate_contextual_response` **Request Body:** ```json { "character_ids": ["char-id-1", "char-id-2"], "response_type": "individual" | "scene", "model": "gpt-4o", "additional_context": "Make it dramatic" } ``` **Response (Individual):** ```json { "response": "Full generated response with all sections", "model_used": "gpt-4o", "characters_included": [{"id": "...", "name": "..."}], "response_type": "individual", "individual_responses_sent": { "Bargin": "Individual response text", "Willow": "Individual response text" }, "success": true } ``` ### Context Building The prompt sent to the LLM includes: ``` You are the storyteller/game master in an RPG session. Here's what the characters have done: Current Scene: [if set] Recent public actions: - Public message 1 - Public message 2 Character: Bargin Description: A dwarf warrior Personality: Gruff and brave Recent messages: Bargin: I push open the door You (Storyteller): You hear creaking hinges Character: Willow Description: An elven archer Personality: Cautious and observant Recent messages: Willow: I look for traps You (Storyteller): Roll for perception Additional context: [if provided] Generate [scene/individual responses based on type] ``` ### Response Parsing (Individual Mode) The backend uses regex patterns to extract individual responses: ```python patterns = [ r'\*\*For CharName:\*\*\s*(.*?)(?=\*\*For\s+\w+:|\Z)', r'For CharName:\s*(.*?)(?=For\s+\w+:|\Z)', r'\*\*CharName:\*\*\s*(.*?)(?=\*\*\w+:|\Z)', r'CharName:\s*(.*?)(?=\w+:|\Z)', ] ``` Each matched section is: 1. Extracted and trimmed 2. Added to character's conversation history 3. Sent via WebSocket if character is connected 4. Pending flag cleared --- ## UI Components ### Generator Section Located in `StorytellerView`, between the scene section and character list: **Visual Design:** - Pink/red gradient header (stands out from other sections) - Collapsible with show/hide toggle - Clear sections for each configuration step - Visual feedback for pending characters **Layout:** ``` ┌─────────────────────────────────────────┐ │ 🧠 AI Context-Aware Response Generator │ │ ▼ Hide │ ├─────────────────────────────────────────┤ │ Description text │ │ │ │ Character Selection │ │ ☑ Bargin (●) (3 msgs) │ │ ☑ Willow (2 msgs) │ │ │ │ Response Type: [Scene/Individual ▼] │ │ Model: [GPT-4o ▼] │ │ Additional Context: [textarea] │ │ │ │ [✨ Generate Context-Aware Response] │ │ │ │ Generated Response: │ │ ┌─────────────────────────────────┐ │ │ │ Response text here... │ │ │ └─────────────────────────────────┘ │ │ [Use as Scene] [Clear] │ └─────────────────────────────────────────┘ ``` --- ## Benefits ### For Storytellers ✅ **Save Time** - Generate responses considering all players at once ✅ **Consistency** - AI maintains narrative coherence across characters ✅ **Context Awareness** - Responses reference recent actions and personality ✅ **Flexibility** - Choose between broadcast scenes or individual replies ✅ **Efficiency** - Automatic distribution of individual responses ### For Players ✅ **Better Immersion** - Responses feel more connected to the story ✅ **No Waiting** - Storyteller can respond to multiple players quickly ✅ **Personalization** - Individual responses tailored to each character ✅ **Privacy Maintained** - Individual responses still private --- ## Example Use Cases ### Use Case 1: Party Splits Up **Scenario:** Bargin goes through the front door, Willow scouts around back **Action:** 1. Select both Bargin and Willow 2. Choose "Individual Responses" 3. Add context: "The building is guarded" 4. Generate **Result:** - Bargin gets: "As you push open the door, guards immediately turn toward you..." - Willow gets: "Around the back, you spot an unguarded window..." ### Use Case 2: Group Enters New Area **Scenario:** All players enter a mysterious temple **Action:** 1. Select all characters 2. Choose "Scene Description" 3. Generate **Result:** A cohesive scene describing the temple that references all characters' recent actions and reactions. ### Use Case 3: Quick Responses to Pending Messages **Scenario:** 3 characters have asked questions **Action:** 1. Click "Select All Pending (3)" 2. Choose "Individual Responses" 3. Generate **Result:** All three characters receive personalized answers, pending flags cleared. --- ## Additional Feature: Session ID Copy Button **Also Added:** Copy button next to Session ID in Storyteller dashboard **Usage:** - Click "📋 Copy" button next to the Session ID - ID copied to clipboard - Alert confirms successful copy - Makes sharing sessions easy **Location:** Storyteller header, next to session ID code --- ## CSS Classes Added ```css .contextual-section .contextual-header .contextual-generator .contextual-description .character-selection .selection-header .btn-small .character-checkboxes .character-checkbox .checkbox-label .pending-badge-small .message-count .selection-summary .response-type-selector .response-type-help .model-selector-contextual .additional-context .btn-large .generated-response .response-content .response-actions .session-id-container .btn-copy ``` --- ## Testing ### Manual Testing Checklist - [ ] Select single character - generates response - [ ] Select multiple characters - includes all in context - [ ] Scene description - generates cohesive narrative - [ ] Individual responses - parses and sends to each character - [ ] "Select All Pending" button - selects correct characters - [ ] Additional context - influences AI generation - [ ] Model selection - uses chosen model - [ ] Copy session ID button - copies to clipboard - [ ] Collapse/expand generator - UI works correctly - [ ] Character receives individual response - appears in their conversation - [ ] Pending flags cleared - after individual responses sent --- ## Future Enhancements Potential improvements for later versions: 1. **Response Templates** - Save common response patterns 2. **Batch Actions** - Send same scene to subset of characters 3. **Response History** - View previous generated responses 4. **Fine-tune Prompts** - Custom prompt templates per game 5. **Voice/Tone Settings** - Adjust AI personality (serious/playful/dark) 6. **Character Reactions** - Generate suggested player reactions 7. **Conversation Summaries** - AI summary of what happened 8. **Export Context** - Save context for reference --- ## Files Modified ### Backend - `main.py` - Added `ContextualResponseRequest` model - Added `/generate_contextual_response` endpoint - Added response parsing logic - Added individual message distribution ### Frontend - `frontend/src/components/StorytellerView.js` - Added contextual response state variables - Added character selection functions - Added response generation function - Added copy session ID function - Added generator UI section - `frontend/src/App.css` - Added `.contextual-*` styles - Added `.character-checkbox` styles - Added `.btn-copy` styles - Added `.session-id-container` styles - Added `.response-type-help` styles --- ## Summary The Context-Aware Response Generator is a powerful tool that significantly improves storyteller efficiency. By allowing the storyteller to generate responses that consider multiple characters simultaneously, it: - Reduces response time - Improves narrative consistency - Maintains privacy through automatic distribution - Provides flexibility between scene and individual responses - Makes managing multiple players much easier Combined with the session ID copy button, these features make the storyteller experience more streamlined and professional. **Status:** ✅ Ready for use!