NEXAS commited on
Commit
460f249
·
verified ·
1 Parent(s): 5236b40

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +49 -4
agent.py CHANGED
@@ -1,6 +1,7 @@
1
  import logging
2
  import asyncio
3
  import json
 
4
  import os
5
  from datetime import datetime
6
  from zoneinfo import ZoneInfo
@@ -737,6 +738,7 @@ async def generate_and_save_summary(db: Database, chat_ctx: llm.ChatContext, con
737
  logger.info("Generating conversation summary...")
738
 
739
  transcript = ""
 
740
 
741
  # Try to extract messages from chat context
742
  try:
@@ -751,11 +753,54 @@ async def generate_and_save_summary(db: Database, chat_ctx: llm.ChatContext, con
751
  if isinstance(item, llm.ChatMessage):
752
  role = item.role
753
  content = item.content
 
 
 
754
  if isinstance(content, list):
755
- content = " ".join([str(c) for c in content])
 
 
 
 
 
 
 
 
 
 
 
756
 
757
- if isinstance(content, str):
758
- transcript += f"{role}: {content}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
759
  except Exception as e:
760
  logger.error(f"Error extracting transcript: {e}")
761
 
@@ -1153,7 +1198,7 @@ async def entrypoint(ctx: JobContext):
1153
  await asyncio.sleep(1)
1154
 
1155
  contact_number = user_context.get("contact_number")
1156
- if contact_number:
1157
  logger.info("Disconnect summary generation (backup)...")
1158
  duration = (datetime.now() - start_time).total_seconds()
1159
  user_name = user_context.get("user_name", "the patient")
 
1
  import logging
2
  import asyncio
3
  import json
4
+ import uuid
5
  import os
6
  from datetime import datetime
7
  from zoneinfo import ZoneInfo
 
738
  logger.info("Generating conversation summary...")
739
 
740
  transcript = ""
741
+ messages_to_save = []
742
 
743
  # Try to extract messages from chat context
744
  try:
 
753
  if isinstance(item, llm.ChatMessage):
754
  role = item.role
755
  content = item.content
756
+
757
+ # Format content for string manipulation
758
+ content_str = content
759
  if isinstance(content, list):
760
+ content_str = " ".join([str(c) for c in content])
761
+
762
+ if isinstance(content_str, str):
763
+ transcript += f"{role}: {content_str}\n"
764
+
765
+ # Prepare for DB
766
+ msg_data = {
767
+ "role": role,
768
+ "content": content_str,
769
+ "tool_name": None,
770
+ "tool_args": None
771
+ }
772
 
773
+ # Attempt to extract tool info safely
774
+ if hasattr(item, 'tool_calls') and item.tool_calls:
775
+ try:
776
+ tc = item.tool_calls[0]
777
+ # Handle both object and dict (depending on underlying library version)
778
+ if isinstance(tc, dict):
779
+ msg_data["tool_name"] = tc.get('function', {}).get('name')
780
+ msg_data["tool_args"] = tc.get('function', {}).get('arguments')
781
+ else:
782
+ # accessing attributes of ToolCall object
783
+ fn = getattr(tc, 'function', None)
784
+ if fn:
785
+ msg_data["tool_name"] = getattr(fn, 'name', None)
786
+ msg_data["tool_args"] = getattr(fn, 'arguments', None)
787
+ except Exception:
788
+ pass # Ignore tool extraction errors
789
+
790
+ if role == "tool":
791
+ msg_data["tool_name"] = getattr(item, 'name', getattr(item, 'tool_call_id', None))
792
+
793
+ messages_to_save.append(msg_data)
794
+
795
+ # Save transcript to DB
796
+ if messages_to_save:
797
+ try:
798
+ # Generate a session ID for this conversation batch
799
+ session_id = str(uuid.uuid4())
800
+ db.save_chat_transcript(session_id, contact_number, messages_to_save)
801
+ except Exception as e:
802
+ logger.error(f"Failed to save chat transcript to DB: {e}")
803
+
804
  except Exception as e:
805
  logger.error(f"Error extracting transcript: {e}")
806
 
 
1198
  await asyncio.sleep(1)
1199
 
1200
  contact_number = user_context.get("contact_number")
1201
+ if contact_number and not assistant.summary_generated:
1202
  logger.info("Disconnect summary generation (backup)...")
1203
  duration = (datetime.now() - start_time).total_seconds()
1204
  user_name = user_context.get("user_name", "the patient")