Pulastya0 commited on
Commit
cb63650
·
verified ·
1 Parent(s): fc4553e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -136
app.py CHANGED
@@ -13,7 +13,7 @@ import chromadb
13
  from chromadb.config import Settings
14
  from sentence_transformers import SentenceTransformer
15
 
16
- # Import from the true agent
17
  from agent_langchain import (
18
  process_with_agent,
19
  get_conversation_history,
@@ -24,7 +24,7 @@ from agent_langchain import (
24
  conversations
25
  )
26
 
27
- app = FastAPI(title="Smart Helpdesk AI Agent")
28
 
29
  # Request Models
30
  class TicketRequest(BaseModel):
@@ -100,16 +100,16 @@ async def setup_kb(kb_file: UploadFile = File(...)):
100
  raise HTTPException(status_code=500, detail=f"Setup failed: {str(e)}")
101
 
102
  # -------------------------------
103
- # MAIN ORCHESTRATE ENDPOINT (True Agent)
104
  # -------------------------------
105
  @app.post("/orchestrate")
106
  async def orchestrate_endpoint(ticket: TicketRequest):
107
  """
108
- Main AI Agent endpoint - handles everything:
109
- - Initial ticket processing
110
- - Follow-up conversations
111
- - Automatic escalation decisions
112
- - Multi-turn dialogue
113
  """
114
  try:
115
  result = process_with_agent(
@@ -122,10 +122,10 @@ async def orchestrate_endpoint(ticket: TicketRequest):
122
  "response": result["response"],
123
  "status": result["status"],
124
  "message_count": result["message_count"],
125
- "can_continue": result.get("can_continue", True),
126
  "instructions": {
127
- "continue_conversation": "Send another request with the same conversation_id",
128
- "new_ticket": "Send a request without conversation_id"
129
  }
130
  }
131
 
@@ -195,130 +195,6 @@ 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
- # 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
  # -------------------------------
@@ -332,5 +208,6 @@ async def health():
332
  "status": "ok",
333
  "kb_status": kb_status,
334
  "kb_records": kb_count,
335
- "active_conversations": len(conversations)
 
336
  }
 
13
  from chromadb.config import Settings
14
  from sentence_transformers import SentenceTransformer
15
 
16
+ # Import from autonomous agent
17
  from agent_langchain import (
18
  process_with_agent,
19
  get_conversation_history,
 
24
  conversations
25
  )
26
 
27
+ app = FastAPI(title="Smart Helpdesk AI Agent - Autonomous")
28
 
29
  # Request Models
30
  class TicketRequest(BaseModel):
 
100
  raise HTTPException(status_code=500, detail=f"Setup failed: {str(e)}")
101
 
102
  # -------------------------------
103
+ # MAIN ORCHESTRATE ENDPOINT (Autonomous Agent)
104
  # -------------------------------
105
  @app.post("/orchestrate")
106
  async def orchestrate_endpoint(ticket: TicketRequest):
107
  """
108
+ Main AI Agent endpoint - fully autonomous:
109
+ - Decides its own workflow
110
+ - Handles multi-turn conversations
111
+ - Auto-escalates when needed
112
+ - Maintains context
113
  """
114
  try:
115
  result = process_with_agent(
 
122
  "response": result["response"],
123
  "status": result["status"],
124
  "message_count": result["message_count"],
125
+ "reasoning_trace": result.get("reasoning_trace", []),
126
  "instructions": {
127
+ "continue_conversation": "Include the conversation_id in your next request",
128
+ "new_ticket": "Omit conversation_id to start fresh"
129
  }
130
  }
131
 
 
195
  traceback.print_exc()
196
  raise HTTPException(status_code=500, detail=f"KB query failed: {str(e)}")
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  # -------------------------------
199
  # Health Check
200
  # -------------------------------
 
208
  "status": "ok",
209
  "kb_status": kb_status,
210
  "kb_records": kb_count,
211
+ "active_conversations": len(conversations),
212
+ "agent_type": "Autonomous ReAct Agent with Gemini"
213
  }