Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -195,6 +195,130 @@ async def kb_query_endpoint(ticket: TicketRequest):
|
|
| 195 |
traceback.print_exc()
|
| 196 |
raise HTTPException(status_code=500, detail=f"KB query failed: {str(e)}")
|
| 197 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
# -------------------------------
|
| 199 |
# Health Check
|
| 200 |
# -------------------------------
|
|
|
|
| 195 |
traceback.print_exc()
|
| 196 |
raise HTTPException(status_code=500, detail=f"KB query failed: {str(e)}")
|
| 197 |
|
| 198 |
+
# Add this to your EXISTING app.py (don't replace, just add these endpoints)
|
| 199 |
+
|
| 200 |
+
from datetime import datetime
|
| 201 |
+
from typing import Optional
|
| 202 |
+
|
| 203 |
+
# Global conversation storage
|
| 204 |
+
conversations = {}
|
| 205 |
+
|
| 206 |
+
class ConversationRequest(BaseModel):
|
| 207 |
+
text: str
|
| 208 |
+
conversation_id: Optional[str] = None
|
| 209 |
+
user_email: Optional[str] = None
|
| 210 |
+
|
| 211 |
+
@app.post("/chat")
|
| 212 |
+
async def chat_endpoint(request: ConversationRequest):
|
| 213 |
+
"""
|
| 214 |
+
Agentic chat endpoint - handles conversations with memory and auto-escalation.
|
| 215 |
+
"""
|
| 216 |
+
from agent_langchain import process_ticket_langchain, query_kb
|
| 217 |
+
|
| 218 |
+
# Generate or get conversation ID
|
| 219 |
+
if not request.conversation_id:
|
| 220 |
+
conversation_id = f"conv_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{hash(request.text) % 10000}"
|
| 221 |
+
else:
|
| 222 |
+
conversation_id = request.conversation_id
|
| 223 |
+
|
| 224 |
+
# Initialize conversation
|
| 225 |
+
if conversation_id not in conversations:
|
| 226 |
+
conversations[conversation_id] = {
|
| 227 |
+
"messages": [],
|
| 228 |
+
"ticket_info": None,
|
| 229 |
+
"created_at": datetime.now().isoformat()
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
conv = conversations[conversation_id]
|
| 233 |
+
|
| 234 |
+
# Add user message
|
| 235 |
+
conv["messages"].append({
|
| 236 |
+
"role": "user",
|
| 237 |
+
"content": request.text,
|
| 238 |
+
"timestamp": datetime.now().isoformat()
|
| 239 |
+
})
|
| 240 |
+
|
| 241 |
+
# First message - full orchestration
|
| 242 |
+
if len(conv["messages"]) == 1:
|
| 243 |
+
result = process_ticket_langchain(request.text)
|
| 244 |
+
conv["ticket_info"] = {
|
| 245 |
+
"classification": result["classification"],
|
| 246 |
+
"department": result["department"],
|
| 247 |
+
"initial_query": request.text
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
response_text = result["answer"]
|
| 251 |
+
status = result["status"]
|
| 252 |
+
|
| 253 |
+
# Follow-up messages
|
| 254 |
+
else:
|
| 255 |
+
from agent_langchain import llm
|
| 256 |
+
|
| 257 |
+
# Check for escalation keywords
|
| 258 |
+
escalation_keywords = ["not working", "didn't work", "still broken", "escalate", "human", "agent"]
|
| 259 |
+
wants_escalation = any(kw in request.text.lower() for kw in escalation_keywords)
|
| 260 |
+
|
| 261 |
+
if wants_escalation:
|
| 262 |
+
# Try KB one more time with the new query
|
| 263 |
+
kb_result = query_kb(request.text)
|
| 264 |
+
|
| 265 |
+
if kb_result["answer"] and kb_result["confidence"] >= 0.75:
|
| 266 |
+
response_text = f"Let me try a different approach:\n\n{kb_result['answer']}"
|
| 267 |
+
status = "resolved"
|
| 268 |
+
else:
|
| 269 |
+
# Escalate to human
|
| 270 |
+
ticket_id = f"TKT-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
|
| 271 |
+
response_text = f"""I understand the previous solution didn't resolve your issue. I'm escalating this to a human agent.
|
| 272 |
+
|
| 273 |
+
**Ticket ID:** {ticket_id}
|
| 274 |
+
**Department:** {conv['ticket_info']['department']}
|
| 275 |
+
**Priority:** High
|
| 276 |
+
|
| 277 |
+
A specialist from the {conv['ticket_info']['department']} team will contact you within 2-4 business hours. They will have access to our full conversation history.
|
| 278 |
+
|
| 279 |
+
In the meantime, is there anything else I can help clarify about the troubleshooting steps we've tried?"""
|
| 280 |
+
status = "escalated"
|
| 281 |
+
else:
|
| 282 |
+
# Continue conversation with context
|
| 283 |
+
context = f"""You are an IT helpdesk agent. Here's the conversation history:
|
| 284 |
+
|
| 285 |
+
Initial issue: {conv['ticket_info']['initial_query']}
|
| 286 |
+
Classification: {conv['ticket_info']['classification']}
|
| 287 |
+
Department: {conv['ticket_info']['department']}
|
| 288 |
+
|
| 289 |
+
Recent messages:
|
| 290 |
+
"""
|
| 291 |
+
for msg in conv["messages"][-4:]:
|
| 292 |
+
context += f"{msg['role']}: {msg['content']}\n"
|
| 293 |
+
|
| 294 |
+
context += f"\nUser's current message: {request.text}\n\nProvide a helpful response."
|
| 295 |
+
|
| 296 |
+
response_text = llm.invoke(context).content
|
| 297 |
+
status = "in_progress"
|
| 298 |
+
|
| 299 |
+
# Add assistant response
|
| 300 |
+
conv["messages"].append({
|
| 301 |
+
"role": "assistant",
|
| 302 |
+
"content": response_text,
|
| 303 |
+
"status": status,
|
| 304 |
+
"timestamp": datetime.now().isoformat()
|
| 305 |
+
})
|
| 306 |
+
|
| 307 |
+
return {
|
| 308 |
+
"conversation_id": conversation_id,
|
| 309 |
+
"response": response_text,
|
| 310 |
+
"status": status,
|
| 311 |
+
"message_count": len(conv["messages"]),
|
| 312 |
+
"instructions": "Send follow-up messages with the same conversation_id"
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
@app.get("/conversation/{conversation_id}")
|
| 316 |
+
async def get_conversation_endpoint(conversation_id: str):
|
| 317 |
+
"""Get conversation history."""
|
| 318 |
+
if conversation_id not in conversations:
|
| 319 |
+
raise HTTPException(status_code=404, detail="Conversation not found")
|
| 320 |
+
return conversations[conversation_id]
|
| 321 |
+
|
| 322 |
# -------------------------------
|
| 323 |
# Health Check
|
| 324 |
# -------------------------------
|