Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add more tool calling support to `LocalClient` (#1465)
Sarah Woodersd7961b68b0a8
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 752d3ba1b..80e584791 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -212,7 +212,10 @@ class Agent(object):env.update(globals())for tool in tools:# WARNING: name may not be consistent?- exec(tool.module, env)+ if tool.module: # execute the whole module+ exec(tool.module, env)+ else:+ exec(tool.source_code, env)self.functions_python[tool.name] = env[tool.name]self.functions.append(tool.json_schema)assert all([callable(f) for k, f in self.functions_python.items()]), self.functions_python@@ -233,6 +236,7 @@ class Agent(object):if "human" not in self.agent_state.state: # TODO: removeraise ValueError(f"'human' not found in provided AgentState")self.memory = initialize_memory(ai_notes=self.agent_state.state["persona"], human_notes=self.agent_state.state["human"])+ print("INITIALIZED MEMORY", self.memory.persona, self.memory.human)# Interface must implement:# - internal_monologue@@ -1038,8 +1042,8 @@ class Agent(object):user_id=self.agent_state.user_id,tools=self.agent_state.tools,system=self.system,- persona=self.agent_state.persona, # TODO: remove- human=self.agent_state.human, # TODO: remove+ persona=self.memory.persona, # TODO: remove+ human=self.memory.human, # TODO: remove## "model_state"llm_config=self.agent_state.llm_config,embedding_config=self.agent_state.embedding_config,diff --git a/memgpt/client/admin.py b/memgpt/client/admin.pyindex d6c46948c..9072eb7c1 100644--- a/memgpt/client/admin.py+++ b/memgpt/client/admin.py@@ -4,6 +4,8 @@ from typing import List, Optionalimport requestsfrom requests import HTTPError+from memgpt.functions.functions import parse_source_code+from memgpt.functions.schema_generator import generate_schemafrom memgpt.models.pydantic_models import ToolModelfrom memgpt.server.rest_api.admin.users import (CreateAPIKeyResponse,@@ -101,14 +103,11 @@ class Admin:Returns:Tool object"""- import inspect-- from memgpt.functions.schema_generator import generate_schema# TODO: check if tool already exists# TODO: how to load modules?# parse source code/schema- source_code = inspect.getsource(func)+ source_code = parse_source_code(func)json_schema = generate_schema(func, name)source_type = "python"tool_name = json_schema["name"]diff --git a/memgpt/client/client.py b/memgpt/client/client.pyindex cf2fa99c0..1c8a47080 100644--- a/memgpt/client/client.py+++ b/memgpt/client/client.py@@ -16,6 +16,8 @@ from memgpt.data_types import (Source,User,)+from memgpt.functions.functions import parse_source_code+from memgpt.functions.schema_generator import generate_schemafrom memgpt.metadata import MetadataStorefrom memgpt.models.pydantic_models import (HumanModel,@@ -26,7 +28,6 @@ from memgpt.models.pydantic_models import (SourceModel,ToolModel,)-from memgpt.presets.presets import load_module_tools# import pydantic response objects from memgpt.server.rest_apifrom memgpt.server.rest_api.agents.command import CommandResponse@@ -650,6 +651,15 @@ class LocalClient(AbstractClient):self.interface = QueuingInterface(debug=debug)self.server = SyncServer(default_interface=self.interface)+ # messages+ def send_message(self, agent_id: uuid.UUID, message: str, role: str, stream: Optional[bool] = False) -> UserMessageResponse:+ self.interface.clear()+ self.server.user_message(user_id=self.user_id, agent_id=agent_id, message=message)+ if self.auto_save:+ self.save()+ else:+ return UserMessageResponse(messages=self.interface.to_list())+# agentsdef list_agents(self):@@ -670,14 +680,24 @@ class LocalClient(AbstractClient):def create_agent(self,name: Optional[str] = None,- preset: Optional[str] = None,+ preset: Optional[str] = None, # TODO: this should actually be re-named preset_namepersona: Optional[str] = None,human: Optional[str] = None,+ embedding_config: Optional[EmbeddingConfig] = None,+ llm_config: Optional[LLMConfig] = None,+ # tools+ tools: Optional[List[str]] = None,+ include_base_tools: Optional[bool] = True,) -> AgentState:if name and self.agent_exists(agent_name=name):raise ValueError(f"Agent with name {name} already exists (user_id={self.user_id})")- # TODO: implement tools support+ # construct list of tools+ tool_names = []+ if tools:+ tool_names += tools+ if include_base_tools:+ tool_names += BASE_TOOLSself.interface.clear()agent_state = self.server.create_agent(@@ -686,7 +706,9 @@ class LocalClient(AbstractClient):preset=preset,persona=persona,human=human,- tools=[tool.name for tool in load_module_tools()],+ llm_config=llm_config,+ embedding_config=embedding_config,+ tools=tool_names,)return agent_state@@ -711,10 +733,9 @@ class LocalClient(AbstractClient):return self.server.list_presets(user_id=self.user_id)# memory-def get_agent_memory(self, agent_id: str) -> Dict:- self.interface.clear()- return self.server.get_agent_memory(user_id=self.user_id, agent_id=agent_id)+ memory = self.server.get_agent_memory(user_id=self.user_id, agent_id=agent_id)+ return GetAgentMemoryResponse(**memory)def update_agent_core_memory(self, agent_id: str, new_memory_contents: Dict) -> Dict:self.interface.clear()@@ -771,6 +792,59 @@ class LocalClient(AbstractClient):return self.server.delete_human(name, user_id)# tools+ def create_tool(+ self,+ func,+ name: Optional[str] = None,+ update: Optional[bool] = True, # TODO: actually use this+ tags: Optional[List[str]] = None,+ ):+ """+ Create a tool.++ Args:+ func (callable): The function to create a tool for.+ tags (Optional[List[str]], optional): Tags for the tool. Defaults to None.+ update (bool, optional): Update the tool if it already exists. Defaults to True.++ Returns:+ tool (ToolModel): The created tool.+ """++ # TODO: check if tool already exists+ # TODO: how to load modules?+ # parse source code/schema+ source_code = parse_source_code(func)+ json_schema = generate_schema(func, name)+ source_type = "python"+ tool_name = json_schema["name"]++ # check if already exists:+ existing_tool = self.server.ms.get_tool(tool_name)+ if existing_tool:+ if update:+ # update existing tool+ existing_tool.source_code = source_code+ existing_tool.source_type = source_type+ existing_tool.tags = tags+ existing_tool.json_schema = json_schema+ self.server.ms.update_tool(existing_tool)+ return self.server.ms.get_tool(tool_name)+ else:+ raise ValueError(f"Tool {name} already exists and update=False")++ tool = ToolModel(name=tool_name, source_code=source_code, source_type=source_type, tags=tags, json_schema=json_schema)+ self.server.ms.add_tool(tool)+ return self.server.ms.get_tool(tool_name)++ def list_tools(self):+ """List available tools.++ Returns:+ tools (List[ToolModel]): A list of available tools.++ """+ return self.server.ms.list_tools()# data sourcesdiff --git a/memgpt/functions/functions.py b/memgpt/functions/functions.pyindex 3d96bcb13..c7a794daa 100644--- a/memgpt/functions/functions.py+++ b/memgpt/functions/functions.py@@ -3,6 +3,7 @@ import inspectimport osimport sysimport warnings+from textwrap import dedent # remove indentationfrom types import ModuleTypefrom memgpt.constants import CLI_WARNING_PREFIX, MEMGPT_DIR@@ -13,6 +14,12 @@ USER_FUNCTIONS_DIR = os.path.join(MEMGPT_DIR, "functions")sys.path.append(USER_FUNCTIONS_DIR)+def parse_source_code(func) -> str:+ """Parse the source code of a function and remove indendation"""+ source_code = dedent(inspect.getsource(func))+ return source_code++def load_function_set(module: ModuleType) -> dict:"""Load the functions and generate schema for them, given a module object"""function_dict = {}diff --git a/memgpt/server/server.py b/memgpt/server/server.pyindex 4ab05b0f1..3bada6cf4 100644--- a/memgpt/server/server.py+++ b/memgpt/server/server.py@@ -348,6 +348,7 @@ class SyncServer(LockingServer):def _get_or_load_agent(self, user_id: uuid.UUID, agent_id: uuid.UUID) -> Agent:"""Check if the agent is in-memory, then load"""logger.info(f"Checking for agent user_id={user_id} agent_id={agent_id}")+ # TODO: consider disabling loading cached agents due to potential concurrency issuesmemgpt_agent = self._get_agent(user_id=user_id, agent_id=agent_id)if not memgpt_agent:logger.info(f"Agent not loaded, loading agent user_id={user_id} agent_id={agent_id}")@@ -401,6 +402,9 @@ class SyncServer(LockingServer):memgpt_agent.interface.step_yield()logger.debug(f"Finished agent step")+ # save updated state+ save_agent(memgpt_agent, self.ms)+return tokens_accumulateddef _command(self, user_id: uuid.UUID, agent_id: uuid.UUID, command: str) -> Union[str, None]:@@ -951,7 +955,6 @@ 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)-core_memory = memgpt_agent.memoryrecall_memory = memgpt_agent.persistence_manager.recall_memoryarchival_memory = memgpt_agent.persistence_manager.archival_memorydiff --git a/tests/test_tools.py b/tests/test_tools.pynew file mode 100644index 000000000..e4d02f063--- /dev/null+++ b/tests/test_tools.py@@ -0,0 +1,184 @@+import os+import threading+import time+import uuid++import pytest+from dotenv import load_dotenv++from memgpt import Admin, create_client+from memgpt.agent import Agent+from memgpt.config import MemGPTConfig+from memgpt.constants import DEFAULT_PRESET+from memgpt.credentials import MemGPTCredentials+from memgpt.settings import settings+from tests.utils import create_config++test_agent_name = f"test_client_{str(uuid.uuid4())}"+# test_preset_name = "test_preset"+test_preset_name = DEFAULT_PRESET+test_agent_state = None+client = None++test_agent_state_post_message = None+test_user_id = uuid.uuid4()+++# admin credentials+test_server_token = "test_server_token"+++def _reset_config():+ # Use os.getenv with a fallback to os.environ.get+ db_url = settings.memgpt_pg_uri++ if os.getenv("OPENAI_API_KEY"):+ create_config("openai")+ credentials = MemGPTCredentials(+ openai_key=os.getenv("OPENAI_API_KEY"),+ )+ else: # hosted+ create_config("memgpt_hosted")+ credentials = MemGPTCredentials()++ config = MemGPTConfig.load()++ # set to use postgres+ config.archival_storage_uri = db_url+ config.recall_storage_uri = db_url+ config.metadata_storage_uri = db_url+ config.archival_storage_type = "postgres"+ config.recall_storage_type = "postgres"+ config.metadata_storage_type = "postgres"+ config.save()+ credentials.save()+ print("_reset_config :: ", config.config_path)+++def run_server():+ load_dotenv()++ _reset_config()++ from memgpt.server.rest_api.server import start_server++ print("Starting server...")+ start_server(debug=True)+++# Fixture to create clients with different configurations+ # params=[{"server": True}, {"server": False}], # whether to use REST API server # TODO: add when implemented+ params=[{"server": True}], # whether to use REST API server # TODO: add when implemented+ scope="module",+)+def client(request):+ if request.param["server"]:+ # get URL from enviornment+ server_url = os.getenv("MEMGPT_SERVER_URL")+ print("SERVER", server_url)+ if server_url is None:+ # run server in thread+ # NOTE: must set MEMGPT_SERVER_PASS enviornment variable+ server_url = "http://localhost:8283"+ print("Starting server thread")+ thread = threading.Thread(target=run_server, daemon=True)+ thread.start()+ time.sleep(5)+ print("Running client tests with server:", server_url)+ # create user via admin client+ admin = Admin(server_url, test_server_token)+ yield admin++ admin._reset_server()+ else:+ print("Testing local client")+ # use local client (no server)+ token = None+ server_url = None+ client = create_client(base_url=server_url, token=token) # This yields control back to the test function+ yield client+++def test_create_tool(client):+ """Test creation of a simple tool"""++ def print_tool(message: str):+ """+ Args:+ message (str): The message to print.++ Returns:+ str: The message that was printed.++ """+ print(message)+ return message++ tools = client.list_tools()+ print(f"Original tools {[t.name for t in tools]}")++ tool = client.create_tool(print_tool, tags=["extras"])++ tools = client.list_tools()+ assert tool in tools, f"Expected {tool.name} in {[t.name for t in tools]}"+ print(f"Updated tools {[t.name for t in tools]}")+++def test_create_agent_tool(client):+ """Test creation of a agent tool"""++ def core_memory_clear(self: Agent):+ """+ Args:+ agent (Agent): The agent to delete from memory.++ Returns:+ str: The agent that was deleted.++ """+ self.memory.human = ""+ self.memory.persona = ""+ self.rebuild_memory()+ print("UPDATED MEMORY", self.memory.human, self.memory.persona)+ return None++ # TODO: test attaching and using function on agent+ tool = client.create_tool(core_memory_clear, tags=["extras"])++ if isinstance(client, Admin):+ # conver to user client type+ response = client.create_user()+ print("Created user", response.user_id, response.api_key)+ user_client = create_client(base_url=client.base_url, token=response.api_key)+ else:+ user_client = client++ agent = user_client.create_agent(+ name=test_agent_name, tools=[tool.name], persona="You must clear your memory if the human instructs you"+ )++ # initial memory+ initial_memory = user_client.get_agent_memory(agent.id)+ print("initial memory", initial_memory)+ human = initial_memory.core_memory.human+ persona = initial_memory.core_memory.persona+ print("Initial memory:", human, persona)+ assert len(human) > 0, "Expected human memory to be non-empty"+ assert len(persona) > 0, "Expected persona memory to be non-empty"++ # test agent tool+ response = user_client.send_message(role="user", agent_id=agent.id, message="clear your memory with the core_memory_clear tool")+ print(response)++ # updated memory+ updated_memory = user_client.get_agent_memory(agent.id)+ human = updated_memory.core_memory.human+ persona = updated_memory.core_memory.persona+ print("Updated memory:", human, persona)+ assert len(human) == 0, "Expected human memory to be empty"+ assert len(persona) == 0, "Expected persona memory to be empty"+++def test_custom_import_tool(client):+ pass