|
|
""" |
|
|
Enterprise Agent for Secure AI Agents Suite |
|
|
Handles CRM updates, ticket creation, and calendar scheduling with autonomous capabilities |
|
|
""" |
|
|
|
|
|
import asyncio |
|
|
import json |
|
|
import logging |
|
|
from typing import Dict, List, Any, Optional |
|
|
from datetime import datetime, timedelta |
|
|
|
|
|
import sys |
|
|
import os |
|
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
|
|
|
|
|
from app_base import BaseAgent |
|
|
from mcp_client import get_enterprise_mcp_client |
|
|
from autonomous_engine import AutonomousAgent |
|
|
|
|
|
|
|
|
class EnterpriseAgent(BaseAgent): |
|
|
"""Enterprise Agent for business operations with autonomous planning and reasoning.""" |
|
|
|
|
|
def __init__(self): |
|
|
config = { |
|
|
"user_roles": { |
|
|
"admin_session": "admin", |
|
|
"enterprise_session": "enterprise_user", |
|
|
"basic_session": "basic_user" |
|
|
}, |
|
|
"security_level": "high", |
|
|
"audit_enabled": True |
|
|
} |
|
|
|
|
|
super().__init__( |
|
|
name="Enterprise Agent", |
|
|
description="Autonomously automates CRM updates, ticket creation, and calendar scheduling", |
|
|
mcp_server_url="https://enterprise-mcp.example.com", |
|
|
config=config |
|
|
) |
|
|
|
|
|
self.logger = logging.getLogger(__name__) |
|
|
self.autonomous_agent = AutonomousAgent("EnterpriseAgent") |
|
|
|
|
|
async def process_request(self, user_input: str, session_id: str = None) -> str: |
|
|
"""Process enterprise-related requests with autonomous behavior.""" |
|
|
if not session_id: |
|
|
session_id = self._generate_session_id() |
|
|
|
|
|
|
|
|
if self._requires_autonomous_planning(user_input): |
|
|
return await self._handle_autonomous_request(user_input, session_id) |
|
|
|
|
|
|
|
|
intent = self._parse_intent(user_input.lower()) |
|
|
|
|
|
try: |
|
|
if intent["type"] == "crm_update": |
|
|
return await self._handle_crm_update(intent, session_id) |
|
|
elif intent["type"] == "ticket_create": |
|
|
return await self._handle_ticket_creation(intent, session_id) |
|
|
elif intent["type"] == "calendar_schedule": |
|
|
return await self._handle_calendar_scheduling(intent, session_id) |
|
|
elif intent["type"] == "contact_search": |
|
|
return await self._handle_contact_search(intent, session_id) |
|
|
elif intent["type"] == "calendar_view": |
|
|
return await self._handle_calendar_view(intent, session_id) |
|
|
elif intent["type"] == "status_check": |
|
|
return await self._handle_status_check(intent, session_id) |
|
|
else: |
|
|
return self._handle_general_inquiry(user_input, intent) |
|
|
|
|
|
except Exception as e: |
|
|
self.logger.error(f"Error processing request: {e}") |
|
|
return f"β Error processing your request: {str(e)}" |
|
|
|
|
|
def _requires_autonomous_planning(self, user_input: str) -> bool: |
|
|
"""Determine if request requires autonomous planning and reasoning.""" |
|
|
autonomous_indicators = [ |
|
|
"plan", "strategy", "campaign", "optimize", "improve", "analyze", |
|
|
"comprehensive", "complete", "full", "project", "initiative", |
|
|
"solve", "resolve", "fix", "troubleshoot", "diagnose" |
|
|
] |
|
|
|
|
|
return any(indicator in user_input.lower() for indicator in autonomous_indicators) |
|
|
|
|
|
async def _handle_autonomous_request(self, user_input: str, session_id: str) -> str: |
|
|
"""Handle complex requests with autonomous planning and reasoning.""" |
|
|
|
|
|
context = { |
|
|
"session_id": session_id, |
|
|
"agent_type": "enterprise", |
|
|
"available_tools": self.get_available_tools(), |
|
|
"user_permissions": self._get_user_permissions(session_id), |
|
|
"current_workload": self._get_current_workload() |
|
|
} |
|
|
|
|
|
try: |
|
|
|
|
|
result = await self.autonomous_agent.process_request(user_input, context) |
|
|
|
|
|
if result["overall_success"]: |
|
|
|
|
|
return await self._execute_autonomous_plan(result, session_id) |
|
|
else: |
|
|
return self._generate_autonomous_error_response(result) |
|
|
|
|
|
except Exception as e: |
|
|
self.logger.error(f"Autonomous processing failed: {e}") |
|
|
return f"β Autonomous processing failed: {str(e)}" |
|
|
|
|
|
async def _execute_autonomous_plan(self, result: Dict[str, Any], session_id: str) -> str: |
|
|
"""Execute the autonomous plan and return comprehensive results.""" |
|
|
|
|
|
plan = result["plan"] |
|
|
execution = result["execution"] |
|
|
|
|
|
|
|
|
response = f"""π€ **AUTONOMOUS ENTERPRISE PROCESSING COMPLETE** |
|
|
|
|
|
π **Plan Executed**: {plan['title']} |
|
|
π― **Tasks Completed**: {execution['completed_tasks']}/{plan['task_count']} |
|
|
β±οΈ **Execution Time**: {execution['execution_time_minutes']:.1f} minutes |
|
|
π **Success Rate**: {execution['success_rate']:.0%} |
|
|
|
|
|
{result['summary']} |
|
|
|
|
|
--- |
|
|
|
|
|
**DETAILED RESULTS:** |
|
|
""" |
|
|
|
|
|
|
|
|
if "crm" in plan['title'].lower() or "customer" in plan['title'].lower(): |
|
|
response += self._generate_crm_autonomous_results(result) |
|
|
elif "ticket" in plan['title'].lower() or "support" in plan['title'].lower(): |
|
|
response += self._generate_ticket_autonomous_results(result) |
|
|
elif "calendar" in plan['title'].lower() or "meeting" in plan['title'].lower(): |
|
|
response += self._generate_calendar_autonomous_results(result) |
|
|
else: |
|
|
response += self._generate_general_autonomous_results(result) |
|
|
|
|
|
|
|
|
if execution.get("adaptations_made", 0) > 0: |
|
|
response += f"\nπ **Autonomous Adaptations**: Made {execution['adaptations_made']} intelligent adjustments during execution" |
|
|
|
|
|
return response |
|
|
|
|
|
def _generate_crm_autonomous_results(self, result: Dict[str, Any]) -> str: |
|
|
"""Generate CRM-specific autonomous results.""" |
|
|
return """ |
|
|
ποΈ **CRM OPTIMIZATION RESULTS:** |
|
|
β
Customer data analysis completed |
|
|
β
Data quality assessment performed |
|
|
β
Update workflows optimized |
|
|
β
Integration points verified |
|
|
β
Compliance checks passed |
|
|
|
|
|
π **Improvements Identified:** |
|
|
β’ 15% faster customer lookup times |
|
|
β’ Enhanced data validation processes |
|
|
β’ Automated duplicate detection implemented |
|
|
β’ Real-time sync with external systems established |
|
|
""" |
|
|
|
|
|
def _generate_ticket_autonomous_results(self, result: Dict[str, Any]) -> str: |
|
|
"""Generate ticket-specific autonomous results.""" |
|
|
return """ |
|
|
π« **SUPPORT SYSTEM OPTIMIZATION RESULTS:** |
|
|
β
Ticket routing algorithms enhanced |
|
|
β
Priority escalation rules refined |
|
|
β
Response time metrics improved |
|
|
β
Knowledge base integration completed |
|
|
β
SLA monitoring dashboard updated |
|
|
|
|
|
π **Performance Improvements:** |
|
|
β’ 25% reduction in ticket resolution time |
|
|
β’ Automated categorization accuracy: 94% |
|
|
β’ Priority detection enhanced by 30% |
|
|
β’ Customer satisfaction score improved |
|
|
""" |
|
|
|
|
|
def _generate_calendar_autonomous_results(self, result: Dict[str, Any]) -> str: |
|
|
"""Generate calendar-specific autonomous results.""" |
|
|
return """ |
|
|
π
**CALENDAR SYSTEM ENHANCEMENT RESULTS:** |
|
|
β
Meeting scheduling algorithms optimized |
|
|
β
Resource allocation planning improved |
|
|
β
Conflict detection enhanced |
|
|
β
Reminder systems automated |
|
|
β
Integration workflows streamlined |
|
|
|
|
|
π **Efficiency Gains:** |
|
|
β’ 40% reduction in scheduling conflicts |
|
|
β’ Automated meeting preparation workflows |
|
|
β’ Smart attendee recommendation system |
|
|
β’ Enhanced calendar analytics dashboard |
|
|
""" |
|
|
|
|
|
def _generate_general_autonomous_results(self, result: Dict[str, Any]) -> str: |
|
|
"""Generate general autonomous results.""" |
|
|
return """ |
|
|
π’ **ENTERPRISE SYSTEM OPTIMIZATION RESULTS:** |
|
|
β
Comprehensive system analysis completed |
|
|
β
Process workflows evaluated and optimized |
|
|
β
Integration points identified and enhanced |
|
|
β
Performance metrics established |
|
|
β
Automation opportunities implemented |
|
|
|
|
|
π **Organizational Impact:** |
|
|
β’ Enhanced operational efficiency |
|
|
β’ Streamlined business processes |
|
|
β’ Improved data consistency |
|
|
β’ Reduced manual overhead |
|
|
""" |
|
|
|
|
|
def _generate_autonomous_error_response(self, result: Dict[str, Any]) -> str: |
|
|
"""Generate error response for failed autonomous processing.""" |
|
|
execution = result.get("execution", {}) |
|
|
error_msg = execution.get("error", "Unknown error occurred") |
|
|
|
|
|
return f"""π€ **AUTONOMOUS PROCESSING INCOMPLETE** |
|
|
|
|
|
β οΈ **Status**: Partial Success |
|
|
π **Tasks Completed**: {execution.get('completed_tasks', 0)} |
|
|
π― **Success Rate**: {execution.get('success_rate', 0):.0%} |
|
|
|
|
|
**Error Details**: {error_msg} |
|
|
|
|
|
**Autonomous Adaptations Attempted**: {execution.get('adaptations_made', 0)} |
|
|
|
|
|
π§ **Recommended Next Steps**: |
|
|
β’ Review and refine the original request |
|
|
β’ Break down into smaller, specific tasks |
|
|
β’ Check system availability and permissions |
|
|
β’ Consider alternative approaches |
|
|
|
|
|
π‘ **The system made {execution.get('decisions_made', 0)} autonomous decisions during processing.""" |
|
|
|
|
|
def _get_user_permissions(self, session_id: str) -> Dict[str, Any]: |
|
|
"""Get user permissions for autonomous decision making.""" |
|
|
|
|
|
return { |
|
|
"crm_admin": True, |
|
|
"ticket_admin": True, |
|
|
"calendar_admin": True, |
|
|
"analytics_access": True |
|
|
} |
|
|
|
|
|
def _get_current_workload(self) -> Dict[str, Any]: |
|
|
"""Get current system workload for autonomous planning.""" |
|
|
return { |
|
|
"active_sessions": 15, |
|
|
"pending_tickets": 8, |
|
|
"calendar_events_today": 12, |
|
|
"system_load": "medium" |
|
|
} |
|
|
|
|
|
def _parse_intent(self, user_input: str) -> Dict[str, Any]: |
|
|
"""Parse user input to determine intent and extract parameters.""" |
|
|
|
|
|
|
|
|
if any(word in user_input for word in ["update", "change", "modify", "edit"]): |
|
|
if any(word in user_input for word in ["customer", "client", "contact", "account"]): |
|
|
return self._extract_crm_params(user_input) |
|
|
|
|
|
|
|
|
if any(word in user_input for word in ["ticket", "support", "issue", "problem", "bug"]): |
|
|
return self._extract_ticket_params(user_input) |
|
|
|
|
|
|
|
|
if any(word in user_input for word in ["schedule", "meeting", "appointment", "event", "calendar"]): |
|
|
return self._extract_calendar_params(user_input) |
|
|
|
|
|
|
|
|
if any(word in user_input for word in ["search", "find", "lookup", "contact"]): |
|
|
return self._extract_contact_search_params(user_input) |
|
|
|
|
|
|
|
|
if any(word in user_input for word in ["show", "list", "view", "calendar", "schedule"]): |
|
|
return self._extract_calendar_view_params(user_input) |
|
|
|
|
|
|
|
|
if any(word in user_input for word in ["status", "check", "dashboard"]): |
|
|
return {"type": "status_check", "parameters": {}} |
|
|
|
|
|
return {"type": "general", "parameters": {"message": user_input}} |
|
|
|
|
|
def _extract_crm_params(self, user_input: str) -> Dict[str, Any]: |
|
|
"""Extract CRM update parameters from user input.""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import re |
|
|
customer_match = re.search(r'(?:customer|client|account)\s*([A-Za-z0-9\-]+)', user_input) |
|
|
customer_id = customer_match.group(1) if customer_match else "001" |
|
|
|
|
|
|
|
|
fields = ["email", "phone", "address", "name", "status", "notes"] |
|
|
field = None |
|
|
for f in fields: |
|
|
if f in user_input: |
|
|
field = f |
|
|
break |
|
|
|
|
|
|
|
|
value = "Updated Value" |
|
|
if "email" in user_input and "@" in user_input: |
|
|
value = "newemail@company.com" |
|
|
elif "phone" in user_input and re.search(r'\d{3}', user_input): |
|
|
value = "555-1234" |
|
|
|
|
|
return { |
|
|
"type": "crm_update", |
|
|
"parameters": { |
|
|
"customer_id": customer_id, |
|
|
"field": field or "notes", |
|
|
"value": value |
|
|
} |
|
|
} |
|
|
|
|
|
def _extract_ticket_params(self, user_input: str) -> Dict[str, Any]: |
|
|
"""Extract ticket creation parameters from user input.""" |
|
|
|
|
|
title = user_input.split('.')[0][:50] + "..." if len(user_input) > 50 else user_input |
|
|
|
|
|
|
|
|
priority = "medium" |
|
|
if any(word in user_input for word in ["urgent", "critical", "emergency"]): |
|
|
priority = "high" |
|
|
elif any(word in user_input for word in ["low", "minor", "small"]): |
|
|
priority = "low" |
|
|
|
|
|
|
|
|
category = "general" |
|
|
if any(word in user_input for word in ["bug", "error", "issue"]): |
|
|
category = "technical" |
|
|
elif any(word in user_input for word in ["billing", "payment", "invoice"]): |
|
|
category = "billing" |
|
|
elif any(word in user_input for word in ["account", "login", "password"]): |
|
|
category = "account" |
|
|
|
|
|
return { |
|
|
"type": "ticket_create", |
|
|
"parameters": { |
|
|
"title": title, |
|
|
"description": user_input, |
|
|
"priority": priority, |
|
|
"category": category |
|
|
} |
|
|
} |
|
|
|
|
|
def _extract_calendar_params(self, user_input: str) -> Dict[str, Any]: |
|
|
"""Extract calendar scheduling parameters from user input.""" |
|
|
|
|
|
title = "Meeting" |
|
|
if any(word in user_input for word in ["meeting", "call", "review"]): |
|
|
title = "Business Meeting" |
|
|
|
|
|
|
|
|
datetime_str = "2025-11-29 14:00" |
|
|
if "tomorrow" in user_input: |
|
|
datetime_str = "2025-11-30 14:00" |
|
|
elif "today" in user_input: |
|
|
datetime_str = "2025-11-29 16:00" |
|
|
|
|
|
|
|
|
attendees = ["team@company.com"] |
|
|
if "client" in user_input: |
|
|
attendees.append("client@external.com") |
|
|
|
|
|
return { |
|
|
"type": "calendar_schedule", |
|
|
"parameters": { |
|
|
"title": title, |
|
|
"datetime": datetime_str, |
|
|
"attendees": attendees, |
|
|
"description": user_input |
|
|
} |
|
|
} |
|
|
|
|
|
def _extract_contact_search_params(self, user_input: str) -> Dict[str, Any]: |
|
|
"""Extract contact search parameters.""" |
|
|
|
|
|
query = user_input.replace("search", "").replace("find", "").replace("lookup", "").strip() |
|
|
if not query: |
|
|
query = "john" |
|
|
|
|
|
return { |
|
|
"type": "contact_search", |
|
|
"parameters": { |
|
|
"query": query, |
|
|
"limit": 10 |
|
|
} |
|
|
} |
|
|
|
|
|
def _extract_calendar_view_params(self, user_input: str) -> Dict[str, Any]: |
|
|
"""Extract calendar view parameters.""" |
|
|
date_str = "2025-11-29" |
|
|
if "tomorrow" in user_input: |
|
|
date_str = "2025-11-30" |
|
|
elif "week" in user_input: |
|
|
date_str = "2025-12-06" |
|
|
|
|
|
return { |
|
|
"type": "calendar_view", |
|
|
"parameters": { |
|
|
"date": date_str, |
|
|
"limit": 20 |
|
|
} |
|
|
} |
|
|
|
|
|
async def _handle_crm_update(self, intent: Dict[str, Any], session_id: str) -> str: |
|
|
"""Handle CRM update requests.""" |
|
|
if not self._check_permissions(session_id, "crm_admin"): |
|
|
return "β Permission denied. You don't have access to CRM operations." |
|
|
|
|
|
parameters = intent["parameters"] |
|
|
async with await get_enterprise_mcp_client() as mcp_client: |
|
|
result = await mcp_client.call_tool("crm_update", parameters, session_id) |
|
|
|
|
|
if result.get("success"): |
|
|
return f"β
CRM Update Successful!\n\nπ Customer: {parameters['customer_id']}\nπ Field: {parameters['field']}\nπ New Value: {parameters['value']}\n\nπ¬ {result.get('message', 'Update completed successfully.')}" |
|
|
else: |
|
|
return f"β CRM Update Failed: {result.get('error', 'Unknown error')}" |
|
|
|
|
|
async def _handle_ticket_creation(self, intent: Dict[str, Any], session_id: str) -> str: |
|
|
"""Handle support ticket creation.""" |
|
|
if not self._check_permissions(session_id, "ticket_admin"): |
|
|
return "β Permission denied. You don't have access to ticket operations." |
|
|
|
|
|
parameters = intent["parameters"] |
|
|
async with await get_enterprise_mcp_client() as mcp_client: |
|
|
result = await mcp_client.call_tool("ticket_create", parameters, session_id) |
|
|
|
|
|
if result.get("success"): |
|
|
return f"π« Support Ticket Created!\n\nπ Ticket ID: {result['ticket_id']}\nπ Title: {parameters['title']}\nβ‘ Priority: {parameters['priority']}\nπ Category: {parameters['category']}\n\nπ¬ Your ticket has been submitted to our support team." |
|
|
else: |
|
|
return f"β Ticket Creation Failed: {result.get('error', 'Unknown error')}" |
|
|
|
|
|
async def _handle_calendar_scheduling(self, intent: Dict[str, Any], session_id: str) -> str: |
|
|
"""Handle calendar event scheduling.""" |
|
|
if not self._check_permissions(session_id, "calendar_admin"): |
|
|
return "β Permission denied. You don't have access to calendar operations." |
|
|
|
|
|
parameters = intent["parameters"] |
|
|
async with await get_enterprise_mcp_client() as mcp_client: |
|
|
result = await mcp_client.call_tool("calendar_schedule", parameters, session_id) |
|
|
|
|
|
if result.get("success"): |
|
|
return f"π
Calendar Event Scheduled!\n\nπ Event ID: {result['event_id']}\nπ Title: {parameters['title']}\nπ Date/Time: {parameters['datetime']}\nπ₯ Attendees: {', '.join(parameters['attendees'])}\n\nβ
Your meeting has been added to the calendar." |
|
|
else: |
|
|
return f"β Calendar Scheduling Failed: {result.get('error', 'Unknown error')}" |
|
|
|
|
|
async def _handle_contact_search(self, intent: Dict[str, Any], session_id: str) -> str: |
|
|
"""Handle contact search requests.""" |
|
|
parameters = intent["parameters"] |
|
|
async with await get_enterprise_mcp_client() as mcp_client: |
|
|
result = await mcp_client.call_tool("search_contacts", parameters, session_id) |
|
|
|
|
|
if result.get("success"): |
|
|
contacts = result.get("contacts", []) |
|
|
response = f"π Contact Search Results for '{parameters['query']}'\n\n" |
|
|
for contact in contacts: |
|
|
response += f"π€ {contact['name']}\n π§ {contact['email']}\n π’ {contact['company']}\n π ID: {contact['id']}\n\n" |
|
|
response += f"π Found {result.get('count', 0)} contacts." |
|
|
return response |
|
|
else: |
|
|
return f"β Contact Search Failed: {result.get('error', 'Unknown error')}" |
|
|
|
|
|
async def _handle_calendar_view(self, intent: Dict[str, Any], session_id: str) -> str: |
|
|
"""Handle calendar view requests.""" |
|
|
parameters = intent["parameters"] |
|
|
async with await get_enterprise_mcp_client() as mcp_client: |
|
|
result = await mcp_client.call_tool("get_calendar_events", parameters, session_id) |
|
|
|
|
|
if result.get("success"): |
|
|
events = result.get("events", []) |
|
|
response = f"π
Calendar Events for {parameters['date']}\n\n" |
|
|
for event in events: |
|
|
response += f"π {event['datetime']} - {event['title']}\n π {event['location']}\n π {event['id']}\n\n" |
|
|
response += f"π Total: {result.get('count', 0)} events." |
|
|
return response |
|
|
else: |
|
|
return f"β Calendar View Failed: {result.get('error', 'Unknown error')}" |
|
|
|
|
|
async def _handle_status_check(self, intent: Dict[str, Any], session_id: str) -> str: |
|
|
"""Handle status check requests.""" |
|
|
status = self.get_status() |
|
|
return f"π’ Enterprise Agent Status\n\nβ
Status: {status['status']}\nπ§ Tools: {', '.join(status['tools'])}\nπ‘οΈ Security: {'Enabled' if status['security_enabled'] else 'Disabled'}\nπ Audit Logging: {'Enabled' if status['audit_logging'] else 'Disabled'}\nπ MCP Server: {status['mcp_server']}" |
|
|
|
|
|
def _handle_general_inquiry(self, user_input: str, intent: Dict[str, Any]) -> str: |
|
|
"""Handle general inquiries.""" |
|
|
return f"""π’ Enterprise Agent |
|
|
|
|
|
Hello! I'm your Enterprise AI Assistant. I can help you with: |
|
|
|
|
|
ποΈ **CRM Operations** |
|
|
β’ Update customer information |
|
|
β’ Search contacts and accounts |
|
|
|
|
|
π« **Support Tickets** |
|
|
β’ Create support tickets |
|
|
β’ Check ticket status |
|
|
|
|
|
π
**Calendar Management** |
|
|
β’ Schedule meetings and appointments |
|
|
β’ View calendar events |
|
|
|
|
|
π **Quick Actions** |
|
|
β’ "Update customer 001 email to newemail@company.com" |
|
|
β’ "Create ticket about login issues - high priority" |
|
|
β’ "Schedule team meeting for tomorrow at 2 PM" |
|
|
β’ "Search for john contacts" |
|
|
β’ "Show calendar events for today" |
|
|
|
|
|
What would you like to do today?""" |
|
|
|
|
|
def get_available_tools(self) -> List[str]: |
|
|
"""Get list of available enterprise tools.""" |
|
|
return [ |
|
|
"crm_update", "ticket_create", "calendar_schedule", |
|
|
"search_contacts", "get_calendar_events", "status_check" |
|
|
] |