junaidte14 commited on
Commit
2a85837
·
1 Parent(s): fdbb6b3

final working agent system

Browse files
app/services/agents/__pycache__/agent_service.cpython-312.pyc CHANGED
Binary files a/app/services/agents/__pycache__/agent_service.cpython-312.pyc and b/app/services/agents/__pycache__/agent_service.cpython-312.pyc differ
 
app/services/agents/__pycache__/state_machine.cpython-312.pyc CHANGED
Binary files a/app/services/agents/__pycache__/state_machine.cpython-312.pyc and b/app/services/agents/__pycache__/state_machine.cpython-312.pyc differ
 
app/services/agents/agent_service.py CHANGED
@@ -267,33 +267,34 @@ class AgentService:
267
  raise
268
 
269
  async def process_message(
270
- self,
271
- session_id: int,
272
  user_message: str
273
  ) -> Dict[str, Any]:
274
  """
275
  Process user message in agent session
276
-
277
- Args:
278
- session_id: Session ID
279
- user_message: User's message
280
-
281
- Returns:
282
- Dict with agent response and session state
283
  """
284
  try:
 
285
  # Load session
 
286
  result = await self.db.execute(
287
  select(AgentSession).where(AgentSession.id == session_id)
288
  )
 
289
  session = result.scalar_one_or_none()
290
-
291
  if not session:
292
  raise ValueError(f"Session {session_id} not found")
293
-
294
  if session.status != SessionStatus.IN_PROGRESS:
295
- raise ValueError(f"Session is {session.status}, cannot process messages")
296
-
 
 
 
 
 
297
  if session.conversation_id:
298
  await self.conv_service.add_message(
299
  conversation_id=int(session.conversation_id),
@@ -301,22 +302,34 @@ class AgentService:
301
  content=user_message
302
  )
303
 
 
304
  # Load agent
 
305
  agent = await self.get_agent(session.agent_id)
306
-
307
- # Initialize state machine from session state
 
 
308
  state_machine = AgentStateMachine(agent.config)
 
309
  state_machine.current_step_id = session.current_step
310
  state_machine.collected_data = session.collected_data or {}
311
  state_machine.retry_counts = {}
312
-
313
  current_step = state_machine.get_current_step()
314
-
315
  if not current_step:
316
- return await self._complete_session(session, agent, state_machine)
317
-
318
- # Extract value using AI if enabled
 
 
 
 
 
 
319
  extracted_value = None
 
320
  if current_step.get("ai_extract", True):
321
  try:
322
  extracted_value = await self.ai_extractor.extract_value(
@@ -325,24 +338,36 @@ class AgentService:
325
  field_type=current_step.get("field_type", "text"),
326
  validation=current_step.get("validation")
327
  )
 
328
  except Exception as e:
329
- logger.warning(f"AI extraction failed, using raw input: {str(e)}")
330
- extracted_value = None
331
-
332
- # Process input through state machine
333
- result, error = state_machine.process_user_input(user_message, extracted_value)
334
-
 
 
 
 
 
 
 
335
  # Update session state
 
336
  session.collected_data = state_machine.collected_data
337
  session.current_step = state_machine.current_step_id
338
  session.last_activity_at = datetime.utcnow()
339
-
340
- agent_text_response = ""
341
- # Handle different results
 
342
  if result == StepResult.RETRY:
343
- agent_text_response = error or "Please try again."
344
  session.retry_count += 1
345
 
 
 
346
  if session.conversation_id:
347
  await self.conv_service.add_message(
348
  conversation_id=int(session.conversation_id),
@@ -365,10 +390,14 @@ class AgentService:
365
  "collected_data": state_machine.collected_data,
366
  "progress": state_machine.get_progress()
367
  }
368
-
 
 
 
369
  elif result == StepResult.FAILED:
370
 
371
  session.status = SessionStatus.FAILED
 
372
  agent_text_response = f"Session failed: {error}"
373
 
374
  if session.conversation_id:
@@ -384,17 +413,26 @@ class AgentService:
384
 
385
  await self.db.commit()
386
 
387
- logger.warning(f"Session {session_id} failed: {error}")
 
 
388
 
