File size: 9,053 Bytes
6558d6e
 
 
 
40506ca
6558d6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345bccf
 
6558d6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345bccf
6558d6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40506ca
6558d6e
40506ca
6558d6e
40506ca
 
 
6558d6e
 
40506ca
 
345bccf
40506ca
6558d6e
 
 
 
40506ca
 
 
 
6558d6e
 
40506ca
6558d6e
40506ca
6558d6e
40506ca
 
 
 
6558d6e
 
 
40506ca
6558d6e
40506ca
 
 
 
6558d6e
 
40506ca
 
 
 
6558d6e
 
 
 
 
 
 
40506ca
 
6558d6e
 
 
40506ca
 
 
 
6558d6e
 
40506ca
 
 
6558d6e
40506ca
 
 
 
 
 
b6d91fe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import pickle
import os
from datetime import datetime

CATEGORIES = {
    "easy":   {0:"General", 1:"Billing", 2:"Support", 3:"Technical", 4:"HR"},
    "medium": {0:"General", 1:"Billing", 2:"Support", 3:"Technical", 4:"HR",
               5:"Legal", 6:"Sales", 7:"Marketing", 8:"Operations", 9:"Complaints"},
}

CATEGORY_OVERRIDE = {
    "Technical":  ["crash", "crashes", "bug", "error", "not working", "broken", "upload fail",
                   "application", "software", "login fail", "404", "500", "exception",
                   "loading", "slow", "freeze", "hang", "install", "update failed", "glitch"],
    "Billing":    ["invoice", "charge", "charged", "payment", "refund", "subscription", "billing",
                   "amount", "price", "cost", "fee", "receipt", "transaction", "overcharged"],
    "HR":         ["leave", "salary", "policy", "maternity", "paternity", "holiday", "resignation",
                   "offer letter", "payslip", "appraisal", "human resources", "benefits"],
    "Complaints": ["complaint", "unacceptable", "disgusted", "terrible", "worst", "rude", "awful",
                   "disappointed", "frustrated", "escalate"],
    "Legal":      ["legal", "lawsuit", "compliance", "gdpr", "contract", "terms", "court",
                   "attorney", "lawyer", "liability", "copyright", "trademark"],
}

PRIORITY_RULES = {
    "urgent": ["urgent", "asap", "immediately", "critical", "emergency", "not working",
               "broken", "down", "error", "failed", "crashes", "crash"],
    "high":   ["incorrect", "wrong", "missing", "cannot", "can't", "unable",
               "problem", "issue", "complaint"],
    "medium": ["review", "check", "update", "change", "request", "need", "want", "please"],
    "low":    ["inquiry", "question", "info", "information", "general", "curious", "wondering"]
}

DEPARTMENT_MAP = {
    "Billing":    {"team": "Billing & Finance",   "email": "billing@company.com",    "sla": "24h"},
    "Technical":  {"team": "Tech Support",         "email": "techsupport@company.com","sla": "4h"},
    "HR":         {"team": "Human Resources",      "email": "hr@company.com",         "sla": "48h"},
    "Support":    {"team": "Customer Support",     "email": "support@company.com",    "sla": "12h"},
    "General":    {"team": "General Enquiries",    "email": "hello@company.com",      "sla": "48h"},
    "Legal":      {"team": "Legal & Compliance",   "email": "legal@company.com",      "sla": "72h"},
    "Sales":      {"team": "Sales",                "email": "sales@company.com",      "sla": "6h"},
    "Marketing":  {"team": "Marketing",            "email": "marketing@company.com",  "sla": "48h"},
    "Operations": {"team": "Operations",           "email": "ops@company.com",        "sla": "24h"},
    "Complaints": {"team": "Customer Relations",   "email": "complaints@company.com", "sla": "8h"},
}

