Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: Benchmark Command: `memgpt benchmark` (#816)
starsnatched4c95b7bde371
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 59bf9cbea..eca165c3c 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -644,7 +644,7 @@ class Agent(object):self._append_to_messages(all_new_messages)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_warning+ return all_new_messages_dicts, heartbeat_request, function_failed, active_memory_warning, response.usage.completion_tokensexcept Exception as e:printd(f"step() failed\nuser_message = {user_message}\nerror = {e}")diff --git a/memgpt/autogen/memgpt_agent.py b/memgpt/autogen/memgpt_agent.pyindex 458411dea..01d8b50b3 100644--- a/memgpt/autogen/memgpt_agent.py+++ b/memgpt/autogen/memgpt_agent.py@@ -317,6 +317,7 @@ class MemGPTAgent(ConversableAgent):heartbeat_request,function_failed,token_warning,+ tokens_accumulated,) = self.agent.step(user_message, first_message=False, skip_verify=self.skip_verify)# Skip user inputs if there's a memory warning, function execution failed, or the agent asked for controlif token_warning:diff --git a/memgpt/benchmark/benchmark.py b/memgpt/benchmark/benchmark.pynew file mode 100644index 000000000..c86b55ef8--- /dev/null+++ b/memgpt/benchmark/benchmark.py@@ -0,0 +1,87 @@+# type: ignore++import uuid+import typer+import time++from memgpt import MemGPT+from memgpt.config import MemGPTConfig++# from memgpt.agent import Agent+from memgpt.errors import LLMJSONParsingError+from memgpt.benchmark.constants import TRIES, PERSONA, HUMAN, PROMPTS++app = typer.Typer()+client = MemGPT()+++def send_message(message: str, agent_id, turn: int, fn_type: str, print_msg: bool = False, n_tries: int = TRIES):+ try:+ print_msg = f"\t-> Now running {fn_type}. Progress: {turn}/{n_tries}"+ print(print_msg, end="\r", flush=True)+ response, tokens_accumulated = client.user_message(agent_id=agent_id, message=message, return_token_count=True)++ if turn + 1 == n_tries:+ print(" " * len(print_msg), end="\r", flush=True)++ for r in response:+ if "function_call" in r and fn_type in r["function_call"] and any("assistant_message" in re for re in response):+ return True, r["function_call"], tokens_accumulated++ return False, "No function called.", tokens_accumulated+ except LLMJSONParsingError as e:+ print(f"Error in parsing MemGPT JSON: {e}")+ return False, "Failed to decode valid MemGPT JSON from LLM output.", tokens_accumulated+ except Exception as e:+ print(f"An unexpected error occurred: {e}")+ return False, "An unexpected error occurred.", tokens_accumulated+++def bench(+ print_messages: bool = typer.Option(False, "--messages", help="Print functions calls and messages from the agent."),+ n_tries: int = typer.Option(TRIES, "--n-tries", help="Number of benchmark tries to perform for each function."),+):+ print(f"\nDepending on your hardware, this may take up to 30 minutes. This will also create {n_tries * len(PROMPTS)} new agents.\n")+ config = MemGPTConfig.load()+ print(f"version = {config.memgpt_version}")++ total_score, total_tokens_accumulated, elapsed_time = 0, 0, 0++ for fn_type, message in PROMPTS.items():+ score = 0+ start_time_run = time.time()+ bench_id = uuid.uuid4()++ for i in range(n_tries):+ agent = client.create_agent(agent_config={"name": f"benchmark_{bench_id}_agent_{i}", "persona": PERSONA, "human": HUMAN})++ agent_id = agent.id+ result, msg, tokens_accumulated = send_message(+ message=message, agent_id=agent_id, turn=i, fn_type=fn_type, print_msg=print_messages, n_tries=n_tries+ )++ if print_messages:+ print(f"\t{msg}")++ if result:+ score += 1++ total_tokens_accumulated += tokens_accumulated++ elapsed_time_run = round(time.time() - start_time_run, 2)+ print(f"Score for {fn_type}: {score}/{n_tries}, took {elapsed_time_run} seconds")++ elapsed_time += elapsed_time_run+ total_score += score++ print(f"\nMEMGPT VERSION: {config.memgpt_version}")+ print(f"CONTEXT WINDOW: {config.default_llm_config.context_window}")+ print(f"MODEL WRAPPER: {config.default_llm_config.model_wrapper}")+ print(f"PRESET: {config.preset}")+ print(f"PERSONA: {config.persona}")+ print(f"HUMAN: {config.human}")++ print(+ f"\n\t-> Total score: {total_score}/{len(PROMPTS) * n_tries}, took {elapsed_time} seconds at average of {round(total_tokens_accumulated/elapsed_time, 2)} t/s\n"+ )diff --git a/memgpt/benchmark/constants.py b/memgpt/benchmark/constants.pynew file mode 100644index 000000000..755fdce51--- /dev/null+++ b/memgpt/benchmark/constants.py@@ -0,0 +1,14 @@+# Basic+TRIES = 3+AGENT_NAME = "benchmark"+PERSONA = "sam_pov"+HUMAN = "cs_phd"++# Prompts+PROMPTS = {+ "core_memory_replace": "Hey there, my name is John, what is yours?",+ "core_memory_append": "I want you to remember that I like soccers for later.",+ "conversation_search": "Do you remember when I talked about bananas?",+ "archival_memory_insert": "Can you make sure to remember that I like programming for me so you can look it up later?",+ "archival_memory_search": "Can you retrieve information about the war?",+}diff --git a/memgpt/client/client.py b/memgpt/client/client.pyindex 1802b3098..5a777d126 100644--- a/memgpt/client/client.py+++ b/memgpt/client/client.py@@ -1,6 +1,6 @@import osimport uuid-from typing import Dict, List, Union, Optional+from typing import Dict, List, Union, Optional, Tuplefrom memgpt.data_types import AgentStatefrom memgpt.cli.cli import QuickstartChoice@@ -114,12 +114,15 @@ class Client(object):self.interface.clear()return self.server.update_agent_core_memory(user_id=self.user_id, agent_id=agent_id, new_memory_contents=new_memory_contents)- def user_message(self, agent_id: str, message: str) -> List[Dict]:+ def user_message(self, agent_id: str, message: str, return_token_count: bool = False) -> Union[List[Dict], Tuple[List[Dict], int]]:self.interface.clear()- self.server.user_message(user_id=self.user_id, agent_id=agent_id, message=message)+ tokens_accumulated = self.server.user_message(user_id=self.user_id, agent_id=agent_id, message=message)if self.auto_save:self.save()- return self.interface.to_list()+ if return_token_count:+ return self.interface.to_list(), tokens_accumulated+ else:+ return self.interface.to_list()def run_command(self, agent_id: str, command: str) -> Union[str, None]:self.interface.clear()diff --git a/memgpt/config.py b/memgpt/config.pyindex 6972c6094..cf89726cc 100644--- a/memgpt/config.py+++ b/memgpt/config.py@@ -75,7 +75,7 @@ class MemGPTConfig:persistence_manager_uri: str = None # db URI# version (for backcompat)- memgpt_version: str = None+ memgpt_version: str = memgpt.__version__# user infopolicies_accepted: bool = Falsediff --git a/memgpt/main.py b/memgpt/main.pyindex 4f9c6645c..ea64ab4c9 100644--- a/memgpt/main.py+++ b/memgpt/main.py@@ -30,6 +30,9 @@ from memgpt.cli.cli_load import app as load_appfrom memgpt.agent_store.storage import StorageConnector, TableTypefrom memgpt.metadata import MetadataStore, save_agent+# import benchmark+from memgpt.benchmark.benchmark import bench+app = typer.Typer(pretty_exceptions_enable=False)app.command(name="run")(run)app.command(name="version")(version)@@ -45,6 +48,8 @@ app.command(name="quickstart")(quickstart)app.add_typer(load_app, name="load")# migration commandapp.command(name="migrate")(migrate)+# benchmark command+app.command(name="benchmark")(bench)def clear_line(strip_ui=False):@@ -320,7 +325,7 @@ def run_agent_loop(memgpt_agent, config: MemGPTConfig, first, ms: MetadataStore,skip_next_user_input = Falsedef process_agent_step(user_message, no_verify):- new_messages, heartbeat_request, function_failed, token_warning = memgpt_agent.step(+ new_messages, heartbeat_request, function_failed, token_warning, tokens_accumulated = memgpt_agent.step(user_message, first_message=False, skip_verify=no_verify)diff --git a/memgpt/server/server.py b/memgpt/server/server.pyindex ccee3be51..99c724bd2 100644--- a/memgpt/server/server.py+++ b/memgpt/server/server.py@@ -316,7 +316,7 @@ class SyncServer(LockingServer):memgpt_agent = self._load_agent(user_id=user_id, agent_id=agent_id)return memgpt_agent- def _step(self, user_id: uuid.UUID, agent_id: uuid.UUID, input_message: str) -> None:+ def _step(self, user_id: uuid.UUID, agent_id: uuid.UUID, input_message: str) -> int:"""Send the input message through the agent"""logger.debug(f"Got input message: {input_message}")@@ -331,7 +331,7 @@ class SyncServer(LockingServer):next_input_message = input_messagecounter = 0while True:- new_messages, heartbeat_request, function_failed, token_warning = memgpt_agent.step(+ new_messages, heartbeat_request, function_failed, token_warning, tokens_accumulated = memgpt_agent.step(next_input_message, first_message=False, skip_verify=no_verify)counter += 1@@ -360,6 +360,8 @@ class SyncServer(LockingServer):memgpt_agent.interface.step_yield()logger.debug(f"Finished agent step")+ return tokens_accumulated+def _command(self, user_id: uuid.UUID, agent_id: uuid.UUID, command: str) -> Union[str, None]:"""Process a CLI command"""@@ -510,7 +512,9 @@ class SyncServer(LockingServer):# Package the user message firstpackaged_user_message = system.package_user_message(user_message=message)# Run the agent state forward- self._step(user_id=user_id, agent_id=agent_id, input_message=packaged_user_message)+ tokens_accumulated = self._step(user_id=user_id, agent_id=agent_id, input_message=packaged_user_message)++ return tokens_accumulated@LockingServer.agent_lock_decoratordef system_message(self, user_id: uuid.UUID, agent_id: uuid.UUID, message: str) -> None:diff --git a/tests/test_load_archival.py b/tests/test_load_archival.pyindex 33456bf0c..4173b08d5 100644--- a/tests/test_load_archival.py+++ b/tests/test_load_archival.py@@ -12,6 +12,8 @@ from memgpt.config import MemGPTConfigfrom memgpt.credentials import MemGPTCredentialsfrom memgpt.metadata import MetadataStorefrom memgpt.data_types import User, AgentState, EmbeddingConfig+from memgpt import MemGPT+from .utils import wipe_config@pytest.fixture(autouse=True)@@ -63,24 +65,31 @@ def test_load_directory(metadata_storage_connector, passage_storage_connector, c# create metadata storems = MetadataStore(config)+ user = User(id=uuid.UUID(config.anon_clientid))# embedding configif os.getenv("OPENAI_API_KEY"):+ credentials = MemGPTCredentials(+ openai_key=os.getenv("OPENAI_API_KEY"),+ )+ credentials.save()+ client = MemGPT(quickstart="openai", user_id=user.id)embedding_config = EmbeddingConfig(embedding_endpoint_type="openai",embedding_endpoint="https://api.openai.com/v1",embedding_dim=1536,# openai_key=os.getenv("OPENAI_API_KEY"),)- credentials = MemGPTCredentials(- openai_key=os.getenv("OPENAI_API_KEY"),- )- credentials.save()+else:- embedding_config = EmbeddingConfig(embedding_endpoint_type="local", embedding_endpoint=None, embedding_dim=384)+ client = MemGPT(quickstart="memgpt_hosted", user_id=user.id)+ embedding_config = EmbeddingConfig(+ embedding_endpoint_type="local",+ embedding_endpoint=None,+ embedding_dim=384,+ )# create user and agent- user = User(id=uuid.UUID(config.anon_clientid))agent = AgentState(user_id=user.id,name="test_agent",@@ -170,3 +179,7 @@ def test_load_directory(metadata_storage_connector, passage_storage_connector, cms.delete_user(user.id)ms.delete_agent(agent.id)ms.delete_source(sources[0].id)++ # revert to openai config+ # client = MemGPT(quickstart="openai", user_id=user.id)+ wipe_config()diff --git a/tests/test_migrate.py b/tests/test_migrate.pyindex d7be1727e..acf127376 100644--- a/tests/test_migrate.py+++ b/tests/test_migrate.py@@ -1,8 +1,13 @@import osfrom memgpt.migrate import migrate_all_agents, migrate_all_sources+from memgpt import MemGPT+from memgpt.config import MemGPTConfig+from .utils import wipe_configdef test_migrate_0211():+ wipe_config()+data_dir = "tests/data/memgpt-0.2.11"# os.environ["MEMGPT_CONFIG_PATH"] = os.path.join(data_dir, "config")# print(f"MEMGPT_CONFIG_PATH={os.environ['MEMGPT_CONFIG_PATH']}")