Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
Enable loading local agents with refactored recall memory + update MemGPTConfig to default to sqlite + chroma
Sarah Woodersdeb7f3c1e1dd
diff --git a/configs/memgpt_hosted.json b/configs/memgpt_hosted.jsonindex e7958cfa6..8db237706 100644--- a/configs/memgpt_hosted.json+++ b/configs/memgpt_hosted.json@@ -8,5 +8,5 @@"embedding_endpoint": "https://embeddings.memgpt.ai","embedding_model": "BAAI/bge-large-en-v1.5","embedding_dim": 1536,- "embedding_chunk_size": 300-}\ No newline at end of file+ "embedding_chunk_size": 300,+}diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 5b7eb76d1..5bb286edd 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -323,43 +323,38 @@ class Agent(object):# TODO: support loading from specific fileagent_name = agent_config.name+ # TODO: update this for metadata database+# load state- if agent_config.memgpt_version <= "0.2.6":- directory = agent_config.save_state_dir()- json_files = glob.glob(os.path.join(directory, "*.json")) # This will list all .json files in the current directory.- if not json_files:- print(f"/load error: no .json checkpoint files found")- raise ValueError(f"Cannot load {agent_name} - no saved checkpoints found in {directory}")-- # Sort files based on modified timestamp, with the latest file being the first.- filename = max(json_files, key=os.path.getmtime)- state = json.load(open(filename, "r"))-- # load persistence manager- persistence_manager = LocalStateManager.load(agent_config)-- messages = state["messages"]- agent = cls(- config=agent_config,- model=state["model"],- system=state["system"],- functions=link_functions(state["functions"]),- interface=interface,- persistence_manager=persistence_manager,- persistence_manager_init=False,- persona_notes=state["memory"]["persona"],- human_notes=state["memory"]["human"],- messages_total=state["messages_total"] if "messages_total" in state else len(messages) - 1,- )- agent._messages = messages- agent.memory = initialize_memory(state["memory"]["persona"], state["memory"]["human"])- else:- # TODO- agent = cls(- config=agent_config,- persistence_manager=LocalStateManager.load(agent_config),- persistence_manager_init=False,- )+ directory = agent_config.save_state_dir()+ json_files = glob.glob(os.path.join(directory, "*.json")) # This will list all .json files in the current directory.+ if not json_files:+ print(f"/load error: no .json checkpoint files found")+ raise ValueError(f"Cannot load {agent_name} - no saved checkpoints found in {directory}")++ # Sort files based on modified timestamp, with the latest file being the first.+ filename = max(json_files, key=os.path.getmtime)+ state = json.load(open(filename, "r"))++ # load persistence manager+ persistence_manager = LocalStateManager.load(agent_config)++ messages = state["messages"]+ agent = cls(+ config=agent_config,+ model=state["model"],+ system=state["system"],+ functions=link_functions(state["functions"]),+ interface=interface,+ persistence_manager=persistence_manager,+ persistence_manager_init=False,+ persona_notes=state["memory"]["persona"],+ human_notes=state["memory"]["human"],+ messages_total=state["messages_total"] if "messages_total" in state else len(messages) - 1,+ )+ agent._messages = messages+ agent.memory = initialize_memory(state["memory"]["persona"], state["memory"]["human"])+return agentdef verify_first_message_correctness(self, response, require_send_message=True, require_monologue=False):diff --git a/memgpt/cli/cli_config.py b/memgpt/cli/cli_config.pyindex 470732920..0262f4234 100644--- a/memgpt/cli/cli_config.py+++ b/memgpt/cli/cli_config.py@@ -415,7 +415,7 @@ def configure_archival_storage(config: MemGPTConfig):def configure_recall_storage(config: MemGPTConfig):# Configure recall storage backend- recall_storage_options = ["local", "postgres", "chroma"]+ recall_storage_options = ["sqlite", "postgres", "chroma"]recall_storage_type = questionary.select("Select storage backend for recall data:", recall_storage_options, default=config.recall_storage_type).ask()@@ -450,30 +450,18 @@ def configure():# Will pre-populate with defaults, or what the user previously setconfig = MemGPTConfig.load()- model_endpoint_type, model_endpoint = configure_llm_endpoint(config)- model, model_wrapper, context_window = configure_model(config, model_endpoint_type)- embedding_endpoint_type, embedding_endpoint, embedding_dim, embedding_model = configure_embedding_endpoint(config)- default_preset, default_persona, default_human, default_agent = configure_cli(config)- archival_storage_type, archival_storage_uri, archival_storage_path = configure_archival_storage(config)- recall_storage_type, recall_storage_uri, recall_storage_path = configure_recall_storage(config)-- # check credentials- azure_key, azure_endpoint, azure_version, azure_deployment, azure_embedding_deployment = get_azure_credentials()- openai_key = get_openai_credentials()- if model_endpoint_type == "azure" or embedding_endpoint_type == "azure":- if all([azure_key, azure_endpoint, azure_version]):- print(f"Using Microsoft endpoint {azure_endpoint}.")- if all([azure_deployment, azure_embedding_deployment]):- print(f"Using deployment id {azure_deployment}")- else:- raise ValueError(- "Missing environment variables for Azure (see https://memgpt.readthedocs.io/en/latest/endpoints/#azure). Please set then run `memgpt configure` again."- )- if model_endpoint_type == "openai" or embedding_endpoint_type == "openai":- if not openai_key:- raise ValueError(- "Missing environment variables for OpenAI (see https://memgpt.readthedocs.io/en/latest/endpoints/#openai). Please set them and run `memgpt configure` again."- )+ try:+ model_endpoint_type, model_endpoint = configure_llm_endpoint(config)+ model, model_wrapper, context_window = configure_model(+ config=config, model_endpoint_type=model_endpoint_type, model_endpoint=model_endpoint+ )+ embedding_endpoint_type, embedding_endpoint, embedding_dim, embedding_model = configure_embedding_endpoint(config)+ default_preset, default_persona, default_human, default_agent = configure_cli(config)+ archival_storage_type, archival_storage_uri, archival_storage_path = configure_archival_storage(config)+ recall_storage_type, recall_storage_uri, recall_storage_path = configure_recall_storage(config)+ except ValueError as e:+ typer.secho(str(e), fg=typer.colors.RED)+ returnconfig = MemGPTConfig(# model configsdiff --git a/memgpt/config.py b/memgpt/config.pyindex 2c41b0559..5997ce14e 100644--- a/memgpt/config.py+++ b/memgpt/config.py@@ -69,12 +69,12 @@ class MemGPTConfig:embedding_chunk_size: int = 300 # number of tokens# database configs: archival- archival_storage_type: str = "local" # local, db+ archival_storage_type: str = "chroma" # local, dbarchival_storage_path: str = MEMGPT_DIR # TODO: set to memgpt dirarchival_storage_uri: str = None # TODO: eventually allow external vector DB# database configs: recall- recall_storage_type: str = "local" # local, db+ recall_storage_type: str = "sqlite" # local, dbrecall_storage_path: str = MEMGPT_DIRrecall_storage_uri: str = None # TODO: eventually allow external vector DBdiff --git a/memgpt/connectors/chroma.py b/memgpt/connectors/chroma.pyindex 10c42f158..1fbd0c326 100644--- a/memgpt/connectors/chroma.py+++ b/memgpt/connectors/chroma.py@@ -149,7 +149,6 @@ class ChromaStorageConnector(StorageConnector):def save(self):# save to persistence file (nothing needs to be done)printd("Saving chroma")- raise NotImplementedErrordef size(self, filters: Optional[Dict] = {}) -> int:# unfortuantely, need to use pagination to get filteringdiff --git a/memgpt/connectors/storage.py b/memgpt/connectors/storage.pyindex cf9784908..067152089 100644--- a/memgpt/connectors/storage.py+++ b/memgpt/connectors/storage.py@@ -26,6 +26,7 @@ class TableType:DOCUMENTS = "documents" # TODOUSERS = "users" # TODOAGENTS = "agents" # TODO+ DATA_SOURCES = "data_sources" # TODO# table names used by MemGPT@@ -55,11 +56,13 @@ class StorageConnector:self.table_name = self.generate_table_name(agent_config, table_type=table_type)printd(f"Using table name {self.table_name}")- # setup base filters+ # setup base filters for agent-specific tablesif self.table_type == TableType.ARCHIVAL_MEMORY or self.table_type == TableType.RECALL_MEMORY:# agent-specific tableself.filters = {"user_id": self.user_id, "agent_id": self.agent_config.name}- else:++ # setup base filters for user-specific tables+ if self.table_type == TableType.PASSAGES or self.table_type == TableType.DOCUMENTS:self.filters = {"user_id": self.user_id}def get_filters(self, filters: Optional[Dict] = {}):@@ -100,9 +103,16 @@ class StorageConnector:@staticmethoddef get_storage_connector(table_type: TableType, storage_type: Optional[str] = None, agent_config: Optional[AgentConfig] = None):+ print("STORAGE", storage_type, table_type)+# read from config if not providedif storage_type is None:- storage_type = MemGPTConfig.load().archival_storage_type+ if table_type == TableType.ARCHIVAL_MEMORY:+ storage_type = MemGPTConfig.load().archival_storage_type+ elif table_type == TableType.RECALL_MEMORY:+ storage_type = MemGPTConfig.load().recall_storage_type+ # TODO: other tables+ print("read storage from config")if storage_type == "postgres":from memgpt.connectors.db import PostgresStorageConnector@@ -122,7 +132,7 @@ class StorageConnector:return InMemoryStorageConnector(agent_config=agent_config, table_type=table_type)- elif storage_type == "sqllite":+ elif storage_type == "sqlite":from memgpt.connectors.db import SQLLiteStorageConnectorreturn SQLLiteStorageConnector(agent_config=agent_config, table_type=table_type)diff --git a/memgpt/persistence_manager.py b/memgpt/persistence_manager.pyindex 6e0d3dcf9..42a8bba56 100644--- a/memgpt/persistence_manager.py+++ b/memgpt/persistence_manager.py@@ -59,9 +59,40 @@ class LocalStateManager(PersistenceManager):@classmethoddef load(cls, agent_config: AgentConfig):""" Load a LocalStateManager from a file. """ ""- # TODO: remove this class and just init the class- manager = cls(agent_config)- return manager+ # TODO: remove this function+ return cls(agent_config)+ # try:+ # with open(filename, "rb") as f:+ # data = pickle.load(f)+ # except ModuleNotFoundError as e:+ # # Patch for stripped openai package+ # # ModuleNotFoundError: No module named 'openai.openai_object'+ # with open(filename, "rb") as f:+ # unpickler = OpenAIBackcompatUnpickler(f)+ # data = unpickler.load()+ # # print(f"Unpickled data:\n{data.keys()}")++ # from memgpt.openai_backcompat.openai_object import OpenAIObject++ # def convert_openai_objects_to_dict(obj):+ # if isinstance(obj, OpenAIObject):+ # # Convert to dict or handle as needed+ # # print(f"detected OpenAIObject on {obj}")+ # return obj.to_dict_recursive()+ # elif isinstance(obj, dict):+ # return {k: convert_openai_objects_to_dict(v) for k, v in obj.items()}+ # elif isinstance(obj, list):+ # return [convert_openai_objects_to_dict(v) for v in obj]+ # else:+ # return obj++ # data = convert_openai_objects_to_dict(data)+ # # print(f"Converted data:\n{data.keys()}")++ # manager = cls(agent_config)+ # manager.archival_memory = EmbeddingArchivalMemory(agent_config)+ # manager.recall_memory = BaseRecallMemory(agent_config)+ # return managerdef save(self):"""Ensure storage connectors save data"""