Customer support teams are inundated with tickets, and manual triage is slow, error-prone, and expensive. In 2026, AI-powered workflow automation is transforming ticketing systems by routing tickets instantly and accurately—freeing up human agents for higher-value work. In this hands-on tutorial, you’ll build a practical, testable AI-driven support ticket routing workflow from scratch. You’ll learn to classify incoming support requests by topic, urgency, or customer type, and automatically assign them to the right agent or queue.
For a broader look at how AI is revolutionizing IT ticketing, see our parent pillar article on AI workflow automation in IT support.
Prerequisites
- Python 3.10+ (tested with Python 3.11)
- Pip for dependency management
- Basic Python programming knowledge
- Familiarity with REST APIs (for ticket system integration)
- OpenAI API key (or similar LLM provider, e.g., Anthropic, Google Vertex AI)
- Sample support ticket data (CSV or JSON)
- Optional: Access to a ticketing platform with API (e.g., Zendesk, Freshdesk, Jira Service Management)
1. Define Your Ticket Routing Criteria
-
Identify routing goals: Decide what categories or criteria matter for your workflow. Common examples:
- Department (e.g., Billing, Technical Support, Sales)
- Urgency (e.g., Critical, High, Normal)
- Customer tier (e.g., Enterprise, SMB, Free)
-
Document your categories: For this tutorial, we’ll use:
- Department: Billing, Technical, Sales
- Urgency: Critical, High, Normal, Low
- Prepare example tickets: Gather 10-20 anonymized support tickets for each category to use as test data.
2. Set Up Your Development Environment
-
Create a new project folder:
mkdir ai-ticket-routing && cd ai-ticket-routing
-
Initialize a virtual environment:
python3 -m venv venv
source venv/bin/activate
-
Install required Python packages:
pip install openai pandas python-dotenv requests
-
Create a
.envfile for your API key:touch .env echo "OPENAI_API_KEY=sk-..." >> .env -
Prepare sample ticket data: Save a CSV file named
tickets.csvwith columns:id,subject,description.id,subject,description 1,Unable to login,I'm locked out of my account and need access urgently. 2,Invoice issue,My last invoice has an incorrect amount. 3,Interested in upgrade,Can you tell me more about the enterprise plan? ...
3. Build the AI Ticket Classification Script
-
Create
classify_ticket.pyThis script will use OpenAI’s GPT-3.5/4 API to classify each ticket by department and urgency.
import os import pandas as pd import openai from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv("OPENAI_API_KEY") DEPARTMENTS = ["Billing", "Technical", "Sales"] URGENCY_LEVELS = ["Critical", "High", "Normal", "Low"] def classify_ticket(ticket_text): prompt = f"""You are an AI support assistant. Given this ticket, assign: - Department: Billing, Technical, or Sales - Urgency: Critical, High, Normal, or Low Ticket: \"\"\" {ticket_text} \"\"\" Respond in JSON: {{"department": "...", "urgency": "..."}}""" response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}], max_tokens=50, temperature=0 ) import json try: result = json.loads(response['choices'][0]['message']['content']) return result['department'], result['urgency'] except Exception as e: print("Error parsing AI response:", e) return None, None def main(): df = pd.read_csv("tickets.csv") departments = [] urgencies = [] for idx, row in df.iterrows(): ticket_text = f"Subject: {row['subject']}\nDescription: {row['description']}" dept, urg = classify_ticket(ticket_text) print(f"Ticket {row['id']} → {dept}, {urg}") departments.append(dept) urgencies.append(urg) df['department'] = departments df['urgency'] = urgencies df.to_csv("tickets_classified.csv", index=False) if __name__ == "__main__": main() -
Run the script:
python classify_ticket.py
Expected output: Each ticket is classified, and a new
tickets_classified.csvfile is created with department and urgency columns.Screenshot description: Terminal output showing ticket IDs and their assigned department and urgency.
4. Implement Automated Ticket Routing Logic
-
Define routing rules:
- Billing → assign to billing@company.com
- Technical (Critical/High) → assign to oncall-tech@company.com
- Technical (Normal/Low) → assign to tech-support@company.com
- Sales → assign to sales@company.com
-
Create
route_ticket.py:import pandas as pd def assign_agent(department, urgency): if department == "Billing": return "billing@company.com" elif department == "Technical": if urgency in ["Critical", "High"]: return "oncall-tech@company.com" else: return "tech-support@company.com" elif department == "Sales": return "sales@company.com" else: return "support@company.com" def main(): df = pd.read_csv("tickets_classified.csv") agents = [] for idx, row in df.iterrows(): agent = assign_agent(row['department'], row['urgency']) agents.append(agent) print(f"Ticket {row['id']} routed to {agent}") df['assigned_agent'] = agents df.to_csv("tickets_routed.csv", index=False) if __name__ == "__main__": main() -
Run the routing script:
python route_ticket.py
Expected output:
tickets_routed.csvnow contains anassigned_agentcolumn.Screenshot description: Table view of tickets with their assigned agents.
5. Integrate with Your Ticketing System (Optional)
- Choose your integration method: Use the ticketing system’s REST API (e.g., Zendesk, Freshdesk, Jira).
-
Example: Assigning tickets in Zendesk via API
- Install
requests(already done) - Update
route_ticket.pyto call the Zendesk API
import os import requests ZENDESK_DOMAIN = "yourcompany.zendesk.com" ZENDESK_EMAIL = "youruser@company.com" ZENDESK_TOKEN = os.getenv("ZENDESK_API_TOKEN") def assign_ticket(ticket_id, agent_email): url = f"https://{ZENDESK_DOMAIN}/api/v2/tickets/{ticket_id}.json" data = { "ticket": { "assignee_email": agent_email } } resp = requests.put( url, json=data, auth=(f"{ZENDESK_EMAIL}/token", ZENDESK_TOKEN) ) if resp.status_code == 200: print(f"Ticket {ticket_id} assigned to {agent_email}") else: print(f"Failed to assign ticket {ticket_id}: {resp.text}")Call
assign_ticketfor each ticket after routing. See your ticketing platform’s API docs for details. - Install
6. Test the Full Workflow
-
Use sample tickets: Start with your
tickets.csvfile. -
Run classification:
python classify_ticket.py
-
Run routing:
python route_ticket.py
-
Verify results: Open
tickets_routed.csvand check that each ticket is assigned as expected. - Optional: Use the API integration to assign tickets in your live system.
- Screenshot description: Side-by-side comparison of input ticket and routed result.
Common Issues & Troubleshooting
-
OpenAI API errors: Ensure your API key is valid and you have sufficient quota. Check
.envfile and environment variable loading. -
Incorrect JSON parsing: Sometimes the AI model may return malformed JSON. Add more explicit instructions to the prompt, or use
temperature=0for deterministic output. - Categories not matching your expectations: Tune your prompt and provide more examples. Consider AI workflow automation templates for customer support for best practices.
- API integration failures: Double-check API endpoints, authentication, and permissions. Use test/sandbox environments before production.
-
Rate limits: Batch tickets and respect provider rate limits. Add
time.sleep()between API calls if needed.
Next Steps
- Expand categories: Add more granular routing (e.g., language detection, sentiment, product line).
- Retrain/tune your prompts: Use real ticket data and feedback to improve classification accuracy.
- Automate end-to-end: Trigger your workflow automatically when new tickets are created via webhooks or event-driven functions.
- Integrate with other business systems: Sync ticket routing with CRM, incident management, or internal dashboards.
- Explore prebuilt solutions: For more scalable tools and templates, see our guide to AI workflow automation for customer support or creative AI automation strategies for SMBs.
- Deepen your knowledge: For a strategic overview, read How AI Workflow Automation Is Transforming IT Ticketing & Support in 2026.
Conclusion
You’ve built a fully functional, testable AI-powered support ticket routing workflow from scratch. This foundation can be extended, productionized, and customized for your organization’s needs. As AI workflow automation becomes the standard in customer support, hands-on skills like these will be essential. For more advanced automations and industry insights, explore our related resources on AI workflow automation tools and the future of IT ticketing.