Skip to content

Commit

Permalink
Fix: deep copy agent memory (#1583)
Browse files Browse the repository at this point in the history
## Description
When running an agent with agent memory on the playground it failed deep
copying un-pickle-able field.

Fixes #1449
  • Loading branch information
manthanguptaa authored Dec 17, 2024
1 parent 2c18b48 commit 40fa745
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions phi/memory/agent.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from enum import Enum
from typing import Dict, List, Any, Optional, Tuple
from copy import deepcopy

from pydantic import BaseModel, ConfigDict

Expand Down Expand Up @@ -357,8 +358,22 @@ def clear(self) -> None:
self.summary = None
self.memories = None

def deep_copy(self, *, update: Optional[Dict[str, Any]] = None) -> "AgentMemory":
new_memory = self.model_copy(deep=True, update=update)
# clear the new memory to remove any references to the old memory
new_memory.clear()
return new_memory
def deep_copy(self):
# Create a shallow copy of the object
copied_obj = self.__class__(**self.model_dump())

# Manually deepcopy fields that are known to be safe
for field_name, field_value in self.__dict__.items():
if field_name not in ["db", "classifier", "manager", "summarizer"]:
try:
setattr(copied_obj, field_name, deepcopy(field_value))
except Exception as e:
logger.warning(f"Failed to deepcopy field: {field_name} - {e}")
setattr(copied_obj, field_name, field_value)

copied_obj.db = self.db
copied_obj.classifier = self.classifier
copied_obj.manager = self.manager
copied_obj.summarizer = self.summarizer

return copied_obj

0 comments on commit 40fa745

Please sign in to comment.