REPLY_TEMPLATES = {
    "Billing": """Dear Customer,

Thank you for contacting us regarding your billing inquiry.

We have received your request and our Billing & Finance team will review your account details within 24 hours.

What we'll do:
  - Review your invoice/payment details
  - Verify the transaction in question
  - Send you a detailed resolution

Reference ID: {ref_id}
Priority: {priority}
Expected resolution: {sla}

If urgent, call: +1-800-BILLING

Best regards,
Billing & Finance Team""",

    "Technical": """Dear Customer,

Thank you for reporting this technical issue.

Our Tech Support team has been notified and will respond within 4 hours.

Immediate steps you can try:
  - Clear browser cache and retry
  - Check our status page: status.company.com
  - Restart the application

Reference ID: {ref_id}
Priority: {priority}
Expected resolution: {sla}

For critical issues: techsupport@company.com

Best regards,
Tech Support Team""",

    "HR": """Dear Team Member,

Thank you for reaching out to Human Resources.

Your query has been received and will be handled with full confidentiality.

Our HR team will respond within 48 hours regarding:
  - Policy clarifications
  - Benefits & compensation
  - Workplace concerns

Reference ID: {ref_id}
Priority: {priority}
Expected resolution: {sla}

Best regards,
Human Resources Team""",

    "Support": """Dear Customer,

Thank you for contacting Customer Support.

We have logged your request and a support agent will be in touch within 12 hours.

Reference ID: {ref_id}
Priority: {priority}
Expected resolution: {sla}

Track your ticket: support.company.com/track/{ref_id}

Best regards,
Customer Support Team""",

    "General": """Dear Customer,

Thank you for your inquiry.

We have received your message and will respond within 48 hours.

Reference ID: {ref_id}
Priority: {priority}

Best regards,
General Enquiries Team""",

    "Complaints": """Dear Customer,

We sincerely apologize for your experience.

Your complaint has been escalated to our Customer Relations team who will personally handle this within 8 hours.

Reference ID: {ref_id}
Priority: {priority}
Expected resolution: {sla}

We take all complaints seriously and are committed to resolving this promptly.

Best regards,
Customer Relations Team""",

    "Sales": """Dear Customer,

Thank you for your interest!

Our Sales team will reach out within 6 hours with a personalized proposal.

Reference ID: {ref_id}
Priority: {priority}

Best regards,
Sales Team""",

    "Legal": """Dear Customer,

Thank you for contacting our Legal & Compliance team.

Your matter will be reviewed by our legal team within 72 hours.

Reference ID: {ref_id}
Priority: {priority}
Expected resolution: {sla}

Best regards,
Legal & Compliance Team""",

    "Marketing": """Dear Customer,

Thank you for reaching out to Marketing.

We will respond within 48 hours.

Reference ID: {ref_id}
Priority: {priority}

Best regards,
Marketing Team""",

    "Operations": """Dear Customer,

Thank you for contacting Operations.

Your request has been logged and will be addressed within 24 hours.

Reference ID: {ref_id}
Priority: {priority}
Expected resolution: {sla}

Best regards,
Operations Team""",
}


class TicketAgent:
    def __init__(self, model_dir="."):
        self.models = {}
        self.model_dir = model_dir
        self._load()

    def _load(self):
        for d in ["easy", "medium", "hard"]:
            p = os.path.join(self.model_dir, f"model_{d}.pkl")
            if os.path.exists(p):
                with open(p, "rb") as f:
                    self.models[d] = pickle.load(f)

    def _name(self, c, diff):
        m = CATEGORIES.get(diff, {})
        try:
            return m.get(int(c), str(c))
        except:
            return str(c)

    def classify(self, text, difficulty="easy"):
        text = text.lower()
        
        for cat, kw_list in CATEGORY_OVERRIDE.items():
            if any(kw in text for kw in kw_list):
                if difficulty in self.models:
                    model = self.models[difficulty]
                    classes = model.classes_
                    proba = model.predict_proba([text])[0]
                    scores = {self._name(c, difficulty): round(float(p), 4) for c, p in zip(classes, proba)}
                else:
                    scores = {cat: 1.0}
                scores[cat] = max(scores.get(cat, 0), 0.85)
                return cat, scores
        
        if difficulty not in self.models:
            return "General", {"General": 1.0}
        model = self.models[difficulty]
        classes = model.classes_
        proba = model.predict_proba([text])[0]
        pred = classes[proba.argmax()]
        top = self._name(pred, difficulty)
        scores = {self._name(c, difficulty): round(float(p), 4) for c, p in zip(classes, proba)}
        return top, scores

    def get_priority(self, text):
        text = text.lower()
        for pri, kw_list in PRIORITY_RULES.items():
            if any(kw in text for kw in kw_list):
                return pri
        return "low"

    def route(self, category):
        return DEPARTMENT_MAP.get(category, DEPARTMENT_MAP["General"])

    def generate_reply(self, category, priority, ref_id):
        dept = self.route(category)
        tmpl = REPLY_TEMPLATES.get(category, REPLY_TEMPLATES["General"])
        return tmpl.format(ref_id=ref_id, priority=priority.upper(), sla=dept["sla"])

    def process_ticket(self, text, difficulty="easy", ticket_id=None):
        ref_id = ticket_id or f"TKT-{datetime.now().strftime('%Y%m%d%H%M%S')}"
        cat, scores = self.classify(text, difficulty)
        pri = self.get_priority(text)
        dept = self.route(cat)
        reply = self.generate_reply(cat, pri, ref_id)
        top3 = sorted(scores.items(), key=lambda x: -x[1])[:3]
        return {
            "ref_id": ref_id,
            "category": cat,
            "priority": pri,
            "department": dept["team"],
            "email": dept["email"],
            "sla": dept["sla"],
            "confidence": scores.get(cat, 0.0),
            "top3": top3,
            "reply": reply,
            "timestamp": datetime.now().isoformat()
        }