myavana-ai-bot-test
v1.2.2
Published
Myavana-specific bot implementation
Readme
Myavana Chatbot Package
Advanced AI-powered hair care consultation chatbot for the Myavana platform with multi-model support and intelligent features.
=� Package Overview
Package Name: myavana-ai-bot-test
Version: 2.0.0
Purpose: Main Myavana chatbot with comprehensive hair care expertise and AI model orchestration
<� Features
Multi-Model AI: Gemini 2.0, Gemini 1.5, and xAI Grok integration
� Smart Prompt Management: Context-aware prompt generation
- � Response Caching: Intelligent caching for faster responses
- =� Analytics Integration: Comprehensive user behavior tracking
- = Error Recovery: Circuit breakers and fallback strategies
- <� Personalization: Adaptive responses based on user profiles
- =� Image Analysis: Hair assessment from uploaded photos
- = Hair Issue Detection: Automatic hair problem identification
- =� Product Recommendations: AI-powered product suggestions
<� Architecture
myavana/
�� src/
�� index.js # Legacy implementation (maintained)
�� enhancedIndex.js # New enhanced implementation
�� constructPrompt.js # Myavana-specific prompt construction
�� eventHandlers.js # Event handling (welcome, images)
�� system.js # System prompts and instructions
�� package.json
�� README.md=� Quick Start
Installation
# Install dependencies
cd packages/myavana
npm install
# Start enhanced server
npm start
# or
node src/enhancedIndex.jsEnvironment Variables
# AI Services
GOOGLE_AI_API_KEY=your_gemini_key
XAI_API_KEY=your_xai_key
OPENAI_API_KEY=your_openai_key
# Database
POSTGRES_HOST=localhost
POSTGRES_DB=myavana_bot
POSTGRES_USER=username
POSTGRES_PASSWORD=password
# Redis
REDIS_HOST=localhost
REDIS_PASSWORD=redis_password
# Application
NODE_ENV=production
LOG_LEVEL=info
PORT=3000>� AI Model Configuration
Model Hierarchy
The Myavana chatbot uses a sophisticated model hierarchy for optimal performance:
const modelConfig = {
primary: gemini20FlashExp, // Latest Gemini 2.0 Flash Experimental
fallback: gemini15Flash, // Reliable Gemini 1.5 Flash
finalFallback: 'xai-grok-3-mini-fast' // xAI Grok as last resort
};=� Chat Flow
Event Handling
Welcome Event
{
"eventName": "WELCOME",
"from": "user-123"
}Response: Interactive welcome menu with Myavana services overview.
Regular Chat
{
"message": "How can I improve my 4C hair texture?",
"from": "user-123",
"groupId": "conversation-456",
"eventName": "REGULAR"
}Response: Personalized hair care advice with product recommendations.
Image Analysis
{
"message": "What do you think of my hair?",
"from": "user-123",
"groupId": "conversation-456",
"eventName": "KOMMUNICATE_MEDIA_EVENT",
"metadata": {
"KM_CHAT_CONTEXT": {
"attachments": [{
"type": "image/jpeg",
"payload": { "url": "https://example.com/hair-photo.jpg" }
}]
}
}
}Response: Detailed hair analysis with personalized recommendations.
=� Smart Prompt System
Context-Aware Prompts
The smart prompt system generates contextually relevant prompts based on:
- User Profile: Hair type, concerns, goals, history
- Conversation History: Previous interactions and context
- Hair Issues: Reported problems and patterns
- Product Database: Available Myavana services and products
- Educational Content: FAQs, videos, testimonials
Prompt Construction
const prompt = await smartPromptManager.buildSmartPrompt(
userId,
message,
chatHistory,
userInfo,
allConversationsSummary
);<� Personalization Features
User Profiling
The system builds comprehensive user profiles including:
{
name: "User Name",
hair_type: "4C",
hair_texture: "Coarse",
porosity: "High",
hair_concerns: ["Dryness", "Breakage"],
hair_goals: ["Length Retention", "Moisture"],
confidence_level_inferred: "Medium",
journey_stage_intent: "Learning"
}=� Image Analysis
Hair Assessment Features
When users upload hair photos, the system analyzes:
- Hair Type/Curl Pattern: 1A-4C classification
- Texture Assessment: Fine, medium, coarse
- Condition Evaluation: Healthy, dry, damaged signs
- Density Estimation: Low, medium, high
- Scalp Condition: If visible in image
Analysis Response Format
<html>
<head>
<style>
/* Myavana branding styles */
.highlight { background-color: #fce5d7; }
</style>
</head>
<body>
<h3>Hair Analysis Results</h3>
<p>Based on your photo, I can see you have <span class="highlight">4C textured hair</span> with...</p>
<h3>Personalized Recommendations</h3>
<ul>
<li>Focus on moisture retention</li>
<li>Consider protective styling</li>
</ul>
</body>
</html>=� Analytics & Tracking
User Behavior Analytics
The system tracks:
- Conversation Metrics: Duration, message count, satisfaction
- Feature Usage: Image uploads, product clicks, FAQ views
- Hair Journey Progress: Issue resolution, goal achievement
- Engagement Patterns: Active times, preferred topics
Performance Metrics
- Response Times: AI model performance tracking
- Cache Hit Rates: Efficiency of response caching
- Error Rates: Model failures and recovery success
- User Satisfaction: Implicit and explicit feedback
=� Error Handling & Recovery
Circuit Breaker Pattern
if (errorRecovery.canMakeRequest('gemini20FlashExp')) {
// Try primary model
} else {
// Circuit is open, use fallback
}Error Categories
- AI_MODEL: Model unavailable or quota exceeded
- NETWORK: Connection issues or timeouts
- VALIDATION: Invalid input or request format
- DATABASE: Data access or storage issues
Recovery Strategies
- Model Fallback: Automatic failover to backup models
- Cached Responses: Serve cached content when possible
- Graceful Degradation: Simplified responses during issues
- User Communication: Clear error messages and guidance
>� Testing
Running Tests
# All tests
npm test
# With coverage
npm run test:coverage
# Watch mode
npm run test:watch
# Specific test files
npm test -- eventHandlers.test.js=� Deployment
Enhanced Implementation
Use the new enhanced implementation for production:
# Start enhanced server
node src/enhancedIndex.js
# With PM2
pm2 start src/enhancedIndex.js --name myavana-bot
# With Docker
docker run -p 3000:3000 myavana-chatbotHealth Monitoring
The enhanced implementation includes comprehensive health monitoring:
# Health check
curl http://localhost:3000/health
# Detailed metrics
curl http://localhost:3000/metrics
# Readiness probe
curl http://localhost:3000/ready=� API Documentation
Chat Endpoint
POST /webhook
Request:
{
"message": "How often should I wash my 4C hair?",
"from": "user-123",
"groupId": "conversation-456",
"eventName": "REGULAR"
}Response:
[
{
"messageType": "html",
"message": "<p>For 4C hair, I recommend washing <span class='highlight'>1-2 times per week</span>...</p>"
}
]Welcome Endpoint
POST /webhook
Request:
{
"eventName": "WELCOME",
"from": "user-123"
}Response: Interactive menu with Myavana services.
Image Analysis Endpoint
POST /webhook
Request:
{
"message": "Analyze my hair",
"from": "user-123",
"groupId": "conversation-456",
"eventName": "KOMMUNICATE_MEDIA_EVENT",
"metadata": {
"KM_CHAT_CONTEXT": {
"attachments": [{
"type": "image/jpeg",
"payload": { "url": "image-url" }
}]
}
}
}Response: Detailed HTML-formatted hair analysis.
= Security
Input Validation
All inputs are validated for:
- XSS prevention
- SQL injection protection
- Content appropriateness
- Image URL safety
Rate Limiting
- 100 requests per 15 minutes per IP
- Progressive delays for high-frequency users
- Whitelist for authenticated users
Privacy Protection
- User data anonymization in logs
- Secure image URL validation
- PII detection and handling
<� Troubleshooting
Common Issues
AI Model Timeouts
Error: Request timeout after 30000msSolution: Check AI service status and increase timeout if needed.
Image Analysis Failures
Error: Could not analyze imageSolution: Validate image URL accessibility and format.
High Memory Usage
Warning: Memory usage > 80%Solution: Monitor cache size and enable garbage collection.
Debug Mode
NODE_ENV=development LOG_LEVEL=debug node src/enhancedIndex.jsMonitoring Dashboard
Access comprehensive monitoring at:
- Health:
http://localhost:3000/health - Metrics:
http://localhost:3000/metrics - Status:
http://localhost:3000/ready
=� License
Proprietary - Myavana Technology
= Related Documentation
- Core Package - Shared infrastructure
- Database Schema - Database structure
- API Reference - Complete API documentation
Version: 2.0.0
Last Updated: 2024-01-15
Maintainer: Myavana Development Team
Status: Production Ready
