quantum-ai-v2/agents/management/commands/create_five_whys_agent.py
Claude 641d676f2f 🎉 Complete 5 Whys agent enhancements with session management and UI improvements
## Major Features Added:

### 🕒 Session Time Limits (2hr → 30min)
- Updated ChatSession model: expires_at, extend_session methods
- Changed session creation and extension logic
- Updated JavaScript timing calculations
- Fixed timing indicator functionality with real-time server data

### 💬 Message Limits (50 → 20)
- Added message_limit field to Agent model with migration
- Implemented auto-completion when message limit reached
- Only count user messages (not agent responses) toward limit
- Enhanced error messaging for limit exceeded

### 📥 Chat Download System
- Added PDF and TXT export functionality using ReportLab
- Download buttons in chat header for active sessions
- Comprehensive export with session metadata and formatting
- New API endpoints: /agents/api/chat/export/{session_id}/

### 📋 Previous Sessions Management
- Created Previous Sessions widget showing last 5 non-active sessions
- Download access for all completed sessions with messages
- Session status indicators ( Completed,  Expired,  Abandoned)
- Clean sidebar organization with session history

### 🎨 UI/UX Improvements
- Moved session info from main chat to sidebar for cleaner interface
- Increased chat height: 600px → 800px (mobile: 500px → 650px)
- Added Current Session widget with status, ID, and start time
- Enhanced sidebar layout with proper component stacking
- Responsive design with mobile optimizations

### 🔧 Session Indicators System
- Real-time session status API with server-side data
- Progress bars for time remaining and message usage
- Warning notifications for approaching limits
- Automatic updates every 30 seconds

### 💰 Payment Flow Fixes
- Fixed charging system to actually deduct wallet balance
- Each new session charges 15 AED for 20 messages + 30 minutes
- Proper error handling for insufficient balance
- Session cleanup on payment failures

## Technical Implementation:

**Backend Changes:**
- Enhanced ChatSession model with 30-minute duration
- Message counting logic (user messages only)
- Auto-completion on limit reached
- Session status API endpoint
- PDF/TXT export with ReportLab

**Frontend Changes:**
- Comprehensive sidebar widget system
- Real-time indicator updates with server sync
- Download functionality with loading states
- Session history display with status icons
- Responsive layout improvements

**Database:**
- Added message_limit field to Agent model
- Updated ChatSession expiration logic
- Efficient queries for session history

## User Experience:
 Clear session limits (20 messages, 30 minutes)
 Automatic session completion with preserved history
 Easy download access for all previous sessions
 Transparent pricing (15 AED per session)
 Clean, organized interface with more chat space
 Real-time feedback on session progress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-03 13:28:39 +05:30

69 lines
3.1 KiB
Python

from django.core.management.base import BaseCommand
from agents.models import AgentCategory, Agent
class Command(BaseCommand):
help = 'Create the 5 Whys chat-based analysis agent'
def handle(self, *args, **options):
# Create or get the Analysis category
category, created = AgentCategory.objects.get_or_create(
slug='analysis',
defaults={
'name': 'Analysis & Problem Solving',
'description': 'Advanced analytical tools for problem-solving and decision making',
'icon': '🧠',
'is_active': True
}
)
if created:
self.stdout.write(f'✅ Created category: {category.name}')
else:
self.stdout.write(f'📂 Using existing category: {category.name}')
# Create the 5 Whys agent
agent, created = Agent.objects.get_or_create(
slug='five-whys-analysis',
defaults={
'name': '5 Whys Analysis',
'short_description': 'Interactive problem-solving using the proven 5 Whys methodology',
'description': '''Systematically find root causes through guided 5 Whys methodology. Perfect for troubleshooting operational problems, understanding failures, and identifying systemic issues.''',
'category': category,
'price': 15.00,
'agent_type': 'chat', # This is a chat-based agent
'message_limit': 20, # Limit messages per session
'form_schema': None, # Chat agents don't use form schemas
'webhook_url': 'http://localhost:5678/webhook/5-whys-web', # N8N webhook URL
'is_active': True
}
)
if created:
self.stdout.write(
self.style.SUCCESS(f'🎉 Successfully created 5 Whys Analysis agent!')
)
self.stdout.write(f' 💬 Agent Type: {agent.agent_type}')
self.stdout.write(f' 💰 Price: {agent.price} AED')
self.stdout.write(f' 🔗 Webhook: {agent.webhook_url}')
self.stdout.write(f' 📂 Category: {agent.category.name}')
else:
self.stdout.write(
self.style.WARNING(f'⚠️ 5 Whys Analysis agent already exists')
)
# Update existing agent to ensure it's chat-based
if agent.agent_type != 'chat':
agent.agent_type = 'chat'
agent.form_schema = None
agent.save()
self.stdout.write(
self.style.SUCCESS(f'✅ Updated existing agent to chat-based')
)
self.stdout.write('')
self.stdout.write('🚀 Next steps:')
self.stdout.write(' 1. Ensure N8N webhook is running on localhost:5678')
self.stdout.write(' 2. Visit /agents/five-whys-analysis/ to test the chat interface')
self.stdout.write(' 3. Start a conversation to test the 5 Whys methodology')
self.stdout.write('')
self.stdout.write('💡 The agent is now ready for interactive problem-solving!')