fix(memory): handle Mem0 get_all returning string or dict items (#11)

Mem0's get_all() method may return a list containing either strings
(older version format) or dictionaries (newer version format). This
fix adds proper type checking to handle both cases gracefully.

- get_all_memories: Skip string items, only process dict items
- delete_memory: Add type checking before accessing dict methods
- delete_all_memories: Add type checking before accessing dict methods

Fixes: 'str' object has no attribute 'get' error

Co-authored-by: zhuchao <zhuchaowe@163.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
autobee-sparticle 2026-03-02 22:02:59 +09:00 committed by GitHub
parent a1f60a7024
commit 572374b297
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -476,11 +476,19 @@ class Mem0Manager:
# 获取所有记忆
memories = mem.get_all(user_id=user_id)
# 过滤 agent_id
filtered_memories = [
m for m in memories
if m.get("metadata", {}).get("agent_id") == agent_id
]
# Mem0 的 get_all 可能返回字符串列表或字典列表,需要统一处理
filtered_memories = []
for m in memories:
# 如果是字符串,跳过(旧版本格式,不包含 metadata
if isinstance(m, str):
logger.warning(f"Memory item is string, skipping: {m[:50]}...")
continue
# 如果是字典,检查 agent_id
if isinstance(m, dict):
metadata = m.get("metadata", {})
if isinstance(metadata, dict) and metadata.get("agent_id") == agent_id:
filtered_memories.append(m)
return filtered_memories
@ -511,11 +519,18 @@ class Mem0Manager:
memories = mem.get_all(user_id=user_id)
target_memory = None
for m in memories:
if m.get("id") == memory_id:
# 验证 agent_id 匹配
if m.get("metadata", {}).get("agent_id") == agent_id:
target_memory = m
break
# 跳过字符串类型的记忆(旧版本格式)
if isinstance(m, str):
continue
# 只处理字典类型
if isinstance(m, dict):
if m.get("id") == memory_id:
# 验证 agent_id 匹配
metadata = m.get("metadata", {})
if isinstance(metadata, dict) and metadata.get("agent_id") == agent_id:
target_memory = m
break
if not target_memory:
logger.warning(f"Memory {memory_id} not found or access denied for user={user_id}, agent={agent_id}")
@ -552,16 +567,24 @@ class Mem0Manager:
memories = mem.get_all(user_id=user_id)
# 过滤 agent_id 并删除
# Mem0 的 get_all 可能返回字符串列表或字典列表,需要统一处理
deleted_count = 0
for m in memories:
if m.get("metadata", {}).get("agent_id") == agent_id:
memory_id = m.get("id")
if memory_id:
try:
mem.delete(memory_id=memory_id)
deleted_count += 1
except Exception as e:
logger.warning(f"Failed to delete memory {memory_id}: {e}")
# 跳过字符串类型的记忆(旧版本格式)
if isinstance(m, str):
continue
# 只处理字典类型
if isinstance(m, dict):
metadata = m.get("metadata", {})
if isinstance(metadata, dict) and metadata.get("agent_id") == agent_id:
memory_id = m.get("id")
if memory_id:
try:
mem.delete(memory_id=memory_id)
deleted_count += 1
except Exception as e:
logger.warning(f"Failed to delete memory {memory_id}: {e}")
logger.info(f"Deleted {deleted_count} memories for user={user_id}, agent={agent_id}")
return deleted_count