389
  return {
390
  "message": agent_text_response,
 
 
391
  "is_completed": False,
392
  "failed": True
393
  }
394
-
 
 
 
395
  elif result == StepResult.SUCCESS:
396
 
 
397
  if not state_machine.current_step_id:
 
398
  completion_response = await self._complete_session(
399
  session,
400
  agent,
@@ -414,12 +452,11 @@ class AgentService:
414
 
415
  return completion_response
416
 
 
417
  next_step = state_machine.get_current_step()
418
 
419
  agent_text_response = (
420
  f"Great! {next_step['prompt']}"
421
- if next_step
422
- else "Task complete."
423
  )
424
 
425
  session.retry_count = 0
@@ -446,21 +483,32 @@ class AgentService:
446
  "progress": state_machine.get_progress()
447
  }
448
 
449
- # Default fallback
 
 
450
  await self.db.commit()
 
451
  return {
452
- "message": agent_text_response,
453
  "current_step": current_step["id"],
 
454
  "is_completed": False
455
  }
456
-
457
  except ValueError:
458
  raise
 
459
  except Exception as e:
460
  await self.db.rollback()
461
- logger.exception(f"Failed to process message for session {session_id}: {str(e)}")
462
- raise ValueError(f"Failed to process message: {str(e)}")
463
-
 
 
 
 
 
 
464
  async def _complete_session(
465
  self,
466
  session: AgentSession,
@@ -520,12 +568,20 @@ class AgentService:
520
  )
521
 
522
  return {
523
- "message": agent.completion_message or "Thank you! Your submission is complete.",
 
 
 
 
524
  "current_step": None,
525
  "step_prompt": None,
 
526
  "is_completed": True,
 
527
  "collected_data": state_machine.collected_data,
 
528
  "actions_executed": action_results,
 
529
  "session_id": session.id
530
  }
531
 
 
267
  raise
268
 
269
  async def process_message(
270
+ self,
271
+ session_id: int,
272
  user_message: str
273
  ) -> Dict[str, Any]:
274
  """
275
  Process user message in agent session
 
 
 
 
 
 
 
276
  """
277
  try:
278
+ # =========================
279
  # Load session
280
+ # =========================
281
  result = await self.db.execute(
282
  select(AgentSession).where(AgentSession.id == session_id)
283
  )
284
+
285
  session = result.scalar_one_or_none()
286
+
287
  if not session:
288
  raise ValueError(f"Session {session_id} not found")
289
+
290
  if session.status != SessionStatus.IN_PROGRESS:
291
+ raise ValueError(
292
+ f"Session is {session.status}, cannot process messages"
293
+ )
294
+
295
+ # =========================
296
+ # Save USER message
297
+ # =========================
298
  if session.conversation_id:
299
  await self.conv_service.add_message(
300
  conversation_id=int(session.conversation_id),
 
302
  content=user_message
303
  )
304
 
305
+ # =========================
306
  # Load agent
307
+ # =========================
308
  agent = await self.get_agent(session.agent_id)
309
+
310
+ # =========================
311
+ # Restore state machine
312
+ # =========================
313
  state_machine = AgentStateMachine(agent.config)
314
+
315
  state_machine.current_step_id = session.current_step
316
  state_machine.collected_data = session.collected_data or {}
317
  state_machine.retry_counts = {}
318
+
319
  current_step = state_machine.get_current_step()
320
+
321
  if not current_step:
322
+ return await self._complete_session(
323
+ session,
324
+ agent,
325
+ state_machine
326
+ )
327
+
328
+ # =========================
329
+ # AI extraction
330
+ # =========================
331
  extracted_value = None
332
+
333
  if current_step.get("ai_extract", True):
334
  try:
335
  extracted_value = await self.ai_extractor.extract_value(
 
338
  field_type=current_step.get("field_type", "text"),
339
  validation=current_step.get("validation")
340
  )
341
+
342
  except Exception as e:
343
+ logger.warning(
344
+ f"AI extraction failed, using raw input: {str(e)}"
345
+ )
346
+
347
+ # =========================
348
+ # Process input
349
+ # =========================
350
+ result, error = state_machine.process_user_input(
351
+ user_message,
352
+ extracted_value
353
+ )
354
+
355
+ # =========================
356
  # Update session state
