Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 43 additions & 13 deletions src/memos/api/handlers/memory_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@
remove_embedding_recursive,
sort_children_by_memory_type,
)
from memos.memories.textual.tree_text_memory.retrieve.retrieve_utils import (
cosine_similarity_matrix,
find_best_unrelated_subgroup,
)


if TYPE_CHECKING:
Expand All @@ -41,7 +37,6 @@ def handle_get_all_memories(
mem_cube_id: str,
memory_type: Literal["text_mem", "act_mem", "param_mem", "para_mem"],
naive_mem_cube: Any,
embedder: Any,
) -> MemoryResponse:
"""
Main handler for getting all memories.
Expand All @@ -64,14 +59,6 @@ def handle_get_all_memories(
# Get all text memories from the graph database
memories = naive_mem_cube.text_mem.get_all(user_name=mem_cube_id)

mems = [mem.get("memory", "") for mem in memories.get("nodes", [])]
embeddings = embedder.embed(mems)
similarity_matrix = cosine_similarity_matrix(embeddings)
selected_indices, _ = find_best_unrelated_subgroup(
embeddings, similarity_matrix, bar=0.9
)
memories["nodes"] = [memories["nodes"][i] for i in selected_indices]

# Format and convert to tree structure
memories_cleaned = remove_embedding_recursive(memories)
custom_type_ratios = {
Expand Down Expand Up @@ -176,6 +163,49 @@ def handle_get_subgraph(
raise


def handle_get_memory(memory_id: str, naive_mem_cube: NaiveMemCube) -> GetMemoryResponse:
"""
Handler for getting a single memory by its ID.

Tries to retrieve from text memory first, then preference memory if not found.

Args:
memory_id: The ID of the memory to retrieve
naive_mem_cube: Memory cube instance

Returns:
GetMemoryResponse with the memory data
"""

try:
memory = naive_mem_cube.text_mem.get(memory_id)
except Exception:
memory = None

# If not found in text memory, try preference memory
pref = None
if memory is None and naive_mem_cube.pref_mem is not None:
collection_names = ["explicit_preference", "implicit_preference"]
for collection_name in collection_names:
try:
pref = naive_mem_cube.pref_mem.get_with_collection_name(collection_name, memory_id)
if pref is not None:
break
except Exception:
continue

# Get the data from whichever memory source succeeded
data = (memory or pref).model_dump() if (memory or pref) else None

return GetMemoryResponse(
message="Memory retrieved successfully"
if data
else f"Memory with ID {memory_id} not found",
code=200,
data=data,
)


def handle_get_memories(
get_mem_req: GetMemoryRequest, naive_mem_cube: NaiveMemCube
) -> GetMemoryResponse:
Expand Down
10 changes: 8 additions & 2 deletions src/memos/api/routers/server_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@
naive_mem_cube = components["naive_mem_cube"]
redis_client = components["redis_client"]
status_tracker = TaskStatusTracker(redis_client=redis_client)
embedder = components["embedder"]
graph_db = components["graph_db"]
vector_db = components["vector_db"]

Expand Down Expand Up @@ -302,7 +301,6 @@ def get_all_memories(memory_req: GetMemoryPlaygroundRequest):
),
memory_type=memory_req.memory_type or "text_mem",
naive_mem_cube=naive_mem_cube,
embedder=embedder,
)


Expand All @@ -314,6 +312,14 @@ def get_memories(memory_req: GetMemoryRequest):
)


@router.get("/get_memory/{memory_id}", summary="Get memory by id", response_model=GetMemoryResponse)
def get_memory_by_id(memory_id: str):
return handlers.memory_handler.handle_get_memory(
memory_id=memory_id,
naive_mem_cube=naive_mem_cube,
)


@router.post(
"/delete_memory", summary="Delete memories for user", response_model=DeleteMemoryResponse
)
Expand Down