quantum-ai-v2/agents/models.py
Claude ab2360a91d 💬 Implement complete chat-based agent system with 5 Whys Analysis
🏗️ **Database Extensions:**
- Add agent_type field to Agent model (form/chat distinction)
- Create ChatSession model for conversation management
- Create ChatMessage model for message storage with metadata
- Add database indexes for performance optimization

🎨 **Frontend Implementation:**
- Create agent_chat.html template with modern chat interface
- Implement real-time messaging UI with message bubbles
- Add typing indicators and loading states
- Responsive design for mobile and desktop
- Empty states and error handling

🔧 **Backend Logic:**
- Extend agent_detail_view to route chat vs form agents
- Implement chat_agent_view for chat interface rendering
- Add start_chat_session API endpoint with session management
- Add send_chat_message API endpoint with webhook integration
- Add get_chat_history and end_chat_session endpoints
- Session-based fee charging system

🤖 **5 Whys Agent:**
- Create "Analysis & Problem Solving" category
- Implement 5 Whys Analysis chat-based agent (15 AED)
- Interactive problem-solving methodology guidance
- N8N webhook integration for AI responses

 **Interactive Features:**
- JavaScript ChatInterface class for real-time communication
- Auto-session creation and management
- Message validation and error handling
- Automatic scrolling and UI state management
- CSRF protection and security measures

🔗 **API Integration:**
- Chat-specific API endpoints with RESTful design
- Webhook payload formatting for N8N integration
- Session ID tracking and conversation continuity
- Metadata storage for webhook responses

🛡️ **Security & UX:**
- Login required for chat agents
- Wallet balance validation before session creation
- Session isolation per user and agent
- Comprehensive error handling and user feedback

**New URLs:**
- /agents/api/chat/start/ - Start new chat session
- /agents/api/chat/send/ - Send chat message
- /agents/api/chat/history/<session_id>/ - Get chat history
- /agents/api/chat/end/ - End chat session
- /agents/five-whys-analysis/ - 5 Whys chat interface

**Backward Compatibility:**
- Existing form-based agents (Social Ads, Job Posting, PDF) unchanged
- Admin interface updated to show agent types
- Marketplace displays both agent types seamlessly

🚀 Ready for interactive 5 Whys problem-solving conversations\!

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-01 09:39:43 +05:30

123 lines
4.9 KiB
Python

from django.db import models
import uuid
class AgentCategory(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True)
icon = models.CharField(max_length=50, blank=True, help_text="Icon class or emoji")
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Agent(models.Model):
AGENT_TYPE_CHOICES = [
('form', 'Form-based'),
('chat', 'Chat-based'),
]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
short_description = models.CharField(max_length=300)
description = models.TextField()
category = models.ForeignKey(AgentCategory, on_delete=models.CASCADE, related_name='agents')
price = models.DecimalField(max_digits=10, decimal_places=2)
agent_type = models.CharField(max_length=10, choices=AGENT_TYPE_CHOICES, default='form', help_text="Agent interaction type")
form_schema = models.JSONField(help_text="JSON schema for agent input form", null=True, blank=True)
webhook_url = models.URLField(help_text="n8n webhook URL for execution")
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class AgentExecution(models.Model):
STATUS_CHOICES = [
('pending', 'Pending'),
('running', 'Running'),
('completed', 'Completed'),
('failed', 'Failed'),
]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
agent = models.ForeignKey(Agent, on_delete=models.CASCADE, related_name='executions')
user = models.ForeignKey('authentication.User', on_delete=models.CASCADE)
input_data = models.JSONField()
output_data = models.JSONField(null=True, blank=True)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
fee_charged = models.DecimalField(max_digits=10, decimal_places=2)
webhook_response = models.JSONField(null=True, blank=True)
error_message = models.TextField(blank=True)
execution_time = models.DurationField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
completed_at = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"{self.agent.name} - {self.user.email} - {self.status}"
class ChatSession(models.Model):
STATUS_CHOICES = [
('active', 'Active'),
('completed', 'Completed'),
('abandoned', 'Abandoned'),
('failed', 'Failed'),
]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
session_id = models.CharField(max_length=100, unique=True, help_text="Unique session identifier")
agent = models.ForeignKey(Agent, on_delete=models.CASCADE, related_name='chat_sessions')
user = models.ForeignKey('authentication.User', on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active')
context_data = models.JSONField(default=dict, help_text="Session context and progress tracking")
fee_charged = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
completed_at = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ['-created_at']
indexes = [
models.Index(fields=['session_id']),
models.Index(fields=['user', '-created_at']),
]
def __str__(self):
return f"{self.agent.name} - {self.user.email} - {self.session_id}"
class ChatMessage(models.Model):
MESSAGE_TYPE_CHOICES = [
('user', 'User Message'),
('agent', 'Agent Response'),
('system', 'System Message'),
]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
session = models.ForeignKey(ChatSession, on_delete=models.CASCADE, related_name='messages')
message_type = models.CharField(max_length=10, choices=MESSAGE_TYPE_CHOICES)
content = models.TextField()
metadata = models.JSONField(default=dict, help_text="Additional message data like webhook responses")
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['timestamp']
indexes = [
models.Index(fields=['session', 'timestamp']),
]
def __str__(self):
return f"{self.session.session_id} - {self.message_type} - {self.timestamp}"