Spaces:
Runtime error
Runtime error
Download apps/agents/views.py from junaidte14/django-admin-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 7.07 kB
-
https://huggingface.co/spaces/junaidte14/django-admin-dashboard/resolve/main/apps/agents/views.py
- Command line
-
hf download hf://spaces/junaidte14/django-admin-dashboard/apps/agents/views.py
-
curl -L -o views.py https://huggingface.co/spaces/junaidte14/django-admin-dashboard/resolve/main/apps/agents/views.py
7.07 kB
| """ | |
| Agent management views. | |
| """ | |
| from django.shortcuts import render, redirect, get_object_or_404 | |
| from django.contrib.auth.decorators import login_required, user_passes_test | |
| from django.contrib import messages | |
| from django.http import JsonResponse | |
| from django.views.decorators.http import require_http_methods | |
| import httpx | |
| from django.conf import settings | |
| from apps.core.models import Agent, AgentSession, User | |
| def is_staff_or_admin(user): | |
| """Check if user is staff or admin.""" | |
| return user.is_authenticated and (user.is_staff or user.role == 'admin') | |
| def agent_list_view(request): | |
| """ | |
| List all agents. | |
| """ | |
| status_filter = request.GET.get('status', 'all') | |
| agents = Agent.objects.all() | |
| if status_filter != 'all': | |
| agents = agents.filter(status=status_filter) | |
| # Add statistics | |
| for agent in agents: | |
| sessions = AgentSession.objects.filter(agent_id=agent.id) | |
| agent.total_sessions = sessions.count() | |
| agent.completed_sessions = sessions.filter(status='completed').count() | |
| agent.completion_rate = ( | |
| agent.completed_sessions / agent.total_sessions * 100 | |
| if agent.total_sessions > 0 else 0 | |
| ) | |
| # Get creator | |
| try: | |
| agent.creator = User.objects.get(id=agent.created_by_id) | |
| except User.DoesNotExist: | |
| agent.creator = None | |
| context = { | |
| 'agents': agents, | |
| 'status_filter': status_filter, | |
| } | |
| return render(request, 'agents/list.html', context) | |
| def agent_detail_view(request, agent_id): | |
| """ | |
| Agent detail view with analytics. | |
| """ | |
| agent = get_object_or_404(Agent, id=agent_id) | |
| # Get sessions | |
| sessions = AgentSession.objects.filter(agent_id=agent_id).order_by('-started_at')[:50] | |
| # Statistics | |
| all_sessions = AgentSession.objects.filter(agent_id=agent_id) | |
| total_sessions = all_sessions.count() | |
| completed_sessions = all_sessions.filter(status='completed').count() | |
| abandoned_sessions = all_sessions.filter(status='abandoned').count() | |
| # Average completion time | |
| completed = all_sessions.filter(status='completed', completed_at__isnull=False) | |
| if completed.exists(): | |
| durations = [ | |
| (s.completed_at - s.started_at).total_seconds() / 60 | |
| for s in completed | |
| ] | |
| avg_time = sum(durations) / len(durations) | |
| else: | |
| avg_time = 0 | |
| # Get creator | |
| try: | |
| agent.creator = User.objects.get(id=agent.created_by_id) | |
| except User.DoesNotExist: | |
| agent.creator = None | |
| context = { | |
| 'agent': agent, | |
| 'sessions': sessions, | |
| 'stats': { | |
| 'total_sessions': total_sessions, | |
| 'completed_sessions': completed_sessions, | |
| 'abandoned_sessions': abandoned_sessions, | |
| 'completion_rate': (completed_sessions / total_sessions * 100) if total_sessions > 0 else 0, | |
| 'avg_completion_time_minutes': avg_time, | |
| } | |
| } | |
| return render(request, 'agents/detail.html', context) | |
| def agent_create(request): | |
| """ | |
| Create new agent. | |
| """ | |
| if request.method == 'POST': | |
| # Get form data | |
| name = request.POST.get('name') | |
| agent_type = request.POST.get('agent_type') | |
| description = request.POST.get('description', '') | |
| welcome_message = request.POST.get('welcome_message') | |
| if not all([name, agent_type, welcome_message]): | |
| messages.error(request, 'Please fill in all required fields') | |
| return redirect('agents:create') | |
| try: | |
| # Call FastAPI to create agent | |
| client = httpx.Client(timeout=30.0) | |
| response = client.post( | |
| f"{settings.FASTAPI_BASE_URL}/agents", | |
| json={ | |
| 'name': name, | |
| 'agent_type': agent_type, | |
| 'description': description, | |
| 'welcome_message': welcome_message, | |
| 'completion_message': 'Thank you! Your request has been completed.', | |
| 'error_message': 'Sorry, something went wrong. Please try again.', | |
| 'max_retries': 3, | |
| 'config': {}, | |
| 'status': 'draft' | |
| }, | |
| headers={'Authorization': f'Bearer {request.user.get_token()}'} | |
| ) | |
| client.close() | |
| if response.status_code == 200: | |
| messages.success(request, f'Agent "{name}" created successfully') | |
| return redirect('dashboard:agents') | |
| else: | |
| messages.error(request, f'Failed to create agent: {response.text}') | |
| except Exception as e: | |
| messages.error(request, f'Error creating agent: {str(e)}') | |
| # Get agent type choices | |
| agent_types = [ | |
| ('order_taking', 'Order Taking'), | |
| ('appointment_booking', 'Appointment Booking'), | |
| ('support_ticket', 'Support Ticket'), | |
| ('lead_qualification', 'Lead Qualification'), | |
| ('survey', 'Survey'), | |
| ('custom', 'Custom'), | |
| ] | |
| context = { | |
| 'agent_types': agent_types, | |
| } | |
| return render(request, 'agents/create.html', context) | |
| def agent_toggle_status(request, agent_id): | |
| """ | |
| Toggle agent active/inactive status. | |
| """ | |
| agent = get_object_or_404(Agent, id=agent_id) | |
| # Toggle status | |
| if agent.status == 'active': | |
| agent.status = 'inactive' | |
| else: | |
| agent.status = 'active' | |
| agent.save() | |
| return JsonResponse({ | |
| 'success': True, | |
| 'status': agent.status, | |
| 'message': f'Agent {agent.status} successfully' | |
| }) | |
| def agent_delete(request, agent_id): | |
| """ | |
| Delete an agent. | |
| """ | |
| agent = get_object_or_404(Agent, id=agent_id) | |
| agent_name = agent.name | |
| try: | |
| # Call FastAPI to delete | |
| client = httpx.Client(timeout=30.0) | |
| response = client.delete( | |
| f"{settings.FASTAPI_BASE_URL}/agents/{agent_id}", | |
| headers={'Authorization': f'Bearer {request.user.get_token()}'} | |
| ) | |
| client.close() | |
| if response.status_code == 200: | |
| return JsonResponse({ | |
| 'success': True, | |
| 'message': f'Agent "{agent_name}" deleted successfully' | |
| }) | |
| else: | |
| return JsonResponse({ | |
| 'success': False, | |
| 'message': f'Failed to delete agent: {response.text}' | |
| }, status=400) | |
| except Exception as e: | |
| return JsonResponse({ | |
| 'success': False, | |
| 'message': f'Error deleting agent: {str(e)}' | |
| }, status=500) |