357
+ # =========================
358
  session.collected_data = state_machine.collected_data
359
  session.current_step = state_machine.current_step_id
360
  session.last_activity_at = datetime.utcnow()
361
+
362
+ # =========================================================
363
+ # RETRY
364
+ # =========================================================
365
  if result == StepResult.RETRY:
366
+
367
  session.retry_count += 1
368
 
369
+ agent_text_response = error or "Please try again."
370
+
371
  if session.conversation_id:
372
  await self.conv_service.add_message(
373
  conversation_id=int(session.conversation_id),
 
390
  "collected_data": state_machine.collected_data,
391
  "progress": state_machine.get_progress()
392
  }
393
+
394
+ # =========================================================
395
+ # FAILED
396
+ # =========================================================
397
  elif result == StepResult.FAILED:
398
 
399
  session.status = SessionStatus.FAILED
400
+
401
  agent_text_response = f"Session failed: {error}"
402
 
403
  if session.conversation_id:
 
413
 
414
  await self.db.commit()
415
 
416
+ logger.warning(
417
+ f"Session {session_id} failed: {error}"
418
+ )
419
 
420
  return {
421
  "message": agent_text_response,
422
+ "current_step": current_step["id"],
423
+ "step_prompt": current_step["prompt"],
424
  "is_completed": False,
425
  "failed": True
426
  }
427
+
428
+ # =========================================================
429
+ # SUCCESS
430
+ # =========================================================
431
  elif result == StepResult.SUCCESS:
432
 
433
+ # WORKFLOW COMPLETE
434
  if not state_machine.current_step_id:
435
+
436
  completion_response = await self._complete_session(
437
  session,
438
  agent,
 
452
 
453
  return completion_response
454
 
455
+ # MOVE TO NEXT STEP
456
  next_step = state_machine.get_current_step()
457
 
458
  agent_text_response = (
459
  f"Great! {next_step['prompt']}"
 
 
460
  )
461
 
462
  session.retry_count = 0
 
483
  "progress": state_machine.get_progress()
484
  }
485
 
486
+ # =========================================================
487
+ # FALLBACK
488
+ # =========================================================
489
  await self.db.commit()
490
+
491
  return {
492
+ "message": "Unexpected workflow state",
493
  "current_step": current_step["id"],
494
+ "step_prompt": current_step["prompt"],
495
  "is_completed": False
496
  }
497
+
498
  except ValueError:
499
  raise
500
+
501
  except Exception as e:
502
  await self.db.rollback()
503
+
504
+ logger.exception(
505
+ f"Failed to process message for session {session_id}: {str(e)}"
506
+ )
507
+
508
+ raise ValueError(
509
+ f"Failed to process message: {str(e)}"
510
+ )
511
+
512
  async def _complete_session(
513
  self,
514
  session: AgentSession,
 
568
  )
569
 
570
  return {
571
+ "message": (
572
+ agent.completion_message
573
+ or "Thank you! Your submission is complete."
574
+ ),
575
+
576
  "current_step": None,
577
  "step_prompt": None,
578
+
579
  "is_completed": True,
580
+
581
  "collected_data": state_machine.collected_data,
582
+
583
  "actions_executed": action_results,
584
+
585
  "session_id": session.id
586
  }
587
 
app/services/agents/state_machine.py CHANGED
@@ -190,14 +190,7 @@ class AgentStateMachine:
190
  return current_step.get("next_step")
191
 
192
  def is_complete(self) -> bool:
193
- """Check if workflow is complete"""
194
- current_step = self.get_current_step()
195
- if not current_step:
196
- return True
197
-
198
- # Complete if current step has no next step
199
- has_next = current_step.get("next_step") or current_step.get("conditional_next")
200
- return not has_next
201
 
202
  def get_progress(self) -> Dict[str, Any]:
203
  """Get current progress"""
 
190
  return current_step.get("next_step")
191
 
192
  def is_complete(self) -> bool:
193
+ return self.current_step_id is None
 
 
 
 
 
 
 
194
 
195
  def get_progress(self) -> Dict[str, Any]:
196
  """Get current progress"""