umangagarwal1008 commited on
Commit
2837446
·
verified ·
1 Parent(s): 5a2fa0e

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +299 -0
app.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import json
4
+ import os
5
+ from openai import OpenAI
6
+
7
+ # Load OpenAI API key and base URL from Colab secrets
8
+ try:
9
+ OPENAI_API_KEY = os.environ.get("API_KEY")
10
+ OPENAI_API_BASE = os.environ.get("API_BASE")
11
+ openai_client = OpenAI(api_key=OPENAI_API_KEY, base_url=OPENAI_API_BASE)
12
+ except Exception as e:
13
+ st.error(f"Error loading OpenAI credentials: {e}")
14
+ st.stop()
15
+
16
+
17
+ # Define the functions for categorization, metadata extraction, priority prediction, and response generation
18
+ def query_openai(prompt, query):
19
+ """
20
+ Queries the OpenAI model with a given prompt and query.
21
+
22
+ Args:
23
+ prompt (str): The prompt for the model.
24
+ query (str): The query to be answered by the model.
25
+
26
+ Returns:
27
+ str: The model's response.
28
+ """
29
+ messages = [
30
+ {"role": "system", "content": prompt},
31
+ {"role": "user", "content": query}
32
+ ]
33
+ response = openai_client.chat.completions.create(
34
+ model="gpt-3.5-turbo", # Or another suitable OpenAI model
35
+ messages=messages,
36
+ max_tokens=500 # Adjust max_tokens as needed
37
+ )
38
+ return response.choices[0].message.content
39
+
40
+ def classify_ticket(prompt, query):
41
+ """
42
+ Classifies a support ticket using the OpenAI model and returns the result in JSON format.
43
+
44
+ Args:
45
+ prompt (str): The classification prompt for the model.
46
+ query (str): The support ticket text to be classified.
47
+
48
+ Returns:
49
+ dict: A dictionary containing the classification result, or None if classification fails.
50
+ """
51
+ try:
52
+ response_text = query_openai(prompt, query)
53
+ # Attempt to parse the response text as JSON
54
+ classification_result = json.loads(response_text)
55
+ return classification_result
56
+ except json.JSONDecodeError as e:
57
+ st.error(f"Error decoding JSON from OpenAI response: {e}")
58
+ st.text(f"Raw OpenAI response: {response_text}")
59
+ return None
60
+ except Exception as e:
61
+ st.error(f"An unexpected error occurred during classification: {e}")
62
+ return None
63
+
64
+ def extract_metadata(prompt, query):
65
+ """
66
+ Extracts metadata from a support ticket using the OpenAI model and returns the result in JSON format.
67
+
68
+ Args:
69
+ prompt (str): The metadata extraction prompt for the model.
70
+ query (str): The support ticket text to extract metadata from.
71
+
72
+ Returns:
73
+ dict: A dictionary containing the extracted metadata, or None if extraction fails.
74
+ """
75
+ try:
76
+ response_text = query_openai(prompt, query)
77
+ # Attempt to parse the response text as JSON
78
+ metadata_result = json.loads(response_text)
79
+ return metadata_result
80
+ except json.JSONDecodeError as e:
81
+ st.error(f"Error decoding JSON from OpenAI response: {e}")
82
+ st.text(f"Raw OpenAI response: {response_text}")
83
+ return None
84
+ except Exception as e:
85
+ st.error(f"An unexpected error occurred during metadata extraction: {e}")
86
+ return None
87
+
88
+ def predict_priority(prompt, query, problem_type, user_impact):
89
+ """
90
+ Predicts the priority of a support ticket using the OpenAI model and returns the result in JSON format.
91
+
92
+ Args:
93
+ prompt (str): The priority prediction prompt for the model.
94
+ query (str): The support ticket text to predict the priority for.
95
+ problem_type (str): The extracted problem type.
96
+ user_impact (str): The extracted user impact.
97
+
98
+ Returns:
99
+ dict: A dictionary containing the predicted priority, or None if prediction fails.
100
+ """
101
+ try:
102
+ # Include problem_type and user_impact in the query sent to the model
103
+ full_query = f"""
104
+ Support Ticket: {query}
105
+ Problem Type: {problem_type}
106
+ User Impact: {user_impact}
107
+
108
+ Based on the support ticket, problem type, and user impact, predict the priority: Low, Medium, High, or Urgent.
109
+ Return only a structured JSON output in the following format:
110
+ {{"priority": "priority_prediction"}}
111
+ """
112
+ response_text = query_openai(prompt, full_query)
113
+ priority_result = json.loads(response_text)
114
+ return priority_result
115
+ except json.JSONDecodeError as e:
116
+ st.error(f"Error decoding JSON from OpenAI response: {e}")
117
+ st.text(f"Raw OpenAI response: {response_text}")
118
+ return None
119
+ except Exception as e:
120
+ st.error(f"An unexpected error occurred during priority prediction: {e}")
121
+ return None
122
+
123
+ def generate_response(response_prompt, query, category, metadata_tags, priority):
124
+ """
125
+ Generates a draft response for a support ticket using the OpenAI model.
126
+
127
+ Args:
128
+ response_prompt (str): The prompt for generating the response.
129
+ query (str): The original support ticket text.
130
+ category (str): The predicted category of the ticket.
131
+ metadata_tags (dict): The extracted metadata tags (Device, Problem Type, User Impact).
132
+ priority (str): The predicted priority of the ticket.
133
+
134
+ Returns:
135
+ str: The generated response text, or None if response generation fails.
136
+ """
137
+ # Combine the inputs into a single message for the model
138
+ user_message = f"""
139
+ Support Ticket: {query}
140
+ Category: {category}
141
+ Metadata Tags: {metadata_tags}
142
+ Priority: {priority}
143
+ """
144
+
145
+ try:
146
+ # Pass the combined message to the query_openai function
147
+ response_text = query_openai(response_prompt, user_message)
148
+ return response_text
149
+ except Exception as e:
150
+ st.error(f"An unexpected error occurred during response generation: {e}")
151
+ return None
152
+
153
+ # Define the prompts
154
+ classification_prompt = """
155
+ You are a technical assistant. Classify the support ticket based on the Support Ticket Text presented in the input into the following categories and not any other.
156
+ - Technical issues
157
+ - Hardware issues
158
+ - Data recovery
159
+ Return only a structured JSON output in the following format:
160
+ {"Category": "category_prediction"}
161
+ """
162
+
163
+ metadata_prompt = f"""
164
+ You are an intelligent assistant that extracts structured metadata from technical support queries.
165
+ Analyze the query and extract the following information:
166
+
167
+ * **Device** (e.g., Laptop, Phone, Router, etc.)
168
+ * **Problem Type** (e.g., Not Turning On, Lost Internet, Deleted Files)
169
+ * **User Impact** — Estimate based on how severely the issue affects the user's ability to continue working or using the device:
170
+
171
+ * **Blocker**: The user cannot proceed with work at all.
172
+ * **Major**: The user is heavily impacted but may have a workaround.
173
+ * **Moderate**: The issue is disruptive but not critical.
174
+ * **Minor**: The issue is present but does not significantly hinder usage.
175
+
176
+ Use the following **few-shot examples** as guidance. Return your output in **pure JSON format only**.
177
+
178
+ **Few-shot Examples:**
179
+
180
+ Query: My phone battery is draining rapidly even on battery saver mode. I barely use it and it drops 50% in a few hours.
181
+ Output:
182
+ Device: Phone,
183
+ Problem Type: Battery Draining,
184
+ User Impact: Moderate
185
+
186
+
187
+
188
+ Query: I accidentally deleted a folder containing all project files. Please help me recover it.
189
+ Output:
190
+ Device: Laptop,
191
+ Problem Type: Deleted Files,
192
+ User Impact: Blocker
193
+
194
+
195
+
196
+ Query: My router is not working.
197
+ Output:
198
+ Device: Router,
199
+ Problem Type: Lost Internet,
200
+ User Impact: Minor
201
+
202
+
203
+ Only return your final output in valid JSON format without any additional explanation.
204
+ """
205
+
206
+ priority_prompt ="""
207
+ You are an intelligent assistant that determines the priority level of a support ticket.
208
+
209
+ For any given ticket, follow this step-by-step reasoning process to assign the correct priority level: Low, Medium, High, or Urgent.
210
+
211
+ Step-by-step Evaluation:
212
+ Is the device or service completely unusable?
213
+
214
+ Is the issue blocking critical or time-sensitive work?
215
+
216
+ Is there a specific deadline or urgency mentioned by the user?
217
+
218
+ Does the user mention partial functionality or ongoing work?
219
+
220
+ Is the tone or language expressing frustration or emergency?
221
+
222
+ After evaluating each step, decide the most appropriate priority level based on the impact and urgency.
223
+
224
+ Finally, return only the structured output in valid dictionary format, like this:
225
+ {"priority": "High"}
226
+
227
+ Do not include your reasoning in the output — just the json.
228
+ """
229
+
230
+ response_prompt = """
231
+ You are provided with a support ticket along with its Category, Tags, and assigned Priority level.
232
+
233
+ Your task is to draft a short, empathetic response to the customer based on this information.
234
+
235
+ Guidelines:
236
+ 1. Read the support ticket carefully and understand the customer's sentiment.
237
+ 2. Use the Category and Tags to acknowledge the issue accurately.
238
+ 3. Include an estimated time of resolution (ETA) based on the Priority level.
239
+ 4. Ensure the tone is empathetic and reassuring.
240
+ 5. Limit the response to fewer than 48 words.
241
+
242
+ Return only the final response to the customer. Do not include any explanations or formatting.
243
+ """
244
+
245
+
246
+ # Streamlit App
247
+ st.title("Support Ticket Categorization System")
248
+
249
+ st.write("Enter the support ticket text below:")
250
+
251
+ support_ticket_input = st.text_area("Support Ticket Text", height=200)
252
+
253
+ if st.button("Process Ticket"):
254
+ if support_ticket_input:
255
+ st.write("Processing...")
256
+
257
+ # Categorization
258
+ category_result = classify_ticket(classification_prompt, support_ticket_input)
259
+ category = category_result.get('Category') if category_result else "N/A"
260
+ st.subheader("Category:")
261
+ st.write(category)
262
+
263
+ # Metadata Extraction
264
+ metadata_result = extract_metadata(metadata_prompt, support_ticket_input)
265
+ device = metadata_result.get('Device') if metadata_result else "N/A"
266
+ problem_type = metadata_result.get('Problem Type') if metadata_result else "N/A"
267
+ user_impact = metadata_result.get('User Impact') if metadata_result else "N/A"
268
+
269
+ st.subheader("Metadata:")
270
+ st.write(f"Device: {device}")
271
+ st.write(f"Problem Type: {problem_type}")
272
+ st.write(f"User Impact: {user_impact}")
273
+
274
+ # Priority Prediction
275
+ priority_result = predict_priority(priority_prompt, support_ticket_input, problem_type, user_impact)
276
+ priority = priority_result.get('priority') if priority_result else "N/A"
277
+ st.subheader("Priority:")
278
+ st.write(priority)
279
+
280
+ # Draft Response Generation
281
+ draft_response = generate_response(response_prompt, support_ticket_input, category, metadata_result, priority)
282
+ st.subheader("Draft Response:")
283
+ st.write(draft_response)
284
+
285
+ # Save results (optional - you can modify this to save to a file)
286
+ results = {
287
+ "support_ticket_text": support_ticket_input,
288
+ "Category": category,
289
+ "Device": device,
290
+ "Problem Type": problem_type,
291
+ "User Impact": user_impact,
292
+ "Priority": priority,
293
+ "draft_response": draft_response
294
+ }
295
+ st.subheader("All Results (JSON):")
296
+ st.json(results)
297
+
298
+ else:
299
+ st.warning("Please enter support ticket text to process.")