diff --git a/database.py b/database.py index cf9b222..87ad873 100644 --- a/database.py +++ b/database.py @@ -14,6 +14,26 @@ class Database(): """Memory database abstraction""" + @staticmethod + def _extract_message_text(raw_content): + """ + Parse raw message JSON and return text content. + Returns None for malformed or unsupported payloads. + """ + try: + msg = ChatMessage.from_json(raw_content) + except (ValueError, KeyError, TypeError) as err: + logging.warning(f"Skipping malformed chat message payload: {err}") + return None + + if msg.is_tool_message(): + return None + + try: + return msg.get_text_content() + except IndexError: + return None + def get(self, conversation_id, user_id): """fetch a conversation by id and user""" @@ -37,14 +57,10 @@ def get(self, conversation_id, user_id): content = conv.get('content', {}).get('text', '') # content is json encoded in memory - msg = ChatMessage.from_json(content) - - # Skip tool related messages as they're intermediate - if msg.is_tool_message(): + content_text = self._extract_message_text(content) + if not content_text: continue - content_text = msg.get_text_content() - if role == 'USER': # If we have a complete Q&A pair, save it if current_question and current_answer: @@ -88,7 +104,8 @@ def list_by_user(self, user_id, top): memoryId=memory_id, actorId=user_id, ) - except: + except Exception as err: + logging.warning(f"list_sessions failed for user {user_id}: {err}") return [] sessions_with_events = [] @@ -152,8 +169,10 @@ def parse_timestamp(event): # memory stores the raw message json # parse the text - msg = ChatMessage.from_json(initial_question) - initial_question = msg.get_text_content() + parsed_question = self._extract_message_text( + initial_question) + if parsed_question: + initial_question = parsed_question # Format timestamp as M/D/YY H:MM AM/PM created_dt = session_data['latest_timestamp']