Baolina commited on
Commit
39d52c2
·
verified ·
1 Parent(s): 2e22837

Create app.py

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