Skip to content

Commit 7585a29

Browse files
fix: replace recursive _traverse_messages with iterative approach to handle deep conversation threads (#235)
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Paul Hernandez <phernandez@users.noreply.github.com>
1 parent 752c78c commit 7585a29

1 file changed

Lines changed: 22 additions & 12 deletions

File tree

src/basic_memory/importers/chatgpt_importer.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ def _get_message_content(self, message: Dict[str, Any]) -> str: # pragma: no co
193193
def _traverse_messages(
194194
self, mapping: Dict[str, Any], root_id: Optional[str], seen: Set[str]
195195
) -> List[Dict[str, Any]]: # pragma: no cover
196-
"""Traverse message tree and return messages in order.
196+
"""Traverse message tree iteratively to handle deep conversations.
197197
198198
Args:
199199
mapping: Message mapping.
@@ -204,19 +204,29 @@ def _traverse_messages(
204204
List of message data.
205205
"""
206206
messages = []
207-
node = mapping.get(root_id) if root_id else None
208-
209-
while node:
207+
if not root_id:
208+
return messages
209+
210+
# Use iterative approach with stack to avoid recursion depth issues
211+
stack = [root_id]
212+
213+
while stack:
214+
node_id = stack.pop()
215+
if not node_id:
216+
continue
217+
218+
node = mapping.get(node_id)
219+
if not node:
220+
continue
221+
222+
# Process current node if it has a message and hasn't been seen
210223
if node["id"] not in seen and node.get("message"):
211224
seen.add(node["id"])
212225
messages.append(node["message"])
213-
214-
# Follow children
226+
227+
# Add children to stack in reverse order to maintain conversation flow
215228
children = node.get("children", [])
216-
for child_id in children:
217-
child_msgs = self._traverse_messages(mapping, child_id, seen)
218-
messages.extend(child_msgs)
219-
220-
break # Don't follow siblings
221-
229+
for child_id in reversed(children):
230+
stack.append(child_id)
231+
222232
return messages

0 commit comments

Comments
 (0)