Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
cleanup
Charles Packer34d76b611ddb
diff --git a/memgpt/autogen/examples/agent_groupchat.py b/memgpt/autogen/examples/agent_groupchat.pyindex bb38dd584..2fd976469 100644--- a/memgpt/autogen/examples/agent_groupchat.py+++ b/memgpt/autogen/examples/agent_groupchat.py@@ -1,10 +1,17 @@"""Example of how to add MemGPT into an AutoGen groupchatBased on the official AutoGen example here: https://github.com/microsoft/autogen/blob/main/notebook/agentchat_groupchat.ipynb++Begin by doing:+ pip install "pyautogen[teachable]"+ pip install pymemgpt+ or+ pip install -e . (inside the MemGPT home directory)"""import osimport autogen+from memgpt.autogen.memgpt_agent import create_autogen_memgpt_agentconfig_list = [{@@ -40,19 +47,20 @@ if not USE_MEMGPT:name="Coder",llm_config=llm_config,)+else:# In our example, we swap this AutoGen agent with a MemGPT agent# This MemGPT agent will have all the benefits of MemGPT, ie persistent memory, etc.- from memgpt.autogen.memgpt_agent import create_autogen_memgpt_agent-coder = create_autogen_memgpt_agent("MemGPT_coder",persona_description="I am a 10x engineer, trained in Python. I was the first engineer at Uber (which I make sure to tell everyone I work with).",user_description="You are participating in a group chat with a user and a product manager (PM).",+ # extra options+ interface_kwargs={"debug": True},)# Initialize the group chat between the user and two LLM agents (PM and coder)-groupchat = autogen.GroupChat(agents=[user_proxy, coder, pm], messages=[], max_round=12)+groupchat = autogen.GroupChat(agents=[user_proxy, pm, coder], messages=[], max_round=12)manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)# Begin the group chat with a message from the userdiff --git a/memgpt/autogen/interface.py b/memgpt/autogen/interface.pyindex 15d9cc270..4f01fd7aa 100644--- a/memgpt/autogen/interface.py+++ b/memgpt/autogen/interface.py@@ -2,6 +2,7 @@ import jsonimport refrom colorama import Fore, Style, init+init(autoreset=True)@@ -10,7 +11,6 @@ DEBUG = False # only dumps important messages in the terminalclass DummyInterface(object):-def set_message_list(self, message_list):pass@@ -42,10 +42,21 @@ class AutoGenInterface(object):The buffer needs to be wiped before each call to memgpt.agent.step()"""- def __init__(self, message_list=None, show_user_message=False, fancy=True):+ def __init__(+ self,+ message_list=None,+ fancy=False,+ show_user_message=False,+ show_inner_thoughts=False,+ show_function_outputs=False,+ debug=False,+ ):self.message_list = message_list- self.show_user_message = show_user_messageself.fancy = fancy # set to false to disable colored outputs + emoji prefixes+ self.show_user_message = show_user_message+ self.show_inner_thoughts = show_inner_thoughts+ self.show_function_outputs = show_function_outputs+ self.debug = debugdef reset_message_list(self):"""Clears the buffer. Call before every agent.step() when using MemGPT+AutoGen"""@@ -53,28 +64,60 @@ class AutoGenInterface(object):async def internal_monologue(self, msg):# ANSI escape code for italic is '\x1B[3m'- message = f'\x1B[3m{Fore.LIGHTBLACK_EX}π {msg}{Style.RESET_ALL}' if self.fancy else f'[inner thoughts] {msg}'+ if self.debug:+ print(f"inner thoughts :: {msg}")+ if not self.show_inner_thoughts:+ return+ message = (+ f"\x1B[3m{Fore.LIGHTBLACK_EX}π {msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[inner thoughts] {msg}"+ )self.message_list.append(message)async def assistant_message(self, msg):- message = f'{Fore.YELLOW}{Style.BRIGHT}π€ {Fore.YELLOW}{msg}{Style.RESET_ALL}' if self.fancy else msg+ if self.debug:+ print(f"assistant :: {msg}")+ message = (+ f"{Fore.YELLOW}{Style.BRIGHT}π€ {Fore.YELLOW}{msg}{Style.RESET_ALL}"+ if self.fancy+ else msg+ )self.message_list.append(message)async def memory_message(self, msg):- message = f'{Fore.LIGHTMAGENTA_EX}{Style.BRIGHT}π§ {Fore.LIGHTMAGENTA_EX}{msg}{Style.RESET_ALL}' if self.fancy else f'[memory] {msg}'+ if self.debug:+ print(f"memory :: {msg}")+ message = (+ f"{Fore.LIGHTMAGENTA_EX}{Style.BRIGHT}π§ {Fore.LIGHTMAGENTA_EX}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[memory] {msg}"+ )self.message_list.append(message)async def system_message(self, msg):- message = f'{Fore.MAGENTA}{Style.BRIGHT}π₯οΈ [system] {Fore.MAGENTA}{msg}{Style.RESET_ALL}' if self.fancy else f'[system] {msg}'+ if self.debug:+ print(f"system :: {msg}")+ message = (+ f"{Fore.MAGENTA}{Style.BRIGHT}π₯οΈ [system] {Fore.MAGENTA}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[system] {msg}"+ )self.message_list.append(message)async def user_message(self, msg, raw=False):+ if self.debug:+ print(f"user :: {msg}")if not self.show_user_message:returnif isinstance(msg, str):if raw:- message = f'{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg}{Style.RESET_ALL}' if self.fancy else f'[user] {msg}'+ message = (+ f"{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[user] {msg}"+ )self.message_list.append(message)returnelse:@@ -82,77 +125,137 @@ class AutoGenInterface(object):msg_json = json.loads(msg)except:print(f"Warning: failed to parse user message into json")- message = f'{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg}{Style.RESET_ALL}' if self.fancy else f'[user] {msg}'+ message = (+ f"{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[user] {msg}"+ )self.message_list.append(message)return- if msg_json['type'] == 'user_message':- msg_json.pop('type')- message = f'{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg_json}{Style.RESET_ALL}' if self.fancy else f'[user] {msg}'- elif msg_json['type'] == 'heartbeat':+ if msg_json["type"] == "user_message":+ msg_json.pop("type")+ message = (+ f"{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg_json}{Style.RESET_ALL}"+ if self.fancy+ else f"[user] {msg}"+ )+ elif msg_json["type"] == "heartbeat":if True or DEBUG:- msg_json.pop('type')- message = f'{Fore.GREEN}{Style.BRIGHT}π {Fore.GREEN}{msg_json}{Style.RESET_ALL}' if self.fancy else f'[system heartbeat] {msg}'- elif msg_json['type'] == 'system_message':- msg_json.pop('type')- message = f'{Fore.GREEN}{Style.BRIGHT}π₯οΈ {Fore.GREEN}{msg_json}{Style.RESET_ALL}' if self.fancy else f'[system] {msg}'+ msg_json.pop("type")+ message = (+ f"{Fore.GREEN}{Style.BRIGHT}π {Fore.GREEN}{msg_json}{Style.RESET_ALL}"+ if self.fancy+ else f"[system heartbeat] {msg}"+ )+ elif msg_json["type"] == "system_message":+ msg_json.pop("type")+ message = (+ f"{Fore.GREEN}{Style.BRIGHT}π₯οΈ {Fore.GREEN}{msg_json}{Style.RESET_ALL}"+ if self.fancy+ else f"[system] {msg}"+ )else:- message = f'{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg_json}{Style.RESET_ALL}' if self.fancy else f'[user] {msg}'+ message = (+ f"{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg_json}{Style.RESET_ALL}"+ if self.fancy+ else f"[user] {msg}"+ )self.message_list.append(message)async def function_message(self, msg):+ if self.debug:+ print(f"function :: {msg}")+ if not self.show_function_outputs:+ returnif isinstance(msg, dict):- message = f'{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}'+ message = (+ f"{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}"+ )self.message_list.append(message)return- if msg.startswith('Success: '):- message = f'{Fore.RED}{Style.BRIGHT}β‘π’ [function] {Fore.RED}{msg}{Style.RESET_ALL}' if self.fancy else f'[function - OK] {msg}'- elif msg.startswith('Error: '):- message = f'{Fore.RED}{Style.BRIGHT}β‘π΄ [function] {Fore.RED}{msg}{Style.RESET_ALL}' if self.fancy else f'[function - error] {msg}'- elif msg.startswith('Running '):+ if msg.startswith("Success: "):+ message = (+ f"{Fore.RED}{Style.BRIGHT}β‘π’ [function] {Fore.RED}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[function - OK] {msg}"+ )+ elif msg.startswith("Error: "):+ message = (+ f"{Fore.RED}{Style.BRIGHT}β‘π΄ [function] {Fore.RED}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[function - error] {msg}"+ )+ elif msg.startswith("Running "):if DEBUG:- message = f'{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}' if self.fancy else f'[function] {msg}'+ message = (+ f"{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[function] {msg}"+ )else:- if 'memory' in msg:- match = re.search(r'Running (\w+)\((.*)\)', msg)+ if "memory" in msg:+ match = re.search(r"Running (\w+)\((.*)\)", msg)if match:function_name = match.group(1)function_args = match.group(2)- message = f'{Fore.RED}{Style.BRIGHT}β‘π§ [function] {Fore.RED}updating memory with {function_name}{Style.RESET_ALL}:' \- if self.fancy else f'[function] updating memory with {function_name}'+ message = (+ f"{Fore.RED}{Style.BRIGHT}β‘π§ [function] {Fore.RED}updating memory with {function_name}{Style.RESET_ALL}:"+ if self.fancy+ else f"[function] updating memory with {function_name}"+ )try:msg_dict = eval(function_args)- if function_name == 'archival_memory_search':- message = f'{Fore.RED}\tquery: {msg_dict["query"]}, page: {msg_dict["page"]}' \- if self.fancy else f'[function] query: {msg_dict["query"]}, page: {msg_dict["page"]}'+ if function_name == "archival_memory_search":+ message = (+ f'{Fore.RED}\tquery: {msg_dict["query"]}, page: {msg_dict["page"]}'+ if self.fancy+ else f'[function] query: {msg_dict["query"]}, page: {msg_dict["page"]}'+ )else:- message = f'{Fore.RED}{Style.BRIGHT}\t{Fore.RED} {msg_dict["old_content"]}\n\t{Fore.GREEN}β {msg_dict["new_content"]}' \- if self.fancy else f'[old -> new] {msg_dict["old_content"]} -> {msg_dict["new_content"]}'+ message = (+ f'{Fore.RED}{Style.BRIGHT}\t{Fore.RED} {msg_dict["old_content"]}\n\t{Fore.GREEN}β {msg_dict["new_content"]}'+ if self.fancy+ else f'[old -> new] {msg_dict["old_content"]} -> {msg_dict["new_content"]}'+ )except Exception as e:print(e)message = msg_dictelse:print(f"Warning: did not recognize function message")- message = f'{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}' \- if self.fancy else f'[function] {msg}'- elif 'send_message' in msg:+ message = (+ f"{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[function] {msg}"+ )+ elif "send_message" in msg:# ignore in debug modemessage = Noneelse:- message = f'{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}' \- if self.fancy else f'[function] {msg}'+ message = (+ f"{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[function] {msg}"+ )else:try:msg_dict = json.loads(msg)if "status" in msg_dict and msg_dict["status"] == "OK":- message = f'{Fore.GREEN}{Style.BRIGHT}β‘ [function] {Fore.GREEN}{msg}{Style.RESET_ALL}' \- if self.fancy else f'[function] {msg}'+ message = (+ f"{Fore.GREEN}{Style.BRIGHT}β‘ [function] {Fore.GREEN}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[function] {msg}"+ )except Exception:print(f"Warning: did not recognize function message {type(msg)} {msg}")- message = f'{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}' \- if self.fancy else f'[function] {msg}'+ message = (+ f"{Fore.RED}{Style.BRIGHT}β‘ [function] {Fore.RED}{msg}{Style.RESET_ALL}"+ if self.fancy+ else f"[function] {msg}"+ )- if message: self.message_list.append(message)+ if message:+ self.message_list.append(message)diff --git a/memgpt/autogen/memgpt_agent.py b/memgpt/autogen/memgpt_agent.pyindex a3bb6f3fc..c8ac74160 100644--- a/memgpt/autogen/memgpt_agent.py+++ b/memgpt/autogen/memgpt_agent.py@@ -41,11 +41,15 @@ def create_autogen_memgpt_agent(persona_description=personas.DEFAULT,user_description=humans.DEFAULT,interface=None,+ interface_kwargs={},persistence_manager=None,+ persistence_manager_kwargs={},):- interface = AutoGenInterface() if interface is None else interface+ interface = AutoGenInterface(**interface_kwargs) if interface is None else interfacepersistence_manager = (- InMemoryStateManager() if persistence_manager is None else persistence_manager+ InMemoryStateManager(**persistence_manager_kwargs)+ if persistence_manager is None+ else persistence_manager)memgpt_agent = presets.use_preset(@@ -92,12 +96,17 @@ class MemGPTAgent(ConversableAgent):sender: Optional[Agent] = None,config: Optional[Any] = None,) -> Tuple[bool, Union[str, Dict, None]]:- ret = []+ # ret = []# for the interface+ # print(f"a_gen_reply messages:\n{messages}")self.agent.interface.reset_message_list()for msg in messages:- user_message = system.package_user_message(msg["content"])+ if "name" in msg:+ user_message_raw = f"{msg['name']}: {msg['content']}"+ else:+ user_message_raw = msg["content"]+ user_message = system.package_user_message(user_message_raw)while True:(new_messages,@@ -107,7 +116,7 @@ class MemGPTAgent(ConversableAgent):) = await self.agent.step(user_message, first_message=False, skip_verify=self.skip_verify)- ret.extend(new_messages)+ # ret.extend(new_messages)# Skip user inputs if there's a memory warning, function execution failed, or the agent asked for controlif token_warning:user_message = system.get_token_limit_warning()