IT Support Agent
This example demonstrates how to build an intelligent IT support agent that can help users with common technical issues, password resets, software installations, and troubleshooting.
Overviewā
This example shows:
- Domain-specific knowledge base for IT support
- Multi-step troubleshooting workflows
- Escalation policies for complex issues
- Integration with ticketing systems
- Performance monitoring and analytics
Use Caseā
Perfect for:
- Internal IT Helpdesk - Employee support automation
- Customer Technical Support - Product troubleshooting
- DevOps Support - Infrastructure issue resolution
- Software Support - Application-specific help
Code Implementationā
import os
import json
from datetime import datetime
from typing import Dict, List, Optional
from dotenv import load_dotenv
from recoagent import RecoAgent
from recoagent.tools import Tool
from recoagent.agents import RAGAgentGraph
from recoagent.policies import SafetyPolicy
# Load environment variables
load_dotenv()
class ITSupportAgent:
def __init__(self):
"""Initialize the IT Support Agent."""
self.agent = RAGAgentGraph(
llm_provider="openai",
llm_model="gpt-4",
embedding_model="text-embedding-ada-002",
chunk_size=400,
chunk_overlap=50
)
# Add domain-specific tools
self._setup_tools()
# Set up safety policies for IT support
self._setup_policies()
# Load IT support knowledge base
self._load_knowledge_base()
# Initialize ticket tracking
self.tickets = {}
self.ticket_counter = 1000
def _setup_tools(self):
"""Add IT-specific tools to the agent."""
def create_ticket(issue_description: str, priority: str = "medium") -> str:
"""Create a support ticket for tracking issues."""
ticket_id = f"TICKET-{self.ticket_counter}"
self.ticket_counter += 1
ticket = {
"id": ticket_id,
"description": issue_description,
"priority": priority,
"status": "open",
"created_at": datetime.now().isoformat(),
"assignee": None
}
self.tickets[ticket_id] = ticket
return f"Created ticket {ticket_id} for: {issue_description}. Priority: {priority}"
def check_system_status(system: str) -> str:
"""Check the status of various systems."""
# Simulate system status checks
status_map = {
"email": "Operational",
"vpn": "Operational",
"network": "Operational",
"servers": "Minor issues - monitoring",
"database": "Operational"
}
status = status_map.get(system.lower(), "Status unknown")
return f"{system.title()} status: {status}"
def reset_password(user_id: str, method: str = "self-service") -> str:
"""Reset user password using specified method."""
if method == "self-service":
return f"Password reset link sent to user {user_id}. Please check email and follow instructions."
elif method == "admin":
return f"Admin password reset initiated for user {user_id}. New temporary password sent."
else:
return f"Password reset method '{method}' not recognized. Use 'self-service' or 'admin'."
def install_software(software_name: str, user_id: str) -> str:
"""Request software installation for a user."""
return f"Software installation request for '{software_name}' submitted for user {user_id}. IT team will process within 24 hours."
def escalate_issue(issue: str, reason: str) -> str:
"""Escalate complex issues to senior support."""
return f"Issue escalated to senior support: {issue}. Reason: {reason}"
# Add tools to agent
self.agent.add_tool(Tool(name="create_ticket", function=create_ticket))
self.agent.add_tool(Tool(name="check_system_status", function=check_system_status))
self.agent.add_tool(Tool(name="reset_password", function=reset_password))
self.agent.add_tool(Tool(name="install_software", function=install_software))
self.agent.add_tool(Tool(name="escalate_issue", function=escalate_issue))
print("ā
IT Support tools loaded")
def _setup_policies(self):
"""Set up safety policies for IT support."""
policies = SafetyPolicy(
max_cost_per_query=0.20, # Higher limit for support scenarios
max_latency_ms=10000, # Allow more time for complex issues
allowed_topics=[
"password reset", "software installation", "email issues",
"vpn problems", "network connectivity", "system status",
"troubleshooting", "technical support", "helpdesk"
],
escalation_triggers=[
"security breach", "data loss", "system down", "urgent"
]
)
self.agent.set_safety_policy(policies)
print("ā
Safety policies configured")
def _load_knowledge_base(self):
"""Load IT support knowledge base."""
knowledge_base = [
# Password and Authentication
"To reset your password, go to the login page and click 'Forgot Password'. You will receive an email with reset instructions.",
"If you can't access your email, contact IT support for admin password reset.",
"Password requirements: minimum 12 characters, include uppercase, lowercase, numbers, and special characters.",
"Two-factor authentication is required for all corporate accounts. Use the authenticator app or SMS.",
# Email Issues
"If email is not working, check your internet connection and try refreshing the page.",
"Email attachments larger than 25MB should be sent through secure file sharing.",
"To access email from mobile devices, use the Outlook app or configure IMAP settings.",
"If emails are going to spam, check your spam folder and mark legitimate emails as not spam.",
# VPN and Remote Access
"VPN connection issues can usually be resolved by restarting the VPN client and rebooting your computer.",
"If VPN keeps disconnecting, check your internet connection stability and contact IT if the issue persists.",
"To access shared drives remotely, connect to VPN first, then map network drives.",
"VPN login credentials are the same as your corporate email credentials.",
# Software and Applications
"To install software, submit a request through the IT portal. Most requests are processed within 24 hours.",
"For urgent software installations, contact IT support directly with business justification.",
"Company-approved software list is available in the IT portal under 'Software Catalog'.",
"If an application crashes frequently, try restarting it and clearing temporary files.",
# Network and Connectivity
"If you can't access the internet, check your network cable and restart your network adapter.",
"For Wi-Fi issues, forget and reconnect to the network, or try connecting to a different network.",
"Corporate network requires VPN connection for accessing internal resources from external networks.",
"If network is slow, check if other users are experiencing the same issue and report to IT.",
# System Issues
"For slow computer performance, restart your computer and close unnecessary applications.",
"If your computer won't start, try safe mode or contact IT for hardware diagnostics.",
"Regular system updates are required. Check for updates weekly and install them promptly.",
"Backup your important files regularly to OneDrive or network drives.",
# Security
"Never share your login credentials with anyone. IT will never ask for your password.",
"If you receive suspicious emails, do not click links or download attachments. Forward to IT security.",
"Report any security incidents immediately to IT security team.",
"Lock your computer when leaving your desk to prevent unauthorized access.",
# General Troubleshooting
"For most technical issues, try the following steps: 1) Restart the application, 2) Restart your computer, 3) Check network connection, 4) Contact IT support.",
"When contacting IT support, provide detailed information about the issue, error messages, and steps you've already tried.",
"IT support hours: Monday-Friday 8 AM - 6 PM. Emergency support available 24/7 for critical issues.",
"Use the IT portal for non-urgent requests and to track ticket status."
]
self.agent.add_documents(knowledge_base)
print(f"ā
Loaded {len(knowledge_base)} IT support documents")
def handle_support_request(self, user_query: str, user_id: str = "user123") -> Dict:
"""Handle a support request from a user."""
print(f"\nš§ IT Support Request from {user_id}")
print(f"š Query: {user_query}")
print("-" * 50)
# Process the request through the agent
response = self.agent.run(user_query)
# Analyze the response for escalation needs
escalation_needed = self._check_escalation_triggers(user_query, response)
if escalation_needed:
escalation_result = self.agent.run_tool("escalate_issue", {
"issue": user_query,
"reason": "Complex issue requiring senior support"
})
response.tools_used.append(escalation_result)
# Create ticket if needed
if self._should_create_ticket(user_query, response):
ticket_result = self.agent.run_tool("create_ticket", {
"issue_description": user_query,
"priority": self._determine_priority(user_query)
})
response.tools_used.append(ticket_result)
# Format response
result = {
"user_id": user_id,
"query": user_query,
"answer": response.answer,
"confidence": response.confidence,
"tools_used": [tool.name for tool in response.tools_used],
"sources": len(response.sources),
"escalated": escalation_needed,
"ticket_created": any("create_ticket" in str(tool) for tool in response.tools_used),
"timestamp": datetime.now().isoformat()
}
return result
def _check_escalation_triggers(self, query: str, response) -> bool:
"""Check if the issue needs escalation."""
escalation_keywords = [
"security breach", "data loss", "system down", "urgent",
"critical", "emergency", "hacked", "compromised"
]
query_lower = query.lower()
return any(keyword in query_lower for keyword in escalation_keywords)
def _should_create_ticket(self, query: str, response) -> bool:
"""Determine if a ticket should be created."""
ticket_keywords = [
"request", "need help", "issue", "problem", "not working",
"install", "access", "permission", "account"
]
query_lower = query.lower()
return any(keyword in query_lower for keyword in ticket_keywords)
def _determine_priority(self, query: str) -> str:
"""Determine ticket priority based on query content."""
high_priority_keywords = ["urgent", "critical", "emergency", "down", "broken"]
low_priority_keywords = ["question", "information", "how to", "documentation"]
query_lower = query.lower()
if any(keyword in query_lower for keyword in high_priority_keywords):
return "high"
elif any(keyword in query_lower for keyword in low_priority_keywords):
return "low"
else:
return "medium"
def get_ticket_status(self, ticket_id: str) -> Optional[Dict]:
"""Get the status of a support ticket."""
return self.tickets.get(ticket_id)
def list_open_tickets(self) -> List[Dict]:
"""List all open support tickets."""
return [ticket for ticket in self.tickets.values() if ticket["status"] == "open"]
def generate_support_report(self) -> Dict:
"""Generate a summary report of support activities."""
total_tickets = len(self.tickets)
open_tickets = len([t for t in self.tickets.values() if t["status"] == "open"])
priority_breakdown = {}
for ticket in self.tickets.values():
priority = ticket["priority"]
priority_breakdown[priority] = priority_breakdown.get(priority, 0) + 1
return {
"total_tickets": total_tickets,
"open_tickets": open_tickets,
"priority_breakdown": priority_breakdown,
"resolution_rate": (total_tickets - open_tickets) / total_tickets if total_tickets > 0 else 0
}
def main():
"""Main function to run the IT Support Agent demo."""
print("š„ļø IT Support Agent Demo")
print("=" * 50)
# Initialize agent
agent = ITSupportAgent()
# Sample support requests
sample_requests = [
("I can't log into my email account. It says my password is wrong.", "user001"),
("My VPN keeps disconnecting every few minutes. Can you help?", "user002"),
("I need Microsoft Office installed on my computer. How do I request this?", "user003"),
("My computer is running very slowly. What should I do?", "user004"),
("I received a suspicious email asking for my password. Is this legitimate?", "user005"),
("I can't access the shared drive. It says access denied.", "user006"),
("URGENT: The server is down and no one can access their files!", "user007"),
("How do I reset my password if I forgot it?", "user008")
]
print("\nšÆ Processing Sample Support Requests")
print("=" * 50)
for query, user_id in sample_requests:
result = agent.handle_support_request(query, user_id)
print(f"\nš¤ User: {result['user_id']}")
print(f"š¬ Answer: {result['answer']}")
print(f"šÆ Confidence: {result['confidence']:.2f}")
print(f"š§ Tools Used: {', '.join(result['tools_used'])}")
print(f"š Ticket Created: {result['ticket_created']}")
print(f"šØ Escalated: {result['escalated']}")
print("-" * 50)
# Show ticket summary
print("\nš Support Report")
print("=" * 30)
report = agent.generate_support_report()
print(f"Total Tickets: {report['total_tickets']}")
print(f"Open Tickets: {report['open_tickets']}")
print(f"Resolution Rate: {report['resolution_rate']:.1%}")
print(f"Priority Breakdown: {report['priority_breakdown']}")
# Interactive mode
print("\nš¬ Interactive Support Mode")
print("=" * 40)
print("Type 'quit' to exit, 'tickets' to see open tickets")
while True:
user_input = input("\nš§ Enter support request: ").strip()
if user_input.lower() == 'quit':
break
elif user_input.lower() == 'tickets':
open_tickets = agent.list_open_tickets()
print(f"\nš Open Tickets ({len(open_tickets)}):")
for ticket in open_tickets:
print(f" {ticket['id']}: {ticket['description'][:50]}... (Priority: {ticket['priority']})")
elif user_input:
result = agent.handle_support_request(user_input, "interactive_user")
print(f"\nš” {result['answer']}")
if result['ticket_created']:
print("š A support ticket has been created for your request.")
print("\nš IT Support Agent demo completed!")
if __name__ == "__main__":
main()
Running the Exampleā
1. Setupā
# Create project directory
mkdir it-support-agent
cd it-support-agent
# Install dependencies
pip install recoagent python-dotenv
# Create .env file
echo "OPENAI_API_KEY=your_api_key_here" > .env
2. Run the Exampleā
python it_support_agent.py
3. Expected Outputā
š„ļø IT Support Agent Demo
==================================================
ā
IT Support tools loaded
ā
Safety policies configured
ā
Loaded 32 IT support documents
šÆ Processing Sample Support Requests
==================================================
š§ IT Support Request from user001
š Query: I can't log into my email account. It says my password is wrong.
--------------------------------------------------
š¤ User: user001
š¬ Answer: To reset your password, go to the login page and click 'Forgot Password'. You will receive an email with reset instructions. If you can't access your email, contact IT support for admin password reset.
šÆ Confidence: 0.94
š§ Tools Used: reset_password, create_ticket
š Ticket Created: True
šØ Escalated: False
--------------------------------------------------
š§ IT Support Request from user007
š Query: URGENT: The server is down and no one can access their files!
--------------------------------------------------
š¤ User: user007
š¬ Answer: This is a critical issue that requires immediate attention. I'm escalating this to senior support and creating a high-priority ticket. The senior support team will investigate the server outage immediately.
šÆ Confidence: 0.89
š§ Tools Used: escalate_issue, create_ticket
š Ticket Created: True
šØ Escalated: True
--------------------------------------------------
š Support Report
==============================
Total Tickets: 8
Open Tickets: 8
Resolution Rate: 0.0%
Priority Breakdown: {'high': 1, 'medium': 6, 'low': 1}
š¬ Interactive Support Mode
========================================
Type 'quit' to exit, 'tickets' to see open tickets
š§ Enter support request: I need help with my VPN
Key Featuresā
1. Domain-Specific Knowledgeā
- Comprehensive IT support knowledge base
- Covers common issues like passwords, VPN, email, software
- Includes troubleshooting procedures and escalation paths
2. Intelligent Toolsā
- Ticket Creation: Automatically creates support tickets
- System Status: Checks status of various systems
- Password Reset: Handles password reset workflows
- Software Installation: Processes software requests
- Escalation: Escalates complex issues to senior support
3. Safety and Policiesā
- Topic restrictions for IT support context
- Escalation triggers for critical issues
- Cost and latency controls
- Security-focused policies
4. Analytics and Reportingā
- Ticket tracking and status monitoring
- Priority classification
- Resolution rate tracking
- Support activity reports
Customization Optionsā
Add More Toolsā
def check_user_permissions(user_id: str, resource: str) -> str:
"""Check user permissions for a specific resource."""
# Your permission checking logic
return f"User {user_id} has {'access' if has_access else 'no access'} to {resource}"
agent.add_tool(Tool(name="check_permissions", function=check_user_permissions))
Custom Knowledge Baseā
# Load from external sources
def load_knowledge_from_database():
"""Load IT knowledge from database."""
# Connect to your IT knowledge base
knowledge = get_it_knowledge_from_db()
agent.add_documents(knowledge)
def load_knowledge_from_files(directory: str):
"""Load knowledge from documentation files."""
for file in glob.glob(f"{directory}/*.md"):
with open(file, 'r') as f:
content = f.read()
agent.add_documents([content])
Integration with Ticketing Systemsā
def create_service_now_ticket(issue: str, priority: str) -> str:
"""Create ticket in ServiceNow."""
# ServiceNow API integration
ticket_data = {
"description": issue,
"priority": priority,
"category": "IT Support"
}
response = requests.post(
"https://your-instance.service-now.com/api/now/table/incident",
headers={"Authorization": f"Bearer {token}"},
json=ticket_data
)
return f"ServiceNow ticket created: {response.json()['result']['number']}"
Deployment Considerationsā
Production Setupā
# Production configuration
agent = ITSupportAgent()
agent.agent.configure(
llm_model="gpt-4", # Use GPT-4 for better performance
max_tokens=1000, # Limit response length
temperature=0.1 # Low temperature for consistency
)
Monitoring and Analyticsā
# Add monitoring
import logging
from recoagent.observability import LangSmithClient
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Add LangSmith tracing
langsmith = LangSmithClient()
agent.agent.add_callback_handler(langsmith)
Security Considerationsā
# Implement security measures
def sanitize_user_input(query: str) -> str:
"""Sanitize user input to prevent injection attacks."""
# Remove potentially dangerous characters
sanitized = re.sub(r'[<>"\']', '', query)
return sanitized.strip()
def audit_support_interaction(user_id: str, query: str, response: str):
"""Audit support interactions for security."""
audit_log = {
"timestamp": datetime.now().isoformat(),
"user_id": user_id,
"query": query,
"response": response,
"ip_address": get_client_ip(),
"user_agent": get_user_agent()
}
# Log to secure audit system
audit_logger.info(json.dumps(audit_log))
Next Stepsā
This IT Support agent can be extended by:
- Integrating with real ticketing systems (ServiceNow, Jira, Zendesk)
- Adding voice support for phone-based support
- Implementing multi-language support for global teams
- Adding escalation workflows with approval processes
- Creating dashboards for support metrics and analytics
Related Examplesā
- Customer Service Agent - Customer-facing support
- Technical Documentation - Documentation-based support
- Production Agent - Enterprise deployment
Ready for more? Check out the Customer Service Agent example for customer-facing support scenarios!