Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

fix: patch `/rewrite` (#1034)

Charles Packerfb85273a7381
diff --git a/memgpt/agent_store/db.py b/memgpt/agent_store/db.py
index fea91bd36..7441a659f 100644
--- a/memgpt/agent_store/db.py
+++ b/memgpt/agent_store/db.py
@@ -490,6 +490,23 @@ class PostgresStorageConnector(SQLStorageConnector):
def insert(self, record: Record, exists_ok=True):
self.insert_many([record], exists_ok=exists_ok)
+ def update(self, record: RecordType):
+ """
+ Updates a record in the database based on the provided Record object.
+ """
+ with self.session_maker() as session:
+ # Find the record by its ID
+ db_record = session.query(self.db_model).filter_by(id=record.id).first()
+ if not db_record:
+ raise ValueError(f"Record with id {record.id} does not exist.")
+
+ # Update the record with new values from the provided Record object
+ for attr, value in vars(record).items():
+ setattr(db_record, attr, value)
+
+ # Commit the changes to the database
+ session.commit()
+
class SQLLiteStorageConnector(SQLStorageConnector):
def __init__(self, table_type: str, config: MemGPTConfig, user_id, agent_id=None):
@@ -550,3 +567,26 @@ class SQLLiteStorageConnector(SQLStorageConnector):
def insert(self, record: Record, exists_ok=True):
self.insert_many([record], exists_ok=exists_ok)
+
+ def update(self, record: Record):
+ """
+ Updates an existing record in the database with values from the provided record object.
+ """
+ if not record.id:
+ raise ValueError("Record must have an id.")
+
+ with self.session_maker() as session:
+ # Fetch the existing record from the database
+ db_record = session.query(self.db_model).filter_by(id=record.id).first()
+ if not db_record:
+ raise ValueError(f"Record with id {record.id} does not exist.")
+
+ # Update the database record with values from the provided record object
+ for column in self.db_model.__table__.columns:
+ column_name = column.name
+ if hasattr(record, column_name):
+ new_value = getattr(record, column_name)
+ setattr(db_record, column_name, new_value)
+
+ # Commit the changes to the database
+ session.commit()
diff --git a/memgpt/cli/cli.py b/memgpt/cli/cli.py
index 84d088932..fe48dd07c 100644
--- a/memgpt/cli/cli.py
+++ b/memgpt/cli/cli.py
@@ -615,6 +615,15 @@ def run(
# create agent
try:
preset = ms.get_preset(preset_name=agent_state.preset, user_id=user.id)
+ if preset is None:
+ # create preset records in metadata store
+ from memgpt.presets.presets import add_default_presets
+
+ add_default_presets(user.id, ms)
+ # try again
+ preset = ms.get_preset(preset_name=agent_state.preset, user_id=user.id)
+ assert preset is not None, "Couldn't find presets in database, please run `memgpt configure`"
+
memgpt_agent = presets.create_agent_from_preset(
agent_state=agent_state,
preset=preset,
diff --git a/memgpt/main.py b/memgpt/main.py
index b50e2193b..72c0625c6 100644
--- a/memgpt/main.py
+++ b/memgpt/main.py
@@ -227,12 +227,32 @@ def run_agent_loop(memgpt_agent, config: MemGPTConfig, first, ms: MetadataStore,
for x in range(len(memgpt_agent.messages) - 1, 0, -1):
if memgpt_agent.messages[x].get("role") == "assistant":
text = user_input[len("/rewrite ") :].strip()
- args = json.loads(memgpt_agent.messages[x].get("function_call").get("arguments"), strict=JSON_LOADS_STRICT)
- args["message"] = text
- memgpt_agent.messages[x].get("function_call").update(
- {"arguments": json.dumps(args, ensure_ascii=JSON_ENSURE_ASCII)}
- )
- break
+ # Get the current message content
+ # The rewrite target is the output of send_message
+ message_obj = memgpt_agent._messages[x]
+ if message_obj.tool_calls is not None and len(message_obj.tool_calls) > 0:
+ # Check that we hit an assistant send_message call
+ name_string = message_obj.tool_calls[0].function.get("name")
+ if name_string is None or name_string != "send_message":
+ print("Assistant missing send_message function call")
+ break # cancel op
+ args_string = message_obj.tool_calls[0].function.get("arguments")
+ if args_string is None:
+ print("Assistant missing send_message function arguments")
+ break # cancel op
+ args_json = json.loads(args_string, strict=JSON_LOADS_STRICT)
+ if "message" not in args_json:
+ print("Assistant missing send_message message argument")
+ break # cancel op
+
+ # Once we found our target, rewrite it
+ args_json["message"] = text
+ new_args_string = json.dumps(args_json, ensure_ascii=JSON_ENSURE_ASCII)
+ message_obj.tool_calls[0].function["arguments"] = new_args_string
+
+ # To persist to the database, all we need to do is "re-insert" into recall memory
+ memgpt_agent.persistence_manager.recall_memory.storage.update(record=message_obj)
+ break
continue
elif user_input.lower() == "/summarize":
diff --git a/memgpt/presets/presets.py b/memgpt/presets/presets.py
index 8b83ddc57..ebbf7b74f 100644
--- a/memgpt/presets/presets.py
+++ b/memgpt/presets/presets.py
@@ -79,6 +79,7 @@ def create_agent_from_preset(
if not (agent_state.state == {} or agent_state.state is None):
raise ValueError(f"'state' must be uninitialized (empty)")
+ assert preset is not None, "preset cannot be none"
preset_name = agent_state.preset
assert preset_name == preset.name, f"AgentState preset '{preset_name}' does not match preset name '{preset.name}'"
persona = agent_state.persona
diff --git a/tests/test_storage.py b/tests/test_storage.py
index de81c85d6..96d1e5649 100644
--- a/tests/test_storage.py
+++ b/tests/test_storage.py
@@ -210,6 +210,23 @@ def test_storage(storage_connector, table_type, clear_dynamically_created_models
conn.size() == 2
), f"Expected 1 record, got {conn.size()}: {conn.get_all()}" # expect 2, since storage connector filters for agent1
+ # test: update
+ # NOTE: only testing with messages
+ if table_type == TableType.RECALL_MEMORY:
+ TEST_STRING = "hello world"
+
+ updated_record = records[1]
+ updated_record.text = TEST_STRING
+
+ current_record = conn.get(id=updated_record.id)
+ assert current_record is not None, f"Couldn't find {updated_record.id}"
+ assert current_record.text != TEST_STRING, (current_record.text, TEST_STRING)
+
+ conn.update(updated_record)
+ new_record = conn.get(id=updated_record.id)
+ assert new_record is not None, f"Couldn't find {updated_record.id}"
+ assert new_record.text == TEST_STRING, (new_record.text, TEST_STRING)
+
# test: list_loaded_data
# TODO: add back
# if table_type == TableType.ARCHIVAL_MEMORY: