Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: during agent creation - create new presets in the DB if the preset had overrides (#1159)
Charles Packer76a2137d0d32
diff --git a/memgpt/cli/cli.py b/memgpt/cli/cli.pyindex 76a07db24..fc9bcb012 100644--- a/memgpt/cli/cli.py+++ b/memgpt/cli/cli.py@@ -24,7 +24,7 @@ from memgpt.constants import MEMGPT_DIR, CLI_WARNING_PREFIX, JSON_ENSURE_ASCIIfrom memgpt.agent import Agent, save_agentfrom memgpt.embeddings import embedding_modelfrom memgpt.server.constants import WS_DEFAULT_PORT, REST_DEFAULT_PORT-from memgpt.data_types import AgentState, LLMConfig, EmbeddingConfig, User, Passage+from memgpt.data_types import AgentState, LLMConfig, EmbeddingConfig, User, Passage, Presetfrom memgpt.metadata import MetadataStorefrom memgpt.migrate import migrate_all_agents, migrate_all_sources@@ -643,8 +643,7 @@ def run(# create agenttry:preset_obj = ms.get_preset(name=preset if preset else config.preset, user_id=user.id)- human_obj = ms.get_human(human, user.id)- persona_obj = ms.get_persona(persona, user.id)+ preset_override = Falseif preset_obj is None:# create preset records in metadata storefrom memgpt.presets.presets import add_default_presets@@ -655,14 +654,28 @@ def run(if preset_obj is None:typer.secho("Couldn't find presets in database, please run `memgpt configure`", fg=typer.colors.RED)sys.exit(1)++ human_obj = ms.get_human(human, user.id)if human_obj is None:typer.secho("Couldn't find human {human} in database, please run `memgpt add human`", fg=typer.colors.RED)+ persona_obj = ms.get_persona(persona, user.id)if persona_obj is None:typer.secho("Couldn't find persona {persona} in database, please run `memgpt add persona`", fg=typer.colors.RED)# Overwrite fields in the preset if they were specified- preset_obj.human = ms.get_human(human, user.id).text- preset_obj.persona = ms.get_persona(persona, user.id).text+ if human_obj.text != preset_obj.human:+ preset_override = True+ preset_obj.human = human_obj.text+ if persona_obj.text != preset_obj.human:+ preset_override = True+ preset_obj.persona = persona_obj.text++ # If the user overrode any parts of the preset, we need to create a new preset to refer back to+ if preset_override:+ # Change the name and uuid+ preset_obj = Preset.clone(preset_obj=preset_obj)+ # Then write out to the database for storage+ ms.create_preset(preset=preset_obj)typer.secho(f"-> 🤖 Using persona profile: '{preset_obj.persona_name}'", fg=typer.colors.WHITE)typer.secho(f"-> 🧑 Using human profile: '{preset_obj.human_name}'", fg=typer.colors.WHITE)diff --git a/memgpt/data_types.py b/memgpt/data_types.pyindex cbe7b7ae0..c3cb219ea 100644--- a/memgpt/data_types.py+++ b/memgpt/data_types.py@@ -552,6 +552,21 @@ class Preset(BaseModel):# functions: List[str] = Field(..., description="The functions of the preset.") # TODO: convert to ID# sources: List[str] = Field(..., description="The sources of the preset.") # TODO: convert to ID+ @staticmethod+ def clone(preset_obj: "Preset", new_name_suffix: str = None) -> "Preset":+ """+ Takes a Preset object and an optional new name suffix as input,+ creates a clone of the given Preset object with a new ID and an optional new name,+ and returns the new Preset object.+ """+ new_preset = preset_obj.model_copy()+ new_preset.id = uuid.uuid4()+ if new_name_suffix:+ new_preset.name = f"{preset_obj.name}_{new_name_suffix}"+ else:+ new_preset.name = f"{preset_obj.name}_{str(uuid.uuid4())[:8]}"+ return new_preset+class Function(BaseModel):name: str = Field(..., description="The name of the function.")diff --git a/memgpt/metadata.py b/memgpt/metadata.pyindex c8fc2c41a..cbe2db796 100644--- a/memgpt/metadata.py+++ b/memgpt/metadata.py@@ -648,7 +648,7 @@ class MetadataStore:session.commit()@enforce_types- def get_human(self, name: str, user_id: uuid.UUID) -> str:+ def get_human(self, name: str, user_id: uuid.UUID) -> Optional[HumanModel]:with self.session_maker() as session:results = session.query(HumanModel).filter(HumanModel.name == name).filter(HumanModel.user_id == user_id).all()if len(results) == 0:@@ -657,7 +657,7 @@ class MetadataStore:return results[0]@enforce_types- def get_persona(self, name: str, user_id: uuid.UUID) -> str:+ def get_persona(self, name: str, user_id: uuid.UUID) -> Optional[PersonaModel]:with self.session_maker() as session:results = session.query(PersonaModel).filter(PersonaModel.name == name).filter(PersonaModel.user_id == user_id).all()if len(results) == 0:diff --git a/memgpt/server/rest_api/agents/index.py b/memgpt/server/rest_api/agents/index.pyindex dbdf58532..d71df7b70 100644--- a/memgpt/server/rest_api/agents/index.py+++ b/memgpt/server/rest_api/agents/index.py@@ -65,8 +65,8 @@ def setup_agents_index_router(server: SyncServer, interface: QueuingInterface, p# TODO turn into a pydantic modelname=request.config["name"],preset=request.config["preset"] if "preset" in request.config else None,- # persona_name=request.config["persona_name"] if "persona_name" in request.config else None,- # human_name=request.config["human_name"] if "human_name" in request.config else None,+ persona_name=request.config["persona_name"] if "persona_name" in request.config else None,+ human_name=request.config["human_name"] if "human_name" in request.config else None,persona=request.config["persona"] if "persona" in request.config else None,human=request.config["human"] if "human" in request.config else None,# llm_config=LLMConfigModel(diff --git a/memgpt/server/server.py b/memgpt/server/server.pyindex 4bf4c4e8a..af92d4c94 100644--- a/memgpt/server/server.py+++ b/memgpt/server/server.py@@ -575,6 +575,8 @@ class SyncServer(LockingServer):preset: Optional[str] = None,persona: Optional[str] = None, # NOTE: this is not the name, it's the memory init valuehuman: Optional[str] = None, # NOTE: this is not the name, it's the memory init value+ persona_name: Optional[str] = None,+ human_name: Optional[str] = None,llm_config: Optional[LLMConfig] = None,embedding_config: Optional[EmbeddingConfig] = None,interface: Union[AgentInterface, None] = None,@@ -604,11 +606,13 @@ class SyncServer(LockingServer):# TODO modify to do creation via presettry:preset_obj = self.ms.get_preset(name=preset if preset else self.config.preset, user_id=user_id)+ preset_override = Falseassert preset_obj is not None, f"preset {preset if preset else self.config.preset} does not exist"logger.debug(f"Attempting to create agent from preset:\n{preset_obj}")# Overwrite fields in the preset if they were specified- if human is not None:+ if human is not None and human != preset_obj.human:+ preset_override = Truepreset_obj.human = human# This is a check for a common bug where users were providing filenames instead of valuestry:@@ -620,6 +624,7 @@ class SyncServer(LockingServer):except:passif persona is not None:+ preset_override = Truepreset_obj.persona = personatry:get_persona_text(persona)@@ -629,18 +634,32 @@ class SyncServer(LockingServer):)except:pass+ if human_name is not None and human_name != preset_obj.human_name:+ preset_override = True+ preset_obj.human_name = human_name+ if persona_name is not None and persona_name != preset_obj.persona_name:+ preset_override = True+ preset_obj.persona_name = persona_namellm_config = llm_config if llm_config else self.server_llm_configembedding_config = embedding_config if embedding_config else self.server_embedding_config# TODO remove (https://github.com/cpacker/MemGPT/issues/1138)if function_names is not None:+ preset_override = Trueavailable_tools = self.ms.list_tools(user_id=user_id)available_tools_names = [t.name for t in available_tools]assert all([f_name in available_tools_names for f_name in function_names])preset_obj.functions_schema = [t.json_schema for t in available_tools if t.name in function_names]print("overriding preset_obj tools with:", preset_obj.functions_schema)+ # If the user overrode any parts of the preset, we need to create a new preset to refer back to+ if preset_override:+ # Change the name and uuid+ preset_obj = Preset.clone(preset_obj=preset_obj)+ # Then write out to the database for storage+ self.ms.create_preset(preset=preset_obj)+agent = Agent(interface=interface,preset=preset_obj,@@ -736,8 +755,10 @@ class SyncServer(LockingServer):# TODO remove this eventually when return type get pydanticfied# this is to add persona_name and human_name so that the columns in UI can populatepreset = self.ms.get_preset(name=agent_state.preset, user_id=user_id)- return_dict["persona_name"] = preset.persona_name- return_dict["human_name"] = preset.human_name+ # TODO hack for frontend, remove+ # (top level .persona is persona_name, and nested memory.persona is the state)+ return_dict["persona"] = preset.persona_name+ return_dict["human"] = preset.human_name# Add information about tools# TODO memgpt_agent should really have a field of List[ToolModel]