Mu Prompt Management Framework
Mu Prompt Management Framework
Table of Contents
- Overview
- System Architecture
- Core Components
- LangChain User Profiling
- Context Analysis
- Progressive Discovery Protocol
- Template System
- Prompt Generation Flow
- Adaptive Response System
- Emergency Detection
- Integration with Claude
- Development Guide
Overview
What is the Mu Prompt System?
The Mu Prompt System is a sophisticated dynamic prompt generation framework that powers the Ask Mü cat health chatbot. Unlike static prompts, every response is generated from a fresh analysis of:
- User communication patterns (via LangChain AI profiling)
- Conversation context (symptoms, cat profile, urgency)
- Conversation phase (greeting → symptom gathering → assessment)
- User traits (anxiety level, experience, preferred style)
Key Innovation: Progressive Discovery Protocol
- Maximum 2 questions per response
- Context-aware: Analyzes existing information before asking
- Urgency-sensitive: Emergency symptoms prioritized
- Adaptive tone: Matches user’s communication style
Production Status
- Status: ✅ Fully Operational
- Deployed: https://askmu.live
- Model: Claude Sonnet 4
- Version: Mu Prompt System v3 with LangChain
- Last Update: October 2025 (Early profiling enabled)
Design Goals
- Empathy-First: Understand user’s emotional state and adapt tone
- Efficient Discovery: Gather critical information without overwhelming
- Safety-Conscious: Detect emergencies and escalate appropriately
- Personalized: Adapt to each user’s communication style and experience
- Context-Aware: Build on previous interactions, avoid redundancy
System Architecture
High-Level Architecture
User Message
│
▼
┌────────────────────────────────────────────────────────┐
│ Mu Prompt System │
│ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 1. Conversation Context Analyzer │ │
│ │ - Extract cat profile (name, age, breed) │ │
│ │ - Detect symptoms and urgency │ │
│ │ - Assess anxiety level │ │
│ │ - Identify experience level │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 2. LangChain User Profiler (2+ messages) │ │
│ │ - Communication style analysis │ │
│ │ - Personality profile matching │ │
│ │ - Confidence level detection │ │
│ │ - Learning preference identification │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 3. Conversation Memory System │ │
│ │ - Retrieve conversation history │ │
│ │ - Update context in database │ │
│ │ - Track conversation phases │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 4. Template Engine │ │
│ │ - Load PromptL templates │ │
│ │ - Interpolate context variables │ │
│ │ - Apply conditional sections │ │
│ │ - Assemble final prompt │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
└──────────────────────┼──────────────────────────────────┘
│
▼
Dynamic System Prompt
│
▼
Claude Sonnet 4 API (300 token max)
│
▼
Empathetic, Adaptive Response
Component Interaction
┌─────────────────┐
│ User Message │
└────────┬────────┘
│
▼
┌─────────────────────────────────────────────────┐
│ MuPromptSystem.generateDynamicPrompt() │
│ │
│ 1. getConversationContext(sessionId) │
│ └─> Returns: history, catProfile, context │
│ │
│ 2. contextAnalyzer.analyze(history, message) │
│ └─> Returns: urgency, symptoms, traits │
│ │
│ 3. langchainProfiler.analyzeUserProfile() │
│ └─> Returns: style, anxiety, personality │
│ │
│ 4. memorySystem.updateConversationContext() │
│ └─> Saves updated context to database │
│ │
│ 5. templateEngine.render(promptData) │
│ └─> Returns: final system prompt │
└──────────────────────┬──────────────────────────┘
│
▼
System Prompt for Claude
Core Components
1. MuPromptSystem (Orchestrator)
File: lib/mu-prompt-system.js
Purpose: Main orchestration class that coordinates all components to generate dynamic prompts.
Key Features:
- Integrates all subsystems (context, profiling, memory, templates)
- Manages early profiling (2-message threshold)
- Handles fallback when LangChain unavailable
- Logs profiling status and decisions
Initialization:
const promptSystem = new MuPromptSystem(
supabaseClient,
anthropicApiKey,
{ earlyProfiling: true } // Enable 2-message profiling
);
Main Method:
const promptData = await promptSystem.generateDynamicPrompt(
sessionId,
userMessage
);
// Returns: Complete data structure for template rendering
2. ConversationContextAnalyzer
File: lib/conversation-context-analyzer.js
Purpose: Analyzes messages to extract actionable context (symptoms, urgency, traits).
Analysis Dimensions:
| Dimension | Values | Purpose |
|---|---|---|
| Conversation Phase | initial, context_building, detail_gathering, assessment, guidance | Determines appropriate response type |
| Urgency Level | emergency, urgent, routine | Prioritizes response content |
| Anxiety Level | low, moderate, high, panic | Adjusts empathy and tone |
| Experience Level | first-time, beginner, experienced | Adjusts complexity |
| Communication Style | emotional, factual, low-literacy | Matches response style |
| Emotional State | calm, concerned, worried, panicked | Fine-tunes empathy |
Keyword Detection:
{
emergency: [
'trouble breathing', 'gasping', 'blue gums',
'unconscious', 'seizure', 'severe bleeding',
'collapsed', 'paralyzed'
],
urgent: [
'not eating', 'vomiting', 'diarrhea',
'lethargy', 'hiding', 'blood', 'pain'
],
routine: [
'scratching', 'grooming', 'sleeping more',
'different behavior'
]
}
Cat Profile Extraction:
{
name: /(?:my cat|his name|her name is|called)\s+(\w+)/i,
age: /(\d+)\s*(?:years?|months?)\s*old/i,
breed: /(persian|siamese|maine coon|tabby|calico)/i,
gender: /\b(he|she|male|female|boy|girl)\b/i
}
3. ConversationMemorySystem
File: lib/conversation-memory-system.js
Purpose: Database-backed persistence for conversation context.
Database Operations:
// Retrieve context
const context = await memorySystem.getConversationContext(sessionId);
// Returns: { catProfile, symptoms, history, phase, ... }
// Update context
await memorySystem.updateConversationContext(sessionId, {
catProfile: { name: 'Luna', age: 3 },
symptoms: ['vomiting', 'lethargy'],
anxietyLevel: 'high',
conversationPhase: 'symptom_gathering'
});
Context Storage:
- Table:
conversation_context - Indexed by:
session_id - Includes: cat profile, symptoms, user traits, phase, question count
Phase Management:
const maxQuestions = memorySystem.getMaxQuestionsForPhase(phase);
// initial: 2 questions
// context_building: 2 questions
// detail_gathering: 1 question (already have context)
// assessment: 0 questions (provide guidance)
4. SimpleTemplateEngine
File: lib/simple-template-engine.js
Purpose: Processes PromptL templates with variable interpolation.
Template Location: prompts/ directory
Syntax:
# Variable interpolation
{{catProfile.name}}
# Conditional sections
{{#if urgencySignals.emergency}}
EMERGENCY PROTOCOL ACTIVATED
{{/if}}
{{#unless catProfile.name}}
Ask for cat's name
{{/unless}}
# Loops
{{#each symptoms}}
- {{this}}
{{/each}}
Rendering:
const prompt = await templateEngine.render('base-prompt', {
catProfile: { name: 'Luna', age: 3 },
urgencySignals: { emergency: [], urgent: ['vomiting'] },
anxietyLevel: 'high'
});
LangChain User Profiling
Overview
File: lib/langchain/langchain-user-profiler.js
Purpose: AI-powered semantic analysis of user communication patterns using Claude Sonnet 4.
Activation: Starts at 2nd user message (early profiling enabled October 2025)
Previous Threshold: 3rd message (before October 2025 update)
Why Early Profiling?
- Faster personalization (one message sooner)
- Better first impressions (adapt tone earlier)
- Improved user experience for anxious users
Profiling Dimensions
1. Communication Style
| Style | Description | Response Adaptation |
|---|---|---|
| emotional | Seeks empathy and support | Warm, reassuring tone; emotional validation |
| factual | Wants direct information | Concise, evidence-based responses |
| low-literacy | Uses simple language | Plain language, short sentences, avoid jargon |
2. Anxiety Level
| Level | Indicators | Response Adaptation |
|---|---|---|
| low | Calm, routine inquiry | Standard empathetic tone |
| moderate | Some concern | Extra reassurance |
| high | Worried, multiple questions | High empathy, structured guidance |
| panic | “HELP!”, “emergency”, excessive punctuation | Immediate calm-down, clear next steps |
3. Experience Level
| Level | Indicators | Response Adaptation |
|---|---|---|
| first-time | “never had a cat”, “new owner” | Detailed explanations, extra context |
| beginner | Basic questions, uncertainty | Moderate detail, encouraging |
| experienced | Mentions other cats, vet visits | Higher complexity, less hand-holding |
4. Preferred Response Style
| Style | Description |
|---|---|
| concise | Brief, to-the-point answers |
| detailed | Comprehensive explanations with background |
5. Confidence Level
| Level | Description |
|---|---|
| confident | Trusts their judgment, wants validation |
| uncertain | Second-guessing, needs guidance |
| overwhelmed | Feeling lost, needs structured support |
| building | Growing confidence, needs reinforcement |
6. Learning Preference
| Preference | Adaptation |
|---|---|
| visual | Use analogies and examples |
| analytical | Provide logical reasoning and evidence |
| practical | Focus on actionable steps |
| contextual | Give background and situational understanding |
Personality Profiles
The system matches users to personality archetypes for tone guidance:
File: lib/langchain/personality-profiles.js
Profiles:
-
Anxious First-Timer
- High anxiety + low experience
- Needs: Calm reassurance, step-by-step guidance
- Tone: Gentle, patient, structured
-
Concerned Experienced Owner
- Moderate anxiety + high experience
- Needs: Validation, differential diagnosis
- Tone: Respectful, collaborative
-
Calm Information Seeker
- Low anxiety + factual style
- Needs: Direct facts, evidence
- Tone: Professional, concise
-
Panicked Emergency
- Panic level + emergency keywords
- Needs: Immediate clear instructions
- Tone: Authoritative, calming, directive
-
Building Confidence
- Improving confidence + beginner
- Needs: Positive reinforcement
- Tone: Encouraging, supportive
Analysis Process
LangChain Invocation:
const profile = await langchainProfiler.analyzeUserProfile(
conversationHistory,
currentMessage
);
Analysis Prompt (sent to Claude Sonnet 4):
You are an expert at analyzing communication patterns to understand
user profiles for adaptive AI responses about cat behavior.
Analyze this cat owner's communication style and needs based on
their messages:
MESSAGE COUNT: 2
IMPORTANT: This is early analysis with only 2 message(s). Focus on
clear indicators while being conservative about confidence levels.
USER MESSAGES:
"""
Help! My cat Luna has been vomiting all morning. I'm really scared,
is this serious? She's only 3 years old.
I've tried giving her water but she won't drink. Should I take her
to the vet right away?
"""
ANALYSIS FRAMEWORK:
[Communication style, anxiety level, experience level descriptors...]
Respond with a JSON profile analysis.
Response Structure:
{
"communicationStyle": "emotional",
"anxietyLevel": "high",
"experienceLevel": "beginner",
"preferredResponseStyle": "detailed",
"confidenceLevel": "uncertain",
"learningPreference": "practical"
}
Confidence Scoring:
{
overall: 0.75, // Confidence in the entire profile
factorScores: {
communicationStyle: 0.9, // Very clear emotional language
anxietyLevel: 0.95, // "Help!", "scared", exclamation
experienceLevel: 0.6, // Limited data, conservative estimate
// ...
}
}
Personality Selection:
const personality = selectPersonality(profile);
// Returns: "Anxious First-Timer"
const instructions = getPersonalityInstructions(personality);
// Returns: Detailed guidance for response tone and structure
Fallback Mechanism
If LangChain analysis fails (API error, timeout):
getFallbackProfile() {
return {
profile: {
communicationStyle: 'emotional',
anxietyLevel: 'moderate',
experienceLevel: 'beginner',
preferredResponseStyle: 'concise',
confidenceLevel: 'uncertain',
learningPreference: 'practical'
},
confidence: { overall: 0.5 },
personalityProfile: {
name: 'Default Concerned Owner',
description: 'Fallback profile when analysis unavailable'
}
};
}
Progressive Discovery Protocol
Core Principle
Maximum 2 Questions Per Response
This is the fundamental constraint of the Mu system, designed to:
- Avoid overwhelming worried pet owners
- Maintain conversation flow
- Build trust through attentive listening
- Respect user’s emotional state
Question Budget System
Phase-Based Limits:
{
initial: 2, // Greeting, get basic context
context_building: 2, // Gather cat profile + symptoms
detail_gathering: 1, // Already have context, refine details
assessment: 0, // Provide guidance, no more questions
guidance: 0 // Final recommendations
}
Question Prioritization
Priority Order:
-
Emergency Verification (if emergency symptoms)
- “Have you contacted a veterinarian?”
- “Is [cat] still breathing normally?”
-
Timeline (if missing)
- “How long has this been going on?”
- “When did you first notice this?”
-
Severity (if unclear)
- “How often is this happening?”
- “Is it getting worse?”
-
Context (after basics covered)
- “Any recent changes in food or environment?”
- “Is [cat] eating/drinking normally?”
-
Clarification (lowest priority)
- “You mentioned [X], can you describe it more?”
Example Progressive Discovery
Message 1 (User):
“Help! My cat has been vomiting”
Mu Response (2 questions):
I’m sorry to hear your cat isn’t feeling well. Vomiting can be concerning.
To help you better:
- How long has the vomiting been going on?
- What’s your cat’s name and age?
Message 2 (User):
“Her name is Luna, she’s 3. Started this morning, maybe 4-5 times already.”
Mu Response (1 question):
Thank you for that information. I’m concerned about Luna vomiting 4-5 times this morning. This is more frequent than normal and warrants attention.
Has she been able to keep any water down, or is she vomiting everything?
[Assessment and guidance…]
Message 3 (User):
“She won’t drink at all. Just tried and she vomited again.”
Mu Response (0 questions - assessment phase):
This is concerning, and I recommend contacting your veterinarian today. Multiple vomiting episodes combined with refusing water can lead to dehydration…
[Detailed guidance, no questions]
Emergency Detection
Emergency Symptom Keywords
Immediate Veterinary Attention Required:
const EMERGENCY_SYMPTOMS = [
// Respiratory
'trouble breathing', 'difficulty breathing', 'gasping for air',
// Circulatory
'pale gums', 'blue gums', 'gray gums',
// Neurological
'unconscious', 'seizure', 'convulsing',
// Trauma
'severe bleeding', 'hit by car',
// Mobility
'can\'t walk', 'paralyzed', 'collapsed'
];
Emergency Protocol
When Emergency Detected:
⚠️ EMERGENCY PROTOCOL ACTIVATED ⚠️
SYMPTOMS DETECTED: {{#each urgencySignals.emergency}}{{this}}, {{/each}}
IMMEDIATE RESPONSE REQUIRED:
CRITICAL INSTRUCTIONS:
1. Contact emergency veterinary clinic immediately
2. If after hours, contact 24-hour emergency vet
3. Do NOT wait to see if it improves
4. Transport safely - avoid unnecessary movement
TIME IS CRITICAL. Please act now.
Response Characteristics:
- Directive tone: Clear commands, not suggestions
- Urgent but not panicking: Calm authority
- Action-focused: Immediate steps only
- Minimal questions: Ask ONLY “Have you contacted a vet?”
- Short sentences: Easy to process under stress
Integration with Claude
API Configuration
Model: claude-sonnet-4-20250514
Temperature: 0.7 (balanced creativity and consistency)
Max Output Tokens: 300 (cost control + concise responses)
System Prompt
Structure:
{
model: 'claude-sonnet-4-20250514',
max_tokens: 300,
temperature: 0.7,
system: generatedPrompt, // Dynamic prompt from template
messages: conversationHistory
}
Token Budget:
System Prompt: ~1500 tokens
Conversation History (10 messages): ~1000 tokens
Current User Message: ~100 tokens
---
Total Input: ~2600 tokens
Max Output: 300 tokens
Total per request: ~2900 tokens
Cost: ~$0.003 per interaction
Development Guide
Adding New Templates
1. Create Template File:
touch prompts/new-scenario.promptl
2. Define Template:
# New Scenario Template
You are Mu, helping with [specific scenario].
CONTEXT:
{{catProfile.name}} is experiencing {{primarySymptom}}.
[Template content...]
3. Register in Template Engine:
// lib/simple-template-engine.js
const TEMPLATES = {
'base-prompt': 'base-prompt.promptl',
'new-scenario': 'new-scenario.promptl' // Add here
};
Testing Prompt Variations
Enable Detailed Logging:
// Set environment variable
LOG_PROMPT_GENERATION=true npm start
Log Output:
🔍 LangChain User Profiler: Performing semantic analysis...
🧠 LangChain profile analysis completed (2 messages): {
style: 'emotional',
anxiety: 'high',
experience: 'beginner',
confidence: 0.75,
personality: 'Anxious First-Timer'
}
Example Scenarios
Scenario 1: Anxious First-Time Owner
User Message:
“HELP!! My cat isn’t eating and I don’t know what to do! Is she dying??”
Context Analysis:
{
anxietyLevel: 'panic',
experienceLevel: 'first-time',
communicationStyle: 'emotional'
}
Mu Response:
First, take a deep breath. Not eating for a short time doesn’t always mean something serious, but I can see how worried you are, and I’m here to help.
To better understand what’s happening:
- How long has it been since your cat last ate?
- What’s your cat’s name and age?
You’re doing the right thing by reaching out. We’ll figure this out together.
Scenario 2: Emergency Situation
User Message:
“My cat just collapsed and won’t get up! Her gums look pale!”
Emergency Protocol Activated:
Mu Response:
⚠️ THIS IS AN EMERGENCY ⚠️
Your cat needs immediate veterinary attention. DO NOT WAIT.
IMMEDIATE ACTIONS:
- Call your emergency vet or 24-hour clinic NOW
- Keep your cat warm with a light blanket
- Minimize movement - transport carefully
Have you contacted a veterinary clinic yet?
Conclusion
The Mu Prompt Management Framework represents a sophisticated, adaptive system that:
- Analyzes user communication patterns with AI-powered LangChain profiling
- Tracks conversation context across multiple dimensions
- Adapts response style based on user needs
- Prioritizes information gathering through progressive discovery
- Templates dynamic prompts for consistent responses
- Integrates seamlessly with Claude Sonnet 4
Production Impact:
- More personalized user experiences
- Faster emergency detection
- Better information gathering efficiency
- Higher user satisfaction
Document Version: 1.0 Last Updated: October 1, 2025 System Status: ✅ Production (https://askmu.live) Framework Version: Mu Prompt System v3 with LangChain