Automating IT service ticket routing with AI is rapidly becoming a must-have for high-performing IT operations teams. By leveraging AI workflow automation, organizations can drastically reduce response times, improve accuracy, and free up valuable human resources for more strategic work.
As we covered in our complete guide to AI workflow automation for IT operations, ticket routing is one of the highest-impact use cases—and deserves a focused, practical deep dive. In this tutorial, you'll learn step-by-step how to build, test, and deploy an AI-powered workflow for IT ticket routing using open-source tools and cloud APIs.
For additional context, you may want to explore how AI-driven solutions are transforming IT ticketing workflows or review real-world ROI metrics and case studies from organizations already leveraging these automations.
Prerequisites
- Python 3.10+ installed (
python --version) - pip (Python package manager)
- Basic knowledge of Python and REST APIs
- Access to an ITSM tool (e.g., ServiceNow, Jira Service Management, or a test/demo environment)
- OpenAI API key (or Azure OpenAI, or similar LLM provider)
- Sample IT ticket data (CSV or JSON format)
- Linux/macOS terminal or Windows Command Prompt/PowerShell
1. Set Up Your Development Environment
-
Create a project folder:
mkdir ai-ticket-routing-demo && cd ai-ticket-routing-demo
-
Create and activate a virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install required Python packages:
pip install openai pandas requests python-dotenv
openai: For LLM integrationpandas: For data handlingrequests: For HTTP requestspython-dotenv: For environment variable management
-
Set up your OpenAI API key:
- Create a file named
.envin your project root with this content:
OPENAI_API_KEY=sk-...
Replace
sk-...with your actual API key. - Create a file named
Screenshot description: Terminal showing successful creation of virtual environment and package installation.
2. Prepare Sample IT Ticket Data
-
Create a sample CSV file (
tickets.csv):ticket_id,subject,description 1001,Email not working,User cannot send or receive emails since morning. 1002,VPN access issue,Unable to connect to company VPN from home. 1003,Request new laptop,Need a replacement laptop due to hardware failure. 1004,Password reset,User forgot Windows login password. 1005,Application crash,Finance app crashes on login. -
Place
tickets.csvin your project folder.
Screenshot description: Editor window showing tickets.csv with sample rows.
3. Build the AI Ticket Routing Script
-
Create
route_tickets.pyin your project folder:import os import pandas as pd import openai from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv("OPENAI_API_KEY") CATEGORIES = [ "Email Support", "Network/VPN", "Hardware Support", "Password Reset", "Application Support" ] def classify_ticket(subject, description): prompt = f"""You are an IT ticket routing assistant. Categorize the following ticket into one of these categories: {', '.join(CATEGORIES)}. Subject: {subject} Description: {description} Category:""" response = openai.Completion.create( model="text-davinci-003", prompt=prompt, max_tokens=10, temperature=0 ) return response.choices[0].text.strip() def main(): df = pd.read_csv("tickets.csv") df["category"] = df.apply( lambda row: classify_ticket(row["subject"], row["description"]), axis=1 ) df.to_csv("tickets_routed.csv", index=False) print("Ticket routing complete! Output saved to tickets_routed.csv.") if __name__ == "__main__": main() -
Run the routing script:
python route_tickets.py
You should see
tickets_routed.csvgenerated with an extracategorycolumn.
Screenshot description: New CSV file with ticket categories filled in.
4. Integrate with Your ITSM Platform
- Choose your ITSM tool's API: (e.g., ServiceNow, Jira Service Management)
-
Example: Create a function to update ticket assignments via API. Below is a ServiceNow example using
requests:import requests def assign_ticket(ticket_id, category): # Map categories to ServiceNow group IDs or assignment rules group_map = { "Email Support": "email_support_group_id", "Network/VPN": "network_group_id", "Hardware Support": "hardware_group_id", "Password Reset": "password_group_id", "Application Support": "app_support_group_id" } group_id = group_map.get(category) if not group_id: print(f"No group mapping for category {category}") return url = f"https://.service-now.com/api/now/table/incident/{ticket_id}" headers = { "Accept": "application/json", "Content-Type": "application/json" } auth = ("your_username", "your_password") data = { "assignment_group": group_id } response = requests.patch(url, json=data, auth=auth, headers=headers) if response.status_code == 200: print(f"Ticket {ticket_id} assigned to {category}") else: print(f"Failed to assign ticket {ticket_id}: {response.text}") - Replace
<your-instance>,your_username, andyour_passwordwith your ServiceNow credentials. - Map category names to actual group IDs from your ITSM.
- Replace
-
Iterate over routed tickets and assign:
routed_df = pd.read_csv("tickets_routed.csv") for idx, row in routed_df.iterrows(): assign_ticket(row["ticket_id"], row["category"])
Screenshot description: Terminal showing successful assignment logs for each ticket.
5. Automate the Workflow (Optional: Schedule & Monitor)
-
Schedule your script using cron (Linux/macOS):
crontab -e
Add a line to run every hour:
0 * * * * /path/to/venv/bin/python /path/to/ai-ticket-routing-demo/route_tickets.py
-
Set up logging and alerts:
- Add
loggingto your Python script for better monitoring. - Optionally integrate with email or Slack for failure notifications.
- Add
Screenshot description: Cron job list with your workflow scheduled.
Common Issues & Troubleshooting
-
API authentication errors: Double-check your
.envand ITSM credentials. -
OpenAI quota/rate limits: Ensure your API key has sufficient quota; handle
openai.error.RateLimitErrorexceptions. -
Incorrect category assignments: Refine your
CATEGORIESlist or prompt. See how to improve AI ticket routing with generative AI. - ITSM API errors: Ensure ticket IDs and group IDs match your platform; check API docs for required fields.
- CSV encoding issues: Use UTF-8 encoding for all files; open in a compatible editor.
Next Steps
- Expand categories and prompts: Analyze your ticket history to refine and expand classification.
- Integrate feedback loops: Allow agents to correct misrouted tickets and retrain your model (see building a customer support ticket routing workflow with AI).
- Explore advanced workflow automation platforms: Compare leading tools in our feature-by-feature comparison.
- Productionize your solution: Containerize with Docker, deploy on a cloud function, and add monitoring (see our step-by-step ITSM integration guide).
AI-driven ticket routing is just one part of the broader automation landscape. For a strategic overview—including security, cost optimization, and incident response—see our complete guide to AI workflow automation for IT operations.