Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
refactor: Use `Message` types inside Agent state (`agent.messages`), enabling immediate tracking of `Message` objects (#836)
Charles Packerc07746b09705
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 267db56ea..2c85ab9d0 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -6,9 +6,12 @@ import osimport jsonfrom pathlib import Pathimport traceback+from typing import List, Tuple-from memgpt.data_types import AgentState-from memgpt.metadata import MetadataStore+from box import Box++from memgpt.data_types import AgentState, Message+from memgpt.models import chat_completion_responsefrom memgpt.interface import AgentInterfacefrom memgpt.persistence_manager import PersistenceManager, LocalStateManagerfrom memgpt.config import MemGPTConfig@@ -16,6 +19,7 @@ from memgpt.system import get_login_event, package_function_response, package_sufrom memgpt.memory import CoreMemory as InContextMemory, summarize_messagesfrom memgpt.openai_tools import create, is_context_overflow_errorfrom memgpt.utils import (+ get_tool_call_id,get_local_time,parse_json,united_diff,@@ -171,7 +175,6 @@ class Agent(object):memgpt_config: MemGPTConfig = None,):# Hold a copy of the state that was used to init the agent- self.config = agent_state # TODO: removeself.agent_state = agent_state# gpt-4, gpt-3.5-turbo, ...@@ -196,17 +199,6 @@ class Agent(object):if "human" not in agent_state.state:raise ValueError(f"'human' not found in provided AgentState")self.memory = initialize_memory(ai_notes=agent_state.state["persona"], human_notes=agent_state.state["human"])- # Once the memory object is initialize, use it to "bake" the system message- if "messages" in agent_state.state and agent_state.state["messages"] is not None:- if not isinstance(agent_state.state["messages"], list):- raise ValueError(f"'messages' in AgentState was bad type: {type(agent_state.state['messages'])}")- self._messages = agent_state.state["messages"]- else:- self._messages = initialize_message_sequence(- self.model,- self.system,- self.memory,- )# Interface must implement:# - internal_monologue@@ -221,12 +213,6 @@ class Agent(object):# TODOself.persistence_manager = LocalStateManager(agent_state=agent_state)- # Keep track of the total number of messages throughout all time- self.messages_total = messages_total if messages_total is not None else (len(self._messages) - 1) # (-system)- # self.messages_total_init = self.messages_total- self.messages_total_init = len(self._messages) - 1- printd(f"Agent initialized, self.messages_total={self.messages_total}")-# State needed for heartbeat pausingself.pause_heartbeats_start = Noneself.pause_heartbeats_minutes = 0@@ -245,14 +231,54 @@ class Agent(object):self.memgpt_config = memgpt_config# Initialize connection to metedata store- self.ms = MetadataStore(self.memgpt_config)+ # self.ms = MetadataStore(self.memgpt_config)++ # Once the memory object is initialized, use it to "bake" the system message+ if "messages" in agent_state.state and agent_state.state["messages"] is not None:+ # print(f"Agent.__init__ :: loading, state={agent_state.state['messages']}")+ if not isinstance(agent_state.state["messages"], list):+ raise ValueError(f"'messages' in AgentState was bad type: {type(agent_state.state['messages'])}")+ assert all([isinstance(msg, str) for msg in agent_state.state["messages"]])++ # Convert to IDs, and pull from the database+ self._messages = [+ self.persistence_manager.recall_memory.storage.get(uuid.UUID(msg_id)) for msg_id in agent_state.state["messages"]+ ]+ assert all([isinstance(msg, Message) for msg in self._messages]), (self._messages, agent_state.state["messages"])+ else:+ # print(f"Agent.__init__ :: creating, state={agent_state.state['messages']}")+ init_messages = initialize_message_sequence(+ self.model,+ self.system,+ self.memory,+ )+ init_messages_objs = []+ for msg in init_messages:+ init_messages_objs.append(+ Message.dict_to_message(+ agent_id=self.agent_state.id, user_id=self.agent_state.user_id, model=self.model, openai_message_dict=msg+ )+ )+ self._messages = []+ self.messages_total = 0+ self._append_to_messages(added_messages=init_messages_objs)++ assert all([isinstance(msg, Message) for msg in self._messages]), (self._messages, init_messages)++ # Keep track of the total number of messages throughout all time+ self.messages_total = messages_total if messages_total is not None else (len(self._messages) - 1) # (-system)+ # self.messages_total_init = self.messages_total+ self.messages_total_init = len(self._messages) - 1+ printd(f"Agent initialized, self.messages_total={self.messages_total}")# Create the agent in the DB- self.save()+ # self.save()+ self.update_state()@property- def messages(self):- return self._messages+ def messages(self) -> List[dict]:+ """Getter method that converts the internal Message list into OpenAI-style dicts"""+ return [msg.to_openai_dict() for msg in self._messages]@messages.setterdef messages(self, value):@@ -265,45 +291,51 @@ class Agent(object):new_messages = [self.messages[0]] + self.messages[num:]self._messages = new_messages- def _prepend_to_messages(self, added_messages):+ def _prepend_to_messages(self, added_messages: List[Message]):"""Wrapper around self.messages.prepend to allow additional calls to a state/persistence manager"""+ assert all([isinstance(msg, Message) for msg in added_messages])+self.persistence_manager.prepend_to_messages(added_messages)new_messages = [self.messages[0]] + added_messages + self.messages[1:] # prepend (no system)self._messages = new_messagesself.messages_total += len(added_messages) # still should increment the message counter (summaries are additions too)- def _append_to_messages(self, added_messages):+ def _append_to_messages(self, added_messages: List[Message]):"""Wrapper around self.messages.append to allow additional calls to a state/persistence manager"""+ assert all([isinstance(msg, Message) for msg in added_messages])+self.persistence_manager.append_to_messages(added_messages)# strip extra metadata if it exists- for msg in added_messages:- msg.pop("api_response", None)- msg.pop("api_args", None)- new_messages = self.messages + added_messages # append+ # for msg in added_messages:+ # msg.pop("api_response", None)+ # msg.pop("api_args", None)+ new_messages = self._messages + added_messages # appendself._messages = new_messagesself.messages_total += len(added_messages)- def _swap_system_message(self, new_system_message):- assert new_system_message["role"] == "system", new_system_message- assert self.messages[0]["role"] == "system", self.messages+ def _swap_system_message(self, new_system_message: Message):+ assert isinstance(new_system_message, Message)+ assert new_system_message.role == "system", new_system_message+ assert self._messages[0].role == "system", self._messages+self.persistence_manager.swap_system_message(new_system_message)- new_messages = [new_system_message] + self.messages[1:] # swap index 0 (system)+ new_messages = [new_system_message] + self._messages[1:] # swap index 0 (system)self._messages = new_messagesdef _get_ai_reply(self,- message_sequence,- function_call="auto",- first_message=False, # hint- ):+ message_sequence: List[dict],+ function_call: str = "auto",+ first_message: bool = False, # hint+ ) -> chat_completion_response.ChatCompletionResponse:"""Get response from LLM API"""try:response = create(- agent_state=self.config,+ agent_state=self.agent_state,messages=message_sequence,functions=self.functions,functions_python=self.functions_python,@@ -316,7 +348,7 @@ class Agent(object):raise Exception("Finish reason was length (maximum context length)")# catches for soft errors- if response.choices[0].finish_reason not in ["stop", "function_call"]:+ if response.choices[0].finish_reason not in ["stop", "function_call", "tool_calls"]:raise Exception(f"API call finish with bad finish reason: {response}")# unpack with response.choices[0].message.content@@ -324,27 +356,54 @@ class Agent(object):except Exception as e:raise e- def _handle_ai_response(self, response_message):+ def _handle_ai_response(+ self, response_message: chat_completion_response.Message, override_tool_call_id: bool = True+ ) -> Tuple[List[Message], bool, bool]:"""Handles parsing and function execution"""+messages = [] # append these to the history when done# Step 2: check if LLM wanted to call a function- if response_message.get("function_call"):+ if response_message.function_call or (response_message.tool_calls is not None and len(response_message.tool_calls) > 0):+ if response_message.function_call:+ raise DeprecationWarning(response_message)+ if response_message.tool_calls is not None and len(response_message.tool_calls) > 1:+ raise NotImplementedError(f">1 tool call not supported")+# The content if then internal monologue, not chatself.interface.internal_monologue(response_message.content)# generate UUID for tool call- tool_call_id = str(uuid.uuid4()) # needs to be a string for JSON- response_message["tool_call_id"] = tool_call_id+ if override_tool_call_id or response_message.function_call:+ tool_call_id = get_tool_call_id() # needs to be a string for JSON+ response_message.tool_calls[0].id = tool_call_id+ else:+ tool_call_id = response_message.tool_calls[0].id+ assert tool_call_id is not None # should be defined++ # only necessary to add the tool_cal_id to a function call (antipattern)+ # response_message_dict = response_message.model_dump()+ # response_message_dict["tool_call_id"] = tool_call_id+# role: assistant (requesting tool call, set tool call ID)- messages.append(response_message) # extend conversation with assistant's reply+ messages.append(+ Message.dict_to_message(+ agent_id=self.agent_state.id,+ user_id=self.agent_state.user_id,+ model=self.model,+ openai_message_dict=response_message.model_dump(),+ )+ ) # extend conversation with assistant's replyprintd(f"Function call message: {messages[-1]}")# Step 3: call the function# Note: the JSON response may not always be valid; be sure to handle errors# Failure case 1: function name is wrong- function_name = response_message["function_call"]["name"]+ function_call = (+ response_message.function_call if response_message.function_call is not None else response_message.tool_calls[0].function+ )+ function_name = function_call.nameprintd(f"Request to call function {function_name} with tool_call_id: {tool_call_id}")try:function_to_call = self.functions_python[function_name]@@ -352,24 +411,40 @@ class Agent(object):error_msg = f"No function named {function_name}"function_response = package_function_response(False, error_msg)messages.append(- {"role": "function", "name": function_name, "content": function_response, "tool_call_id": tool_call_id}+ Message.dict_to_message(+ agent_id=self.agent_state.id,+ user_id=self.agent_state.user_id,+ model=self.model,+ openai_message_dict={+ "role": "tool",+ "name": function_name,+ "content": function_response,+ "tool_call_id": tool_call_id,+ },+ )) # extend conversation with function responseself.interface.function_message(f"Error: {error_msg}")return messages, None, True # force a heartbeat to allow agent to handle error# Failure case 2: function name is OK, but function args are bad JSONtry:- raw_function_args = response_message["function_call"]["arguments"]+ raw_function_args = function_call.argumentsfunction_args = parse_json(raw_function_args)except Exception as e:error_msg = f"Error parsing JSON for function '{function_name}' arguments: {raw_function_args}"function_response = package_function_response(False, error_msg)messages.append(- {- "role": "function",- "name": function_name,- "content": function_response,- }+ Message.dict_to_message(+ agent_id=self.agent_state.id,+ user_id=self.agent_state.user_id,+ model=self.model,+ openai_message_dict={+ "role": "tool",+ "name": function_name,+ "content": function_response,+ "tool_call_id": tool_call_id,+ },+ )) # extend conversation with function responseself.interface.function_message(f"Error: {error_msg}")return messages, None, True # force a heartbeat to allow agent to handle error@@ -408,7 +483,17 @@ class Agent(object):printd(error_msg_user)function_response = package_function_response(False, error_msg)messages.append(- {"role": "function", "name": function_name, "content": function_response, "tool_call_id": tool_call_id}+ Message.dict_to_message(+ agent_id=self.agent_state.id,+ user_id=self.agent_state.user_id,+ model=self.model,+ openai_message_dict={+ "role": "tool",+ "name": function_name,+ "content": function_response,+ "tool_call_id": tool_call_id,+ },+ )) # extend conversation with function responseself.interface.function_message(f"Error: {error_msg}")return messages, None, True # force a heartbeat to allow agent to handle error@@ -417,13 +502,30 @@ class Agent(object):# Step 4: send the info on the function call and function response to GPTself.interface.function_message(f"Success: {function_response_string}")messages.append(- {"role": "function", "name": function_name, "content": function_response, "tool_call_id": tool_call_id}+ Message.dict_to_message(+ agent_id=self.agent_state.id,+ user_id=self.agent_state.user_id,+ model=self.model,+ openai_message_dict={+ "role": "tool",+ "name": function_name,+ "content": function_response,+ "tool_call_id": tool_call_id,+ },+ )) # extend conversation with function responseelse:# Standard non-function replyself.interface.internal_monologue(response_message.content)- messages.append(response_message) # extend conversation with assistant's reply+ messages.append(+ Message.dict_to_message(+ agent_id=self.agent_state.id,+ user_id=self.agent_state.user_id,+ model=self.model,+ openai_message_dict=response_message.model_dump(),+ )+ ) # extend conversation with assistant's replyheartbeat_request = Nonefunction_failed = None@@ -485,37 +587,44 @@ class Agent(object):# Add the extra metadata to the assistant response# (e.g. enough metadata to enable recreating the API call)- assert "api_response" not in all_response_messages[0]- all_response_messages[0]["api_response"] = response_message_copy- assert "api_args" not in all_response_messages[0]- all_response_messages[0]["api_args"] = {- "model": self.model,- "messages": input_message_sequence,- "functions": self.functions,- }+ # assert "api_response" not in all_response_messages[0]+ # all_response_messages[0]["api_response"] = response_message_copy+ # assert "api_args" not in all_response_messages[0]+ # all_response_messages[0]["api_args"] = {+ # "model": self.model,+ # "messages": input_message_sequence,+ # "functions": self.functions,+ # }# Step 4: extend the message historyif user_message is not None:- all_new_messages = [packed_user_message] + all_response_messages+ all_new_messages = [+ Message.dict_to_message(+ agent_id=self.agent_state.id,+ user_id=self.agent_state.user_id,+ model=self.model,+ openai_message_dict=packed_user_message,+ )+ ] + all_response_messageselse:all_new_messages = all_response_messages# Check the memory pressure and potentially issue a memory pressure warning- current_total_tokens = response["usage"]["total_tokens"]+ current_total_tokens = response.usage.total_tokensactive_memory_warning = False# We can't do summarize logic properly if context_window is undefined- if self.config.llm_config.context_window is None:+ if self.agent_state.llm_config.context_window is None:# Fallback if for some reason context_window is missing, just set to the defaultprint(f"{CLI_WARNING_PREFIX}could not find context_window in config, setting to default {LLM_MAX_TOKENS['DEFAULT']}")- print(f"{self.config}")- self.config.llm_config.context_window = (+ print(f"{self.agent_state}")+ self.agent_state.llm_config.context_window = (str(LLM_MAX_TOKENS[self.model])if (self.model is not None and self.model in LLM_MAX_TOKENS)else str(LLM_MAX_TOKENS["DEFAULT"]))- if current_total_tokens > MESSAGE_SUMMARY_WARNING_FRAC * int(self.config.llm_config.context_window):+ if current_total_tokens > MESSAGE_SUMMARY_WARNING_FRAC * int(self.agent_state.llm_config.context_window):printd(- f"{CLI_WARNING_PREFIX}last response total_tokens ({current_total_tokens}) > {MESSAGE_SUMMARY_WARNING_FRAC * int(self.config.llm_config.context_window)}"+ f"{CLI_WARNING_PREFIX}last response total_tokens ({current_total_tokens}) > {MESSAGE_SUMMARY_WARNING_FRAC * int(self.agent_state.llm_config.context_window)}")# Only deliver the alert if we haven't already (this period)if not self.agent_alerted_about_memory_pressure:@@ -523,11 +632,12 @@ class Agent(object):self.agent_alerted_about_memory_pressure = True # it's up to the outer loop to handle thiselse:printd(- f"last response total_tokens ({current_total_tokens}) < {MESSAGE_SUMMARY_WARNING_FRAC * int(self.config.llm_config.context_window)}"+ f"last response total_tokens ({current_total_tokens}) < {MESSAGE_SUMMARY_WARNING_FRAC * int(self.agent_state.llm_config.context_window)}")self._append_to_messages(all_new_messages)- return all_new_messages, heartbeat_request, function_failed, active_memory_warning+ all_new_messages_dicts = [msg.to_openai_dict() for msg in all_new_messages]+ return all_new_messages_dicts, heartbeat_request, function_failed, active_memory_warningexcept Exception as e:printd(f"step() failed\nuser_message = {user_message}\nerror = {e}")@@ -602,11 +712,11 @@ class Agent(object):printd(f"Attempting to summarize {len(message_sequence_to_summarize)} messages [1:{cutoff}] of {len(self.messages)}")# We can't do summarize logic properly if context_window is undefined- if self.config.llm_config.context_window is None:+ if self.agent_state.llm_config.context_window is None:# Fallback if for some reason context_window is missing, just set to the defaultprint(f"{CLI_WARNING_PREFIX}could not find context_window in config, setting to default {LLM_MAX_TOKENS['DEFAULT']}")- print(f"{self.config}")- self.config.llm_config.context_window = (+ print(f"{self.agent_state}")+ self.agent_state.llm_config.context_window = (str(LLM_MAX_TOKENS[self.model])if (self.model is not None and self.model in LLM_MAX_TOKENS)else str(LLM_MAX_TOKENS["DEFAULT"])@@ -625,7 +735,16 @@ class Agent(object):prior_len = len(self.messages)self._trim_messages(cutoff)packed_summary_message = {"role": "user", "content": summary_message}- self._prepend_to_messages([packed_summary_message])+ self._prepend_to_messages(+ [+ Message.dict_to_message(+ agent_id=self.agent_state.id,+ user_id=self.agent_state.user_id,+ model=self.model,+ openai_message_dict=packed_summary_message,+ )+ ]+ )# reset alertself.agent_alerted_about_memory_pressure = False@@ -658,32 +777,36 @@ class Agent(object):printd(f"Rebuilding system with new memory...\nDiff:\n{diff}")# Swap the system message out- self._swap_system_message(new_system_message)-- def to_agent_state(self):- # The state may have change since the last time we wrote it- updated_state = {- "persona": self.memory.persona,- "human": self.memory.human,- "system": self.system,- "functions": self.functions,- "messages": self.messages,- }-- agent_state = AgentState(- name=self.config.name,- user_id=self.config.user_id,- persona=self.config.persona,- human=self.config.human,- llm_config=self.config.llm_config,- embedding_config=self.config.embedding_config,- preset=self.config.preset,- id=self.config.id,- created_at=self.config.created_at,- state=updated_state,+ self._swap_system_message(+ Message.dict_to_message(+ agent_id=self.agent_state.id, user_id=self.agent_state.user_id, model=self.model, openai_message_dict=new_system_message+ ))- return agent_state+ # def to_agent_state(self) -> AgentState:+ # # The state may have change since the last time we wrote it+ # updated_state = {+ # "persona": self.memory.persona,+ # "human": self.memory.human,+ # "system": self.system,+ # "functions": self.functions,+ # "messages": [str(msg.id) for msg in self._messages],+ # }++ # agent_state = AgentState(+ # name=self.agent_state.name,+ # user_id=self.agent_state.user_id,+ # persona=self.agent_state.persona,+ # human=self.agent_state.human,+ # llm_config=self.agent_state.llm_config,+ # embedding_config=self.agent_state.embedding_config,+ # preset=self.agent_state.preset,+ # id=self.agent_state.id,+ # created_at=self.agent_state.created_at,+ # state=updated_state,+ # )++ # return agent_statedef add_function(self, function_name: str) -> str:if function_name in self.functions_python.keys():@@ -699,7 +822,8 @@ class Agent(object):self.functions_python[function_name] = available_functions[function_name]["python_function"]msg = f"Added function {function_name}"- self.save()+ # self.save()+ self.update_state()printd(msg)return msg@@ -721,21 +845,48 @@ class Agent(object):self.functions_python.pop(function_name)msg = f"Removed function {function_name}"- self.save()+ # self.save()+ self.update_state()printd(msg)return msg- def save(self):- """Save agent state locally"""+ # def save(self):+ # """Save agent state locally"""- agent_state = self.to_agent_state()- # TODO(swooders) does this make sense?- # without this, even after Agent.__init__, agent.config.state["messages"] will be None- self.config = agent_state+ # new_agent_state = self.to_agent_state()- # Check if we need to create the agent- if not self.ms.get_agent(agent_id=agent_state.id, user_id=agent_state.user_id, agent_name=agent_state.name):- self.ms.create_agent(agent=agent_state)- else:- # Otherwise, we should update the agent- self.ms.update_agent(agent=agent_state)+ # # without this, even after Agent.__init__, agent.config.state["messages"] will be None+ # self.agent_state = new_agent_state++ # # Check if we need to create the agent+ # if not self.ms.get_agent(agent_id=new_agent_state.id, user_id=new_agent_state.user_id, agent_name=new_agent_state.name):+ # # print(f"Agent.save {new_agent_state.id} :: agent does not exist, creating...")+ # self.ms.create_agent(agent=new_agent_state)+ # # Otherwise, we should update the agent+ # else:+ # # print(f"Agent.save {new_agent_state.id} :: agent already exists, updating...")+ # print(f"Agent.save {new_agent_state.id} :: preupdate:\n\tmessages={new_agent_state.state['messages']}")+ # self.ms.update_agent(agent=new_agent_state)++ def update_state(self):+ updated_state = {+ "persona": self.memory.persona,+ "human": self.memory.human,+ "system": self.system,+ "functions": self.functions,+ "messages": [str(msg.id) for msg in self._messages],+ }++ self.agent_state = AgentState(+ name=self.agent_state.name,+ user_id=self.agent_state.user_id,+ persona=self.agent_state.persona,+ human=self.agent_state.human,+ llm_config=self.agent_state.llm_config,+ embedding_config=self.agent_state.embedding_config,+ preset=self.agent_state.preset,+ id=self.agent_state.id,+ created_at=self.agent_state.created_at,+ state=updated_state,+ )+ return self.agent_statediff --git a/memgpt/agent_store/db.py b/memgpt/agent_store/db.pyindex a297531bf..0c9c078fd 100644--- a/memgpt/agent_store/db.py+++ b/memgpt/agent_store/db.py@@ -113,6 +113,7 @@ def get_db_model(dialect="postgresql",):# get embedding dimention info+ # TODO: Need to remove this and just pass in AgentState/User insteadms = MetadataStore(config)if agent_id and ms.get_agent(agent_id):agent = ms.get_agent(agent_id)diff --git a/memgpt/cli/cli.py b/memgpt/cli/cli.pyindex 121af0124..88f620c99 100644--- a/memgpt/cli/cli.py+++ b/memgpt/cli/cli.py@@ -587,7 +587,7 @@ def run(from memgpt.main import run_agent_loopprint() # extra space- run_agent_loop(memgpt_agent, config, first, no_verify) # TODO: add back no_verify+ run_agent_loop(memgpt_agent, config, first, ms, no_verify) # TODO: add back no_verifydef attach(diff --git a/memgpt/cli/cli_config.py b/memgpt/cli/cli_config.pyindex 6f4321b3b..4f0792f8a 100644--- a/memgpt/cli/cli_config.py+++ b/memgpt/cli/cli_config.py@@ -71,8 +71,8 @@ def configure_llm_endpoint(config: MemGPTConfig):if config.openai_key is None:# allow key to get pulled from env varsopenai_api_key = os.getenv("OPENAI_API_KEY", None)+ # if we still can't find it, ask for it as inputif openai_api_key is None:- # if we still can't find it, ask for it as inputwhile openai_api_key is None or len(openai_api_key) == 0:# Ask for API key as inputopenai_api_key = questionary.text(@@ -87,7 +87,7 @@ def configure_llm_endpoint(config: MemGPTConfig):openai_api_key = Nonedefault_input = shorten_key_middle(config.openai_key) if config.openai_key.startswith("sk-") else config.openai_keyopenai_api_key = questionary.text(- "Enter your OpenAI API key (hit enter to use existing key):",+ "Enter your OpenAI API key (starts with 'sk-', see https://platform.openai.com/api-keys):",default=default_input,).ask()if openai_api_key is None:@@ -542,6 +542,9 @@ def configure():typer.secho(str(e), fg=typer.colors.RED)return+ # openai key might have gotten added along the way+ openai_key = config.openai_key if config.openai_key is not None else openai_key+# TODO: remove most of this (deplicated with User table)config = MemGPTConfig(# model configsdiff --git a/memgpt/client/client.py b/memgpt/client/client.pyindex 2abde109f..1802b3098 100644--- a/memgpt/client/client.py+++ b/memgpt/client/client.py@@ -1,6 +1,6 @@import osimport uuid-from typing import Dict, List, Union+from typing import Dict, List, Union, Optionalfrom memgpt.data_types import AgentStatefrom memgpt.cli.cli import QuickstartChoice@@ -75,27 +75,32 @@ class Client(object):self.interface.clear()return self.server.list_agents(user_id=self.user_id)- def agent_exists(self, agent_id: str) -> bool:+ def agent_exists(self, agent_id: Optional[str] = None, agent_name: Optional[str] = None) -> bool:+ if not (agent_id or agent_name):+ raise ValueError(f"Either agent_id or agent_name must be provided")+ if agent_id and agent_name:+ raise ValueError(f"Only one of agent_id or agent_name can be provided")existing = self.list_agents()- return agent_id in [agent["name"] for agent in existing["agents"]]+ if agent_id:+ return agent_id in [agent["id"] for agent in existing["agents"]]+ else:+ return agent_name in [agent["name"] for agent in existing["agents"]]def create_agent(self,agent_config: dict,- # persistence_manager: Union[PersistenceManager, None] = None,- throw_if_exists: bool = True,) -> AgentState:if isinstance(agent_config, dict):agent_name = agent_config.get("name")else:raise TypeError(f"agent_config must be of type dict")- if not self.agent_exists(agent_id=agent_name):- self.interface.clear()- agent_state = self.server.create_agent(user_id=self.user_id, agent_config=agent_config)- return agent_state- else:- raise ValueError(f"Agent {agent_name} already exists")+ if "name" in agent_config and self.agent_exists(agent_name=agent_config["name"]):+ raise ValueError(f"Agent with name {agent_config['name']} already exists (user_id={self.user_id})")++ self.interface.clear()+ agent_state = self.server.create_agent(user_id=self.user_id, agent_config=agent_config)+ return agent_statedef get_agent_config(self, agent_id: str) -> Dict:self.interface.clear()diff --git a/memgpt/data_types.py b/memgpt/data_types.pyindex 54d085853..b4b71eb1b 100644--- a/memgpt/data_types.py+++ b/memgpt/data_types.py@@ -7,6 +7,7 @@ import numpy as npfrom memgpt.constants import DEFAULT_HUMAN, DEFAULT_MEMGPT_MODEL, DEFAULT_PERSONA, DEFAULT_PRESET, LLM_MAX_TOKENSfrom memgpt.utils import get_local_time, format_datetime+from memgpt.models import chat_completion_responseclass Record:@@ -29,6 +30,7 @@ class ToolCall(object):self,id: str,# TODO should we include this? it's fixed to 'function' only (for now) in OAI schema+ # NOTE: called ToolCall.type in official OpenAI schematool_call_type: str, # only 'function' is supported# function: { 'name': ..., 'arguments': ...}function: Dict[str, str],@@ -37,6 +39,13 @@ class ToolCall(object):self.tool_call_type = tool_call_typeself.function = function+ def to_dict(self):+ return {+ "id": self.id,+ "type": self.tool_call_type,+ "function": self.function,+ }+class Message(Record):"""Representation of a message sent.@@ -53,7 +62,7 @@ class Message(Record):agent_id: uuid.UUID,role: str,text: str,- model: Optional[str], # model used to make function call+ model: Optional[str] = None, # model used to make function callname: Optional[str] = None, # optional participant namecreated_at: Optional[str] = None,tool_calls: Optional[List[ToolCall]] = None, # list of tool calls requested@@ -66,9 +75,10 @@ class Message(Record):self.agent_id = agent_idself.text = textself.model = model # model name (e.g. gpt-4)- self.created_at = created_at+ self.created_at = datetime.now().astimezone() if created_at is None else created_at# openai info+ assert role in ["system", "assistant", "user", "tool"]self.role = role # role (agent/user/function)self.name = name@@ -76,10 +86,15 @@ class Message(Record):# if role == "assistant", this MAY be specified# if role != "assistant", this must be null+ assert tool_calls is None or isinstance(tool_calls, list)self.tool_calls = tool_calls# if role == "tool", then this must be specified# if role != "tool", this must be null+ if role == "tool":+ assert tool_call_id is not None+ else:+ assert tool_call_id is Noneself.tool_call_id = tool_call_id# embedding (optional)@@ -88,6 +103,148 @@ class Message(Record):# def __repr__(self):# pass+ @staticmethod+ def dict_to_message(+ user_id: uuid.UUID,+ agent_id: uuid.UUID,+ openai_message_dict: dict,+ model: Optional[str] = None, # model used to make function call+ allow_functions_style: bool = False, # allow deprecated functions style?+ ):+ """Convert a ChatCompletion message object into a Message object (synced to DB)"""++ # If we're going from deprecated function form+ if openai_message_dict["role"] == "function":+ if not allow_functions_style:+ raise DeprecationWarning(openai_message_dict)+ assert "tool_call_id" in openai_message_dict, openai_message_dict++ # Convert from 'function' response to a 'tool' response+ # NOTE: this does not conventionally include a tool_call_id, it's on the caster to provide it+ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role="tool", # NOTE+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=openai_message_dict["tool_calls"] if "tool_calls" in openai_message_dict else None,+ tool_call_id=openai_message_dict["tool_call_id"] if "tool_call_id" in openai_message_dict else None,+ )++ elif "function_call" in openai_message_dict and openai_message_dict["function_call"] is not None:+ if not allow_functions_style:+ raise DeprecationWarning(openai_message_dict)+ assert openai_message_dict["role"] == "assistant", openai_message_dict+ assert "tool_call_id" in openai_message_dict, openai_message_dict++ # Convert a function_call (from an assistant message) into a tool_call+ # NOTE: this does not conventionally include a tool_call_id (ToolCall.id), it's on the caster to provide it+ tool_calls = [+ ToolCall(+ id=openai_message_dict["tool_call_id"], # NOTE: unconventional source, not to spec+ tool_call_type="function",+ function={+ "name": openai_message_dict["function_call"]["name"],+ "arguments": openai_message_dict["function_call"]["arguments"],+ },+ )+ ]++ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role=openai_message_dict["role"],+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=tool_calls,+ tool_call_id=None, # NOTE: None, since this field is only non-null for role=='tool'+ )++ else:+ # Basic sanity check+ if openai_message_dict["role"] == "tool":+ assert "tool_call_id" in openai_message_dict and openai_message_dict["tool_call_id"] is not None, openai_message_dict+ else:+ if "tool_call_id" in openai_message_dict:+ assert openai_message_dict["tool_call_id"] is None, openai_message_dict++ if "tool_calls" in openai_message_dict:+ assert openai_message_dict["role"] == "assistant", openai_message_dict++ tool_calls = [+ ToolCall(id=tool_call["id"], tool_call_type=tool_call["type"], function=tool_call["function"])+ for tool_call in openai_message_dict["tool_calls"]+ ]+ else:+ tool_calls = None++ # If we're going from tool-call style+ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role=openai_message_dict["role"],+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=tool_calls,+ tool_call_id=openai_message_dict["tool_call_id"] if "tool_call_id" in openai_message_dict else None,+ )++ def to_openai_dict(self):+ """Go from Message class to ChatCompletion message object"""++ # TODO change to pydantic casting, eg `return SystemMessageModel(self)`++ if self.role == "system":+ assert all([v is not None for v in [self.text, self.role]]), vars(self)+ openai_message = {+ "content": self.text,+ "role": self.role,+ }+ # Optional field, do not include if null+ if self.name is not None:+ openai_message["name"] = self.name++ elif self.role == "user":+ assert all([v is not None for v in [self.text, self.role]]), vars(self)+ openai_message = {+ "content": self.text,+ "role": self.role,+ }+ # Optional field, do not include if null+ if self.name is not None:+ openai_message["name"] = self.name++ elif self.role == "assistant":+ assert all([v is not None for v in [self.text, self.role]]), vars(self)+ openai_message = {+ "content": self.text,+ "role": self.role,+ }+ # Optional fields, do not include if null+ if self.name is not None:+ openai_message["name"] = self.name+ if self.tool_calls is not None:+ openai_message["tool_calls"] = [tool_call.to_dict() for tool_call in self.tool_calls]++ elif self.role == "tool":+ assert all([v is not None for v in [self.text, self.role, self.tool_call_id]]), vars(self)+ openai_message = {+ "content": self.text,+ "role": self.role,+ "tool_call_id": self.tool_call_id,+ }++ else:+ raise ValueError(self.role)++ return openai_message+class Document(Record):"""A document represent a document loaded into MemGPT, which is broken down into passages."""@@ -237,6 +394,7 @@ class User:def __init__(self,+ # name: str,id: Optional[uuid.UUID] = None,default_preset=DEFAULT_PRESET,default_persona=DEFAULT_PERSONA,diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.pyindex db9c6de72..2986ab473 100644--- a/memgpt/local_llm/chat_completion_proxy.py+++ b/memgpt/local_llm/chat_completion_proxy.py@@ -1,8 +1,10 @@"""Key idea: create drop-in replacement for agent's ChatCompletion call that runs on an OpenLLM backend"""import os+from datetime import datetimeimport requestsimport json+import uuidfrom box import Box@@ -21,6 +23,8 @@ from memgpt.local_llm.function_parser import patch_functionfrom memgpt.prompts.gpt_summarize import SYSTEM as SUMMARIZE_SYSTEM_MESSAGEfrom memgpt.errors import LocalLLMConnectionError, LocalLLMErrorfrom memgpt.constants import CLI_WARNING_PREFIX, JSON_ENSURE_ASCII+from memgpt.models.chat_completion_response import ChatCompletionResponse, Choice, Message, ToolCall, UsageStatistics+from memgpt.utils import get_tool_call_idhas_shown_warning = Falsegrammar_supported_backends = ["koboldcpp", "llamacpp", "webui", "webui-legacy"]@@ -44,7 +48,7 @@ def get_chat_completion(# extra hints to allow for additional prompt formatting hacks# TODO this could alternatively be supported via passing function_call="send_message" into the wrapperfirst_message=False,-):+) -> ChatCompletionResponse:from memgpt.utils import printdassert context_window is not None, "Local LLM calls need the context length to be explicitly set"@@ -196,23 +200,28 @@ def get_chat_completion(usage["total_tokens"] = usage["prompt_tokens"] + usage["completion_tokens"]# unpack with response.choices[0].message.content- response = Box(- {- "model": model,- "choices": [- {- "message": chat_completion_result,- # TODO vary 'finish_reason' based on backend response- # NOTE if we got this far (parsing worked), then it's probably OK to treat this as a stop- "finish_reason": "stop",- }- ],- "usage": {- "prompt_tokens": usage["prompt_tokens"],- "completion_tokens": usage["completion_tokens"],- "total_tokens": usage["total_tokens"],- },- }+ response = ChatCompletionResponse(+ id=str(uuid.uuid4()), # TODO something better?+ choices=[+ Choice(+ finish_reason="stop",+ index=0,+ message=Message(+ role=chat_completion_result["role"],+ content=chat_completion_result["content"],+ tool_calls=[ToolCall(id=get_tool_call_id(), type="function", function=chat_completion_result["function_call"])]+ if "function_call" in chat_completion_result+ else [],+ ),+ )+ ],+ created=datetime.now().astimezone(),+ model=model,+ # "This fingerprint represents the backend configuration that the model runs with."+ # system_fingerprint=user if user is not None else "null",+ system_fingerprint=None,+ object="chat.completion",+ usage=UsageStatistics(**usage),)printd(response)return responsediff --git a/memgpt/local_llm/llm_chat_completion_wrappers/chatml.py b/memgpt/local_llm/llm_chat_completion_wrappers/chatml.pyindex fdacde9b5..9915a5dff 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/chatml.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/chatml.py@@ -140,6 +140,9 @@ class ChatMLInnerMonologueWrapper(LLMChatCompletionWrapper):inner_thoughts = message["content"]if "function_call" in message and message["function_call"]:prompt += f"\n{self._compile_function_call(message['function_call'], inner_thoughts=inner_thoughts)}"+ elif "tool_calls" in message and message["tool_calls"]:+ for tool_call in message["tool_calls"]:+ prompt += f"\n{self._compile_function_call(tool_call['function'], inner_thoughts=inner_thoughts)}"else:# TODO should we format this into JSON somehow?prompt += inner_thoughts@@ -194,7 +197,7 @@ class ChatMLInnerMonologueWrapper(LLMChatCompletionWrapper):# Last are the user/assistant messagesfor message in messages[1:]:- assert message["role"] in ["user", "assistant", "function"], message+ assert message["role"] in ["user", "assistant", "tool"], messageif message["role"] == "user":# Support for AutoGen naming of agents@@ -217,7 +220,7 @@ class ChatMLInnerMonologueWrapper(LLMChatCompletionWrapper):prompt += f"\n<|im_start|>{role_str}\n{msg_str.strip()}<|im_end|>"- elif message["role"] == "function":+ elif message["role"] == "tool":if self.allow_function_role:role_str = message["role"]msg_str = self._compile_function_response(message)diff --git a/memgpt/main.py b/memgpt/main.pyindex 207c60a75..9d9f41e51 100644--- a/memgpt/main.py+++ b/memgpt/main.py@@ -28,7 +28,7 @@ from memgpt.cli.cli import run, attach, version, server, open_folder, quickstartfrom memgpt.cli.cli_config import configure, list, add, deletefrom memgpt.cli.cli_load import app as load_appfrom memgpt.agent_store.storage import StorageConnector, TableType-from memgpt.metadata import MetadataStore+from memgpt.metadata import MetadataStore, save_agentapp = typer.Typer(pretty_exceptions_enable=False)app.command(name="run")(run)@@ -57,7 +57,7 @@ def clear_line(strip_ui=False):sys.stdout.flush()-def run_agent_loop(memgpt_agent, config: MemGPTConfig, first, no_verify=False, cfg=None, strip_ui=False):+def run_agent_loop(memgpt_agent, config: MemGPTConfig, first, ms: MetadataStore, no_verify=False, cfg=None, strip_ui=False):counter = 0user_input = Noneskip_next_user_input = False@@ -101,10 +101,12 @@ def run_agent_loop(memgpt_agent, config: MemGPTConfig, first, no_verify=False, cif user_input.startswith("/"):# updated agent save functionsif user_input.lower() == "/exit":- memgpt_agent.save()+ # memgpt_agent.save()+ save_agent(memgpt_agent, ms)breakelif user_input.lower() == "/save" or user_input.lower() == "/savechat":- memgpt_agent.save()+ # memgpt_agent.save()+ save_agent(memgpt_agent, ms)continueelif user_input.lower() == "/attach":# TODO: check if agent already has itdiff --git a/memgpt/metadata.py b/memgpt/metadata.pyindex 6dd36e902..05e841006 100644--- a/memgpt/metadata.py+++ b/memgpt/metadata.py@@ -5,6 +5,7 @@ from memgpt.constants import DEFAULT_HUMAN, DEFAULT_MEMGPT_MODEL, DEFAULT_PERSONfrom memgpt.utils import get_local_time, enforce_typesfrom memgpt.data_types import AgentState, Source, User, LLMConfig, EmbeddingConfigfrom memgpt.config import MemGPTConfig+from memgpt.agent import Agentfrom sqlalchemy import create_engine, Column, String, BIGINT, select, inspect, text, JSON, BLOB, BINARY, ARRAY, Booleanfrom sqlalchemy import func@@ -93,6 +94,7 @@ class UserModel(Base):__table_args__ = {"extend_existing": True}id = Column(CommonUUID, primary_key=True, default=uuid.uuid4)+ # name = Column(String, nullable=False)default_preset = Column(String)default_persona = Column(String)default_human = Column(String)@@ -115,6 +117,7 @@ class UserModel(Base):def to_record(self) -> User:return User(id=self.id,+ # name=self.namedefault_preset=self.default_preset,default_persona=self.default_persona,default_human=self.default_human,@@ -368,3 +371,15 @@ class MetadataStore:AgentSourceMappingModel.agent_id == agent_id, AgentSourceMappingModel.source_id == source_id).delete()self.session.commit()+++def save_agent(agent: Agent, ms: MetadataStore):+ """Save agent to metadata store"""++ agent.update_state()+ agent_state = agent.agent_state++ if ms.get_agent(agent_id=agent_state.id):+ ms.update_agent(agent_state)+ else:+ ms.create_agent(agent_state)diff --git a/memgpt/migrate.py b/memgpt/migrate.pyindex d0e9ccc92..873ff8ee5 100644--- a/memgpt/migrate.py+++ b/memgpt/migrate.py@@ -19,7 +19,7 @@ from llama_index import ()from memgpt.agent import Agent-from memgpt.data_types import AgentState, User, Passage, Source+from memgpt.data_types import AgentState, User, Passage, Source, Messagefrom memgpt.metadata import MetadataStorefrom memgpt.utils import MEMGPT_DIR, version_less_than, OpenAIBackcompatUnpickler, annotate_message_json_list_with_tool_callsfrom memgpt.config import MemGPTConfig@@ -302,7 +302,7 @@ def migrate_agent(agent_name: str):# We want to keep the timestampfor i in range(len(data["all_messages"])):data["all_messages"][i]["message"] = full_message_history_buffer[i]- messages_to_insert = [agent.persistence_manager.json_to_message(msg) for msg in data["all_messages"]]+ messages_to_insert = [Message.dict_to_message(msg, allow_functions_style=True) for msg in data["all_messages"]]agent.persistence_manager.recall_memory.insert_many(messages_to_insert)# print("Finished migrating recall memory")diff --git a/memgpt/models/chat_completion_response.py b/memgpt/models/chat_completion_response.pynew file mode 100644index 000000000..ebd172d36--- /dev/null+++ b/memgpt/models/chat_completion_response.py@@ -0,0 +1,66 @@+from typing import List, Optional, Union, Dict, Literal+from pydantic import BaseModel, Field+import datetime+++# class ToolCallFunction(BaseModel):+# name: str+# arguments: str+++class FunctionCall(BaseModel):+ arguments: str+ name: str+++class ToolCall(BaseModel):+ id: str+ # "Currently, only function is supported"+ type: Literal["function"] = "function"+ # function: ToolCallFunction+ function: FunctionCall+++class LogProbToken(BaseModel):+ token: str+ logprob: float+ bytes: Optional[List[int]]+++class MessageContentLogProb(BaseModel):+ token: str+ logprob: float+ bytes: Optional[List[int]]+ top_logprobs: Optional[List[LogProbToken]]+++class Message(BaseModel):+ content: Optional[str] = None+ tool_calls: Optional[List[ToolCall]] = None+ role: str+ function_call: Optional[FunctionCall] = None # Deprecated+++class Choice(BaseModel):+ finish_reason: str+ index: int+ message: Message+ logprobs: Optional[Dict[str, Union[List[MessageContentLogProb], None]]] = None+++class UsageStatistics(BaseModel):+ completion_tokens: int+ prompt_tokens: int+ total_tokens: int+++class ChatCompletionResponse(BaseModel):+ id: str+ choices: List[Choice]+ created: datetime.datetime+ model: str+ # system_fingerprint: str # docs say this is mandatory, but in reality API returns None+ system_fingerprint: Optional[str] = None+ # object: str = Field(default="chat.completion")+ object: Literal["chat.completion"] = "chat.completion"+ usage: UsageStatisticsdiff --git a/memgpt/openai_tools.py b/memgpt/openai_tools.pyindex 84234849b..708a3d913 100644--- a/memgpt/openai_tools.py+++ b/memgpt/openai_tools.py@@ -9,6 +9,7 @@ from box import Boxfrom memgpt.local_llm.chat_completion_proxy import get_chat_completionfrom memgpt.constants import CLI_WARNING_PREFIX+from memgpt.models.chat_completion_response import ChatCompletionResponsefrom memgpt.data_types import AgentState@@ -178,6 +179,10 @@ def openai_chat_completions_request(url, api_key, data):data.pop("functions")data.pop("function_call", None) # extra safe, should exist always (default="auto")+ if "tools" in data and data["tools"] is None:+ data.pop("tools")+ data.pop("tool_choice", None) # extra safe, should exist always (default="auto")+printd(f"Sending request to {url}")try:# Example code to trigger a rate limit response:@@ -195,7 +200,7 @@ def openai_chat_completions_request(url, api_key, data):response.raise_for_status() # Raises HTTPError for 4XX/5XX statusresponse = response.json() # convert to dict from stringprintd(f"response.json = {response}")- response = Box(response) # convert to 'dot-dict' style which is the openai python client default+ response = ChatCompletionResponse(**response) # convert to 'dot-dict' style which is the openai python client defaultreturn responseexcept requests.exceptions.HTTPError as http_err:# Handle HTTP errors (e.g., response 4XX, 5XX)@@ -254,6 +259,10 @@ def azure_openai_chat_completions_request(resource_name, deployment_id, api_versdata.pop("functions")data.pop("function_call", None) # extra safe, should exist always (default="auto")+ if "tools" in data and data["tools"] is None:+ data.pop("tools")+ data.pop("tool_choice", None) # extra safe, should exist always (default="auto")+printd(f"Sending request to {url}")try:response = requests.post(url, headers=headers, json=data)@@ -374,46 +383,77 @@ def create(function_call="auto",# hintfirst_message=False,-):+ # use tool naming?+ # if false, will use deprecated 'functions' style+ use_tool_naming=True,+) -> ChatCompletionResponse:"""Return response to chat completion with backoff"""from memgpt.utils import printdprintd(f"Using model {agent_state.llm_config.model_endpoint_type}, endpoint: {agent_state.llm_config.model_endpoint}")++ # openaiif agent_state.llm_config.model_endpoint_type == "openai":- # openai- return openai_chat_completions_request(- url=agent_state.llm_config.model_endpoint, # https://api.openai.com/v1 -> https://api.openai.com/v1/chat/completions- api_key=agent_state.llm_config.openai_key,- data=dict(+ # TODO do the same for Azure?+ if agent_state.llm_config.openai_key is None:+ raise ValueError(f"OpenAI key is missing from MemGPT config file")+ if use_tool_naming:+ data = dict(+ model=agent_state.llm_config.model,+ messages=messages,+ tools=[{"type": "function", "function": f} for f in functions],+ tool_choice=function_call,+ user=str(agent_state.user_id),+ )+ else:+ data = dict(model=agent_state.llm_config.model,messages=messages,functions=functions,function_call=function_call,user=str(agent_state.user_id),- ),+ )+ return openai_chat_completions_request(+ url=agent_state.llm_config.model_endpoint, # https://api.openai.com/v1 -> https://api.openai.com/v1/chat/completions+ api_key=agent_state.llm_config.openai_key,+ data=data,)++ # azureelif agent_state.llm_config.model_endpoint_type == "azure":- # azureazure_deployment = (agent_state.llm_config.azure_deploymentif agent_state.llm_config.azure_deployment is not Noneelse MODEL_TO_AZURE_ENGINE[agent_state.llm_config.model])- return azure_openai_chat_completions_request(- resource_name=agent_state.llm_config.azure_endpoint,- deployment_id=azure_deployment,- api_version=agent_state.llm_config.azure_version,- api_key=agent_state.llm_config.azure_key,- data=dict(+ if use_tool_naming:+ data = dict(+ # NOTE: don't pass model to Azure calls, that is the deployment_id+ # model=agent_config.model,+ messages=messages,+ tools=[{"type": "function", "function": f} for f in functions],+ tool_choice=function_call,+ user=str(agent_state.user_id),+ )+ else:+ data = dict(# NOTE: don't pass model to Azure calls, that is the deployment_id# model=agent_config.model,messages=messages,functions=functions,function_call=function_call,user=str(agent_state.user_id),- ),+ )+ return azure_openai_chat_completions_request(+ resource_name=agent_state.llm_config.azure_endpoint,+ deployment_id=azure_deployment,+ api_version=agent_state.llm_config.azure_version,+ api_key=agent_state.llm_config.azure_key,+ data=data,)- else: # local model++ # local model+ else:return get_chat_completion(model=agent_state.llm_config.model,messages=messages,diff --git a/memgpt/persistence_manager.py b/memgpt/persistence_manager.pyindex 0d6732dd6..fd7d62933 100644--- a/memgpt/persistence_manager.py+++ b/memgpt/persistence_manager.py@@ -1,5 +1,7 @@from abc import ABC, abstractmethodimport pickle+from typing import List+from memgpt.memory import (BaseRecallMemory,EmbeddingArchivalMemory,@@ -69,6 +71,7 @@ class LocalStateManager(PersistenceManager):# printd(f"{self.__class__.__name__}.all_messages.len = {len(self.all_messages)}")printd(f"{self.__class__.__name__}.messages.len = {len(self.messages)}")+ '''def json_to_message(self, message_json) -> Message:"""Convert agent message JSON into Message object"""@@ -100,6 +103,9 @@ class LocalStateManager(PersistenceManager):else:tool_calls = None+ # if message["role"] == "function":+ # message["role"] = "tool"+return Message(user_id=self.agent_state.user_id,agent_id=self.agent_state.id,@@ -112,40 +118,41 @@ class LocalStateManager(PersistenceManager):tool_call_id=message["tool_call_id"] if "tool_call_id" in message else None,id=message["id"] if "id" in message else None,)+ '''def trim_messages(self, num):# printd(f"InMemoryStateManager.trim_messages")self.messages = [self.messages[0]] + self.messages[num:]- def prepend_to_messages(self, added_messages):+ def prepend_to_messages(self, added_messages: List[Message]):# first tag with timestamps- added_messages = [{"timestamp": get_local_time(), "message": msg} for msg in added_messages]+ # added_messages = [{"timestamp": get_local_time(), "message": msg} for msg in added_messages]printd(f"{self.__class__.__name__}.prepend_to_message")self.messages = [self.messages[0]] + added_messages + self.messages[1:]# add to recall memory- self.recall_memory.insert_many([self.json_to_message(m) for m in added_messages])+ self.recall_memory.insert_many([m for m in added_messages])- def append_to_messages(self, added_messages):+ def append_to_messages(self, added_messages: List[Message]):# first tag with timestamps- added_messages = [{"timestamp": get_local_time(), "message": msg} for msg in added_messages]+ # added_messages = [{"timestamp": get_local_time(), "message": msg} for msg in added_messages]printd(f"{self.__class__.__name__}.append_to_messages")self.messages = self.messages + added_messages# add to recall memory- self.recall_memory.insert_many([self.json_to_message(m) for m in added_messages])+ self.recall_memory.insert_many([m for m in added_messages])- def swap_system_message(self, new_system_message):+ def swap_system_message(self, new_system_message: Message):# first tag with timestamps- new_system_message = {"timestamp": get_local_time(), "message": new_system_message}+ # new_system_message = {"timestamp": get_local_time(), "message": new_system_message}printd(f"{self.__class__.__name__}.swap_system_message")self.messages[0] = new_system_message# add to recall memory- self.recall_memory.insert(self.json_to_message(new_system_message))+ self.recall_memory.insert(new_system_message)def update_memory(self, new_memory):printd(f"{self.__class__.__name__}.update_memory")diff --git a/memgpt/server/server.py b/memgpt/server/server.pyindex 64b42cf9f..8fa4cdb60 100644--- a/memgpt/server/server.py+++ b/memgpt/server/server.py@@ -15,12 +15,26 @@ import memgpt.constants as constantsfrom memgpt.cli.cli import attach# from memgpt.agent_store.storage import StorageConnector-from memgpt.metadata import MetadataStore+from memgpt.metadata import MetadataStore, save_agentimport memgpt.presets.presets as presetsimport memgpt.utils as utilsimport memgpt.server.utils as server_utilsfrom memgpt.persistence_manager import PersistenceManager, LocalStateManager-from memgpt.data_types import Source, Passage, Document, User, AgentState, LLMConfig, EmbeddingConfig, Message, ToolCall+from memgpt.data_types import (+ Source,+ Passage,+ Document,+ User,+ AgentState,+ LLMConfig,+ EmbeddingConfig,+ Message,+ ToolCall,+ LLMConfig,+ EmbeddingConfig,+ Message,+ ToolCall,+)# TODO use custom interfacefrom memgpt.interface import CLIInterface # for printing to terminal@@ -117,6 +131,7 @@ class LockingServer(Server):try:# Execute the function# logger.info(f"running function on agent_id = {agent_id}")+ print("USERID", user_id)return func(self, user_id, agent_id, *args, **kwargs)finally:# Release the lock@@ -213,7 +228,8 @@ class SyncServer(LockingServer):"""Saves all the agents that are in the in-memory object store"""for agent_d in self.active_agents:try:- agent_d["agent"].save()+ # agent_d["agent"].save()+ save_agent(agent_d["agent"], self.ms)logger.info(f"Saved agent {agent_d['agent_id']}")except Exception as e:logger.exception(f"Error occurred while trying to save agent {agent_d['agent_id']}:\n{e}")@@ -257,6 +273,7 @@ class SyncServer(LockingServer):if not agent_state:logger.exception(f"agent_id {agent_id} does not exist")raise ValueError(f"agent_id {agent_id} does not exist")+ # print(f"server._load_agent :: load got agent state {agent_id}, messages = {agent_state.state['messages']}")# Instantiate an agent object using the state retrievedlogger.info(f"Creating an agent object")@@ -331,13 +348,14 @@ class SyncServer(LockingServer):# Get the agent object (loaded in memory)memgpt_agent = self._get_or_load_agent(user_id=user_id, agent_id=agent_id)+ # print("AGENT", memgpt_agent.agent_state.id, memgpt_agent.agent_state.user_id)if command.lower() == "exit":# exit not supported on server.pyraise ValueError(command)elif command.lower() == "save" or command.lower() == "savechat":- memgpt_agent.save()+ save_agent(memgpt_agent, self.ms)elif command.lower() == "attach":# Different from CLI, we extract the data source name from the command@@ -355,15 +373,15 @@ class SyncServer(LockingServer):raise ValueError(f"Invalid data source name: {data_source} (options={data_source_options})")else:# attach new data- attach(memgpt_agent.config.name, data_source)+ attach(memgpt_agent.agent_state.name, data_source)# update agent config- memgpt_agent.config.attach_data_source(data_source)+ memgpt_agent.agent_state.attach_data_source(data_source)# reload agent with new data source# TODO: maybe make this less ugly...memgpt_agent.persistence_manager.archival_memory.storage = StorageConnector.get_storage_connector(- agent_config=memgpt_agent.config+ agent_config=memgpt_agent.agent_state)elif command.lower() == "dump" or command.lower().startswith("dump "):@@ -457,6 +475,8 @@ class SyncServer(LockingServer):"""Process an incoming user message and feed it through the MemGPT agent"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Basic input sanitizationif not isinstance(message, str) or len(message) == 0:@@ -478,6 +498,8 @@ class SyncServer(LockingServer):"""Process an incoming system message and feed it through the MemGPT agent"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Basic input sanitizationif not isinstance(message, str) or len(message) == 0:@@ -499,6 +521,8 @@ class SyncServer(LockingServer):"""Run a command on the agent"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# If the input begins with a command prefix, attempt to process it as a commandif command.startswith("/"):@@ -564,22 +588,25 @@ class SyncServer(LockingServer):embedding_config=agent_config["embedding_config"] if "embedding_config" in agent_config else user.default_embedding_config,)# NOTE: you MUST add to the metadata store before creating the agent, otherwise the storage connectors will error on creation+ # TODO: fix this db dependency and removeself.ms.create_agent(agent_state)logger.debug(f"Attempting to create agent from agent_state:\n{agent_state}")try:agent = presets.create_agent_from_preset(agent_state=agent_state, interface=interface)- # TODO: this is a hacky way to get the system prompts injected into agent into the DB- self.ms.update_agent(agent.agent_state)+ # FIXME: this is a hacky way to get the system prompts injected into agent into the DB+ # self.ms.update_agent(agent.agent_state)except Exception as e:logger.exception(e)self.ms.delete_agent(agent_id=agent_state.id)raise+ save_agent(agent, self.ms)+logger.info(f"Created new agent from config: {agent}")- return agent.config+ return agent.agent_statedef delete_agent(self,@@ -588,6 +615,8 @@ class SyncServer(LockingServer):):if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# TODO: Make sure the user owns the agentagent = self.ms.get_agent(agent_id=agent_id, user_id=user_id)@@ -615,9 +644,9 @@ class SyncServer(LockingServer):],}- def get_agent(self, agent_id: uuid.UUID):+ def get_agent(self, user_id: uuid.UUID, agent_id: uuid.UUID):"""Get the agent state"""- return self.ms.get_agent(agent_id=agent_id)+ return self.ms.get_agent(agent_id=agent_id, user_id=user_id)def get_user(self, user_id: uuid.UUID) -> User:"""Get the user"""@@ -627,6 +656,8 @@ class SyncServer(LockingServer):"""Return the memory of an agent (core memory + non-core statistics)"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Get the agent object (loaded in memory)memgpt_agent = self._get_or_load_agent(user_id=user_id, agent_id=agent_id)@@ -650,6 +681,8 @@ class SyncServer(LockingServer):"""Paginated query of all messages in agent message queue"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Get the agent object (loaded in memory)memgpt_agent = self._get_or_load_agent(user_id=user_id, agent_id=agent_id)@@ -657,9 +690,9 @@ class SyncServer(LockingServer):if start < 0 or count < 0:raise ValueError("Start and count values should be non-negative")- if start + count < len(memgpt_agent.messages): # messages can be returned from whats in memory+ if start + count < len(memgpt_agent._messages): # messages can be returned from whats in memory# Reverse the list to make it in reverse chronological order- reversed_messages = memgpt_agent.messages[::-1]+ reversed_messages = memgpt_agent._messages[::-1]# Check if start is within the range of the listif start >= len(reversed_messages):raise IndexError("Start index is out of range")@@ -668,10 +701,8 @@ class SyncServer(LockingServer):end_index = min(start + count, len(reversed_messages))# Slice the list for pagination- paginated_messages = reversed_messages[start:end_index]+ messages = reversed_messages[start:end_index]- # convert to message objects:- messages = [memgpt_agent.persistence_manager.json_to_message(m) for m in paginated_messages]else:# need to access persistence manager for additional messagesdb_iterator = memgpt_agent.persistence_manager.recall_memory.storage.get_all_paginated(page_size=count, offset=start)@@ -691,6 +722,8 @@ class SyncServer(LockingServer):"""Paginated query of all messages in agent archival memory"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Get the agent object (loaded in memory)memgpt_agent = self._get_or_load_agent(user_id=user_id, agent_id=agent_id)@@ -715,6 +748,8 @@ class SyncServer(LockingServer):):if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Get the agent object (loaded in memory)memgpt_agent = self._get_or_load_agent(user_id=user_id, agent_id=agent_id)@@ -738,6 +773,8 @@ class SyncServer(LockingServer):):if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Get the agent object (loaded in memory)memgpt_agent = self._get_or_load_agent(user_id=user_id, agent_id=agent_id)@@ -755,10 +792,12 @@ class SyncServer(LockingServer):"""Return the config of an agent"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Get the agent object (loaded in memory)memgpt_agent = self._get_or_load_agent(user_id=user_id, agent_id=agent_id)- agent_config = vars(memgpt_agent.config)+ agent_config = vars(memgpt_agent.agent_state)return agent_config@@ -781,6 +820,8 @@ class SyncServer(LockingServer):"""Update the agents core memory block, return the new state"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")+ if self.ms.get_agent(agent_id=agent_id, user_id=user_id) is None:+ raise ValueError(f"Agent agent_id={agent_id} does not exist")# Get the agent object (loaded in memory)memgpt_agent = self._get_or_load_agent(user_id=user_id, agent_id=agent_id)diff --git a/memgpt/system.py b/memgpt/system.pyindex c372e7892..bb7d0fd18 100644--- a/memgpt/system.py+++ b/memgpt/system.py@@ -1,3 +1,4 @@+import uuidimport jsonfrom .utils import get_local_time@@ -18,30 +19,64 @@ def get_initial_boot_messages(version="startup"):]elif version == "startup_with_send_message":+ tool_call_id = str(uuid.uuid4())messages = [# first message includes both inner monologue and function call to send_message{"role": "assistant","content": INITIAL_BOOT_MESSAGE_SEND_MESSAGE_THOUGHT,- "function_call": {- "name": "send_message",- "arguments": '{\n "message": "' + f"{INITIAL_BOOT_MESSAGE_SEND_MESSAGE_FIRST_MSG}" + '"\n}',- },+ # "function_call": {+ # "name": "send_message",+ # "arguments": '{\n "message": "' + f"{INITIAL_BOOT_MESSAGE_SEND_MESSAGE_FIRST_MSG}" + '"\n}',+ # },+ "tool_calls": [+ {+ "id": tool_call_id,+ "type": "function",+ "function": {+ "name": "send_message",+ "arguments": '{\n "message": "' + f"{INITIAL_BOOT_MESSAGE_SEND_MESSAGE_FIRST_MSG}" + '"\n}',+ },+ }+ ],},# obligatory function return message- {"role": "function", "name": "send_message", "content": package_function_response(True, None)},+ {+ # "role": "function",+ "role": "tool",+ "name": "send_message", # NOTE: technically not up to spec, this is old functions style+ "content": package_function_response(True, None),+ "tool_call_id": tool_call_id,+ },]elif version == "startup_with_send_message_gpt35":+ tool_call_id = str(uuid.uuid4())messages = [# first message includes both inner monologue and function call to send_message{"role": "assistant","content": "*inner thoughts* Still waiting on the user. Sending a message with function.",- "function_call": {"name": "send_message", "arguments": '{\n "message": "' + f"Hi, is anyone there?" + '"\n}'},+ # "function_call": {"name": "send_message", "arguments": '{\n "message": "' + f"Hi, is anyone there?" + '"\n}'},+ "tool_calls": [+ {+ "id": tool_call_id,+ "type": "function",+ "function": {+ "name": "send_message",+ "arguments": '{\n "message": "' + f"Hi, is anyone there?" + '"\n}',+ },+ }+ ],},# obligatory function return message- {"role": "function", "name": "send_message", "content": package_function_response(True, None)},+ {+ # "role": "function",+ "role": "tool",+ "name": "send_message",+ "content": package_function_response(True, None),+ "tool_call_id": tool_call_id,+ },]else:diff --git a/memgpt/utils.py b/memgpt/utils.pyindex 4f568a403..637755656 100644--- a/memgpt/utils.py+++ b/memgpt/utils.py@@ -32,6 +32,7 @@ from memgpt.constants import (CORE_MEMORY_PERSONA_CHAR_LIMIT,JSON_ENSURE_ASCII,)+from memgpt.models.chat_completion_response import ChatCompletionResponsefrom memgpt.openai_backcompat.openai_object import OpenAIObject@@ -465,6 +466,24 @@ NOUN_BANK = []+def get_tool_call_id() -> str:+ return str(uuid.uuid4())+++def assistant_function_to_tool(assistant_message: dict) -> dict:+ assert "function_call" in assistant_message+ new_msg = copy.deepcopy(assistant_message)+ function_call = new_msg.pop("function_call")+ new_msg["tool_calls"] = [+ {+ "id": get_tool_call_id(),+ "type": "function",+ "function": function_call,+ }+ ]+ return new_msg++def is_optional_type(hint):"""Check if the type hint is an Optional type."""if isinstance(hint, _GenericAlias):@@ -588,30 +607,31 @@ def create_random_username() -> str:return adjective + noun-def verify_first_message_correctness(response, require_send_message=True, require_monologue=False) -> bool:+def verify_first_message_correctness(+ response: ChatCompletionResponse, require_send_message: bool = True, require_monologue: bool = False+) -> bool:"""Can be used to enforce that the first message always uses send_message"""response_message = response.choices[0].message# First message should be a call to send_message with a non-empty content- if require_send_message and not response_message.get("function_call"):+ if require_send_message and not (response_message.function_call or response_message.tool_calls):printd(f"First message didn't include function call: {response_message}")return False- function_call = response_message.get("function_call")- function_name = function_call.get("name") if function_call is not None else ""+ assert not (response_message.function_call and response_message.tool_calls), response_message+ function_call = response_message.function_call if response_message.function_call else response_message.tool_calls[0].function+ function_name = function_call.name if function_call is not None else ""if require_send_message and function_name != "send_message" and function_name != "archival_memory_search":printd(f"First message function call wasn't send_message or archival_memory_search: {response_message}")return False- if require_monologue and (- not response_message.get("content") or response_message["content"] is None or response_message["content"] == ""- ):+ if require_monologue and (not response_message.content or response_message.content is None or response_message.content == ""):printd(f"First message missing internal monologue: {response_message}")return False- if response_message.get("content"):+ if response_message.content:### Extras- monologue = response_message.get("content")+ monologue = response_message.contentdef contains_special_characters(s):special_characters = '(){}[]"'diff --git a/tests/test_agent_function_update.py b/tests/test_agent_function_update.pyindex c50ee4948..69a51cb3e 100644--- a/tests/test_agent_function_update.py+++ b/tests/test_agent_function_update.py@@ -9,6 +9,8 @@ from memgpt.config import MemGPTConfigfrom memgpt import constantsimport memgpt.functions.function_sets.base as base_functionsfrom memgpt.functions.functions import USER_FUNCTIONS_DIR+from memgpt.utils import assistant_function_to_tool+from memgpt.models import chat_completion_responsefrom tests.utils import wipe_config@@ -60,20 +62,21 @@ def hello_world_function():@pytest.fixture(scope="module")def ai_function_call():- class AiFunctionCall(UserDict):- def content(self):- return self.data["content"]-- return AiFunctionCall(- {- "content": "I will now call hello world",- "function_call": {- "name": "hello_world",- "arguments": json.dumps({}),- },- }+ return chat_completion_response.Message(+ **assistant_function_to_tool(+ {+ "role": "assistant",+ "content": "I will now call hello world",+ "function_call": {+ "name": "hello_world",+ "arguments": json.dumps({}),+ },+ }+ ))+ return+def test_add_function_happy(agent, hello_world_function, ai_function_call):agent.add_function("hello_world")@@ -82,7 +85,7 @@ def test_add_function_happy(agent, hello_world_function, ai_function_call):assert "hello_world" in agent.functions_python.keys()msgs, heartbeat_req, function_failed = agent._handle_ai_response(ai_function_call)- content = json.loads(msgs[-1]["content"])+ content = json.loads(msgs[-1].to_openai_dict()["content"])assert content["message"] == "hello, world!"assert content["status"] == "OK"assert not function_faileddiff --git a/tests/test_client.py b/tests/test_client.pyindex f7b369ce2..0ac1a8e99 100644--- a/tests/test_client.py+++ b/tests/test_client.py@@ -6,49 +6,69 @@ from memgpt.config import MemGPTConfigfrom memgpt import constantsfrom memgpt.data_types import LLMConfig, EmbeddingConfigfrom .utils import wipe_config+import uuid-test_agent_name = "test_client_agent"+test_agent_name = f"test_client_{str(uuid.uuid4())}"test_agent_state = Noneclient = Nonetest_agent_state_post_message = None+test_user_id = uuid.uuid4()+++def test_create_user():+ wipe_config()+ global client+ if os.getenv("OPENAI_API_KEY"):+ client = MemGPT(quickstart="openai", user_id=test_user_id)+ else:+ client = MemGPT(quickstart="memgpt_hosted", user_id=test_user_id)++ user = client.server.create_user({"id": test_user_id})+ assert user is not Nonedef test_create_agent():wipe_config()global clientif os.getenv("OPENAI_API_KEY"):- client = MemGPT(quickstart="openai")+ client = MemGPT(quickstart="openai", user_id=test_user_id)else:- client = MemGPT(quickstart="memgpt_hosted")+ client = MemGPT(quickstart="memgpt_hosted", user_id=test_user_id)config = MemGPTConfig.load()# ensure user exists- user_id = uuid.UUID(config.anon_clientid)- if not client.server.get_user(user_id=user_id):- client.server.create_user({"id": user_id})+ if not client.server.get_user(user_id=test_user_id):+ raise ValueError("Run test_create_user first")global test_agent_statetest_agent_state = client.create_agent(agent_config={+ "user_id": test_user_id,"name": test_agent_name,"persona": constants.DEFAULT_PERSONA,"human": constants.DEFAULT_HUMAN,})+ print(f"\n\n[1] CREATED AGENT {test_agent_state.id}!!!\n\tmessages={test_agent_state.state['messages']}")assert test_agent_state is not Nonedef test_user_message():"""Test that we can send a message through the client"""assert client is not None, "Run create_agent test first"+ print(f"\n\n[2] SENDING MESSAGE TO AGENT {test_agent_state.id}!!!\n\tmessages={test_agent_state.state['messages']}")response = client.user_message(agent_id=test_agent_state.id, message="Hello my name is Test, Client Test")assert response is not None and len(response) > 0global test_agent_state_post_message- test_agent_state_post_message = client.server.active_agents[0]["agent"].to_agent_state()+ client.server.active_agents[0]["agent"].update_state()+ test_agent_state_post_message = client.server.active_agents[0]["agent"].agent_state+ print(+ f"[2] MESSAGE SEND SUCCESS!!! AGENT {test_agent_state_post_message.id}\n\tmessages={test_agent_state_post_message.state['messages']}"+ )def test_save_load():@@ -62,20 +82,20 @@ def test_save_load():assert test_agent_state is not None, "Run create_agent test first"assert test_agent_state_post_message is not None, "Run test_user_message test first"- config = MemGPTConfig.load()- user_id = uuid.UUID(config.anon_clientid)-# Create a new client (not thread safe), and load the same agent# The agent state inside should correspond to the initial state pre-messageif os.getenv("OPENAI_API_KEY"):- client2 = MemGPT(quickstart="openai")+ client2 = MemGPT(quickstart="openai", user_id=test_user_id)else:- client2 = MemGPT(quickstart="memgpt_hosted")- client2_agent_obj = client2.server._get_or_load_agent(user_id=user_id, agent_id=test_agent_state.id)- client2_agent_state = client2_agent_obj.to_agent_state()+ client2 = MemGPT(quickstart="memgpt_hosted", user_id=test_user_id)+ print(f"\n\n[3] CREATING CLIENT2, LOADING AGENT {test_agent_state.id}!")+ client2_agent_obj = client2.server._get_or_load_agent(user_id=test_user_id, agent_id=test_agent_state.id)+ client2_agent_state = client2_agent_obj.update_state()+ print(f"[3] LOADED AGENT! AGENT {client2_agent_state.id}\n\tmessages={client2_agent_state.state['messages']}")# assert test_agent_state == client2_agent_state, f"{vars(test_agent_state)}\n{vars(client2_agent_state)}"def check_state_equivalence(state_1, state_2):+ """Helper function that checks the equivalence of two AgentState objects"""assert state_1.keys() == state_2.keys(), f"{state_1.keys()}\n{state_2.keys}"for k, v1 in state_1.items():v2 = state_2[k]@@ -91,15 +111,16 @@ def test_save_load():client.save()if os.getenv("OPENAI_API_KEY"):- client3 = MemGPT(quickstart="openai")+ client3 = MemGPT(quickstart="openai", user_id=test_user_id)else:- client3 = MemGPT(quickstart="memgpt_hosted")- client3_agent_obj = client3.server._get_or_load_agent(user_id=user_id, agent_id=test_agent_state.id)- client3_agent_state = client3_agent_obj.to_agent_state()+ client3 = MemGPT(quickstart="memgpt_hosted", user_id=test_user_id)+ client3_agent_obj = client3.server._get_or_load_agent(user_id=test_user_id, agent_id=test_agent_state.id)+ client3_agent_state = client3_agent_obj.update_state()check_state_equivalence(vars(test_agent_state_post_message), vars(client3_agent_state))if __name__ == "__main__":+ test_create_user()test_create_agent()test_user_message()diff --git a/tests/test_server.py b/tests/test_server.pyindex 6b2a5fef7..b6bf88d04 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -7,7 +7,6 @@ from memgpt.config import MemGPTConfigfrom memgpt.server.server import SyncServerfrom memgpt.data_types import EmbeddingConfig, AgentState, LLMConfig, Message, Passage, Userfrom memgpt.embeddings import embedding_model-from memgpt.metadata import MetadataStorefrom .utils import wipe_config, wipe_memgpt_homediff --git a/tests/test_storage.py b/tests/test_storage.pyindex 3fab73e29..9567aa00a 100644--- a/tests/test_storage.py+++ b/tests/test_storage.py@@ -18,7 +18,7 @@ from datetime import datetime, timedeltatexts = ["This is a test passage", "This is another test passage", "Cinderella wept"]start_date = datetime(2009, 10, 5, 18, 00)dates = [start_date, start_date - timedelta(weeks=1), start_date + timedelta(weeks=1)]-roles = ["user", "agent", "agent"]+roles = ["user", "assistant", "assistant"]agent_1_id = uuid.uuid4()agent_2_id = uuid.uuid4()agent_ids = [agent_1_id, agent_2_id, agent_1_id]