Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
Remove usage of agent_config from agent.py
Sarah Wooders841d47c46220
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 214038281..1039cc547 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -163,6 +163,7 @@ class Agent(object):# extrasmessages_total=None, # TODO remove?first_message_verify_mono=True, # TODO move to config?+ memgpt_config: MemGPTConfig = None,):# Hold a copy of the state that was used to init the agentself.config = agent_state # TODO: remove@@ -232,8 +233,13 @@ class Agent(object):# When the summarizer is run, set this back to False (to reset)self.agent_alerted_about_memory_pressure = False- # Initialize the connection to the DB- self.memgpt_config = MemGPTConfig()+ # Read local config if not provided+ if not memgpt_config:+ self.memgpt_config = MemGPTConfig()+ else:+ self.memgpt_config = memgpt_config++ # Initialize connection to metedata storeself.ms = MetadataStore(self.memgpt_config)# Create the agent in the DB@@ -292,7 +298,7 @@ class Agent(object):"""Get response from LLM API"""try:response = create(- agent_config=self.config,+ agent_state=self.config,messages=message_sequence,functions=self.functions,function_call=function_call,@@ -599,7 +605,7 @@ class Agent(object):if (self.model is not None and self.model in LLM_MAX_TOKENS)else str(LLM_MAX_TOKENS["DEFAULT"]))- summary = summarize_messages(agent_config=self.config, message_sequence_to_summarize=message_sequence_to_summarize)+ summary = summarize_messages(agent_state=self.agent_state, message_sequence_to_summarize=message_sequence_to_summarize)printd(f"Got summary: {summary}")# Metadata that's useful for the agent to see@@ -686,73 +692,4 @@ class Agent(object):self.ms.create_agent(agent=agent_state)else:# Otherwise, we should update the agent- self.ms.update_agent(agent=agent_state)-- # # save config- # self.config.save()-- # # save agent state to timestamped file- # timestamp = get_local_time().replace(" ", "_").replace(":", "_")- # filename = f"{timestamp}.json"- # os.makedirs(self.config.save_state_dir(), exist_ok=True)- # self.save_agent_state_json(os.path.join(self.config.save_state_dir(), filename))-- # # save the persistence manager too (recall/archival memory)- # self.persistence_manager.save()-- ### Local state management- # def to_dict(self):- # # TODO: select specific variables for the saves state (to eventually move to a DB) rather than checkpointing everything in the class- # return {- # "model": self.model,- # "system": self.system,- # "functions": self.functions,- # "messages": self.messages, # TODO: convert to IDs- # "messages_total": self.messages_total,- # "memory": self.memory.to_dict(),- # }-- # def save_agent_state_json(self, filename):- # """Save agent state to JSON"""- # with open(filename, "w") as file:- # json.dump(self.to_dict(), file)-- # @classmethod- # def load_agent(cls, interface, agent_config: AgentConfig):- # """Load saved agent state based on agent_config"""- # # TODO: support loading from specific file- # agent_name = agent_config.name-- # # TODO: update this for metadata database-- # # load state- # directory = agent_config.save_state_dir()- # json_files = glob.glob(os.path.join(directory, "*.json")) # This will list all .json files in the current directory.- # if not json_files:- # print(f"/load error: no .json checkpoint files found")- # raise ValueError(f"Cannot load {agent_name} - no saved checkpoints found in {directory}")-- # # Sort files based on modified timestamp, with the latest file being the first.- # filename = max(json_files, key=os.path.getmtime)- # state = json.load(open(filename, "r"))-- # # load persistence manager- # persistence_manager = LocalStateManager.load(agent_config)-- # messages = state["messages"] # TODO: reconstruct messages using recall memory + stored IDs- # agent = cls(- # config=agent_config,- # model=state["model"],- # system=state["system"],- # functions=link_functions(state["functions"]),- # interface=interface,- # persistence_manager=persistence_manager,- # persistence_manager_init=False,- # persona_notes=state["memory"]["persona"],- # human_notes=state["memory"]["human"],- # messages_total=state["messages_total"] if "messages_total" in state else len(messages) - 1,- # )- # agent._messages = messages- # agent.memory = initialize_memory(state["memory"]["persona"], state["memory"]["human"])-- # return agent+ self.ms.update_agent(agent=agent_state)diff --git a/memgpt/client/client.py b/memgpt/client/client.pyindex ce4f2a1b1..bed3ae09c 100644--- a/memgpt/client/client.py+++ b/memgpt/client/client.py@@ -29,6 +29,7 @@ class Client(object):self.auto_save = auto_save# make sure everything is set up properly+ # TODO: remove this eventually? for multi-user, we can't have a shared config directoryMemGPTConfig.create_config_dir()# If this is the first ever start, do basic initializationdiff --git a/memgpt/config.py b/memgpt/config.pyindex a39c04897..ff6bb7c42 100644--- a/memgpt/config.py+++ b/memgpt/config.py@@ -361,6 +361,8 @@ class MemGPTConfig:@dataclassclass AgentConfig:"""++ NOTE: this is a deprecated class, use AgentState instead. This class is only used for backcompatibility.Configuration for a specific instance of an agent"""diff --git a/memgpt/data_types.py b/memgpt/data_types.pyindex 821a1fc9a..a2229e937 100644--- a/memgpt/data_types.py+++ b/memgpt/data_types.py@@ -145,6 +145,13 @@ class LLMConfig:model_endpoint: Optional[str] = "https://api.openai.com/v1",model_wrapper: Optional[str] = None,context_window: Optional[int] = None,+ # openai-only+ openai_key: Optional[str] = None,+ # azure-only+ azure_key: Optional[str] = None,+ azure_endpoint: Optional[str] = None,+ azure_version: Optional[str] = None,+ azure_deployment: Optional[str] = None,):self.model = modelself.model_endpoint_type = model_endpoint_type@@ -157,23 +164,10 @@ class LLMConfig:else:self.context_window = context_window--class OpenAILLMConfig(LLMConfig):- def __init__(self, openai_key, **kwargs):- super().__init__(**kwargs)+ # openaiself.openai_key = openai_key--class AzureLLMConfig(LLMConfig):- def __init__(- self,- azure_key: Optional[str] = None,- azure_endpoint: Optional[str] = None,- azure_version: Optional[str] = None,- azure_deployment: Optional[str] = None,- **kwargs,- ):- super().__init__(**kwargs)+ # azureself.azure_key = azure_keyself.azure_endpoint = azure_endpointself.azure_version = azure_versiondiff --git a/memgpt/memory.py b/memgpt/memory.pyindex ce7a8e38b..545604650 100644--- a/memgpt/memory.py+++ b/memgpt/memory.py@@ -6,8 +6,7 @@ from memgpt.constants import MESSAGE_SUMMARY_WARNING_FRACfrom memgpt.utils import get_local_time, printd, count_tokens, validate_date_format, extract_date_from_timestampfrom memgpt.prompts.gpt_summarize import SYSTEM as SUMMARY_PROMPT_SYSTEMfrom memgpt.openai_tools import create-from memgpt.data_types import Message, Passage-from memgpt.config import MemGPTConfig+from memgpt.data_types import Message, Passage, AgentStatefrom memgpt.embeddings import embedding_modelfrom llama_index import Documentfrom llama_index.node_parser import SimpleNodeParser@@ -102,12 +101,12 @@ class CoreMemory(object):def summarize_messages(- agent_config,+ agent_state: AgentState,message_sequence_to_summarize,):"""Summarize a message sequence using GPT"""# we need the context_window- context_window = agent_config.context_window+ context_window = agent_state.llm_config.context_windowsummary_prompt = SUMMARY_PROMPT_SYSTEMsummary_input = str(message_sequence_to_summarize)@@ -116,7 +115,7 @@ def summarize_messages(trunc_ratio = (MESSAGE_SUMMARY_WARNING_FRAC * context_window / summary_input_tkns) * 0.8 # For good measure...cutoff = int(len(message_sequence_to_summarize) * trunc_ratio)summary_input = str(- [summarize_messages(agent_config=agent_config, message_sequence_to_summarize=message_sequence_to_summarize[:cutoff])]+ [summarize_messages(agent_state, message_sequence_to_summarize=message_sequence_to_summarize[:cutoff])]+ message_sequence_to_summarize[cutoff:])message_sequence = [@@ -125,7 +124,7 @@ def summarize_messages(]response = create(- agent_config=agent_config,+ agent_state=agent_config,messages=message_sequence,)diff --git a/memgpt/openai_tools.py b/memgpt/openai_tools.pyindex a6a6fefbf..4d099a0fa 100644--- a/memgpt/openai_tools.py+++ b/memgpt/openai_tools.py@@ -10,6 +10,8 @@ from box import Boxfrom memgpt.local_llm.chat_completion_proxy import get_chat_completionfrom memgpt.constants import CLI_WARNING_PREFIX+from memgpt.data_types import AgentState+MODEL_TO_AZURE_ENGINE = {"gpt-4-1106-preview": "gpt-4","gpt-4": "gpt-4",@@ -365,7 +367,7 @@ def retry_with_exponential_backoff(@retry_with_exponential_backoffdef create(- agent_config,+ agent_state: AgentState,messages,functions=None,function_call="auto",@@ -374,54 +376,53 @@ def create():"""Return response to chat completion with backoff"""from memgpt.utils import printd- from memgpt.config import MemGPTConfig-- config = MemGPTConfig.load() # load credentials (currently not stored in agent config)- printd(f"Using model {agent_config.llm_config.model_endpoint_type}, endpoint: {agent_config.llm_config.model_endpoint}")- if agent_config.llm_config.model_endpoint_type == "openai":+ printd(f"Using model {agent_state.llm_config.model_endpoint_type}, endpoint: {agent_state.llm_config.model_endpoint}")+ if agent_state.llm_config.model_endpoint_type == "openai":# openaireturn openai_chat_completions_request(- url=agent_config.llm_config.model_endpoint, # https://api.openai.com/v1 -> https://api.openai.com/v1/chat/completions- api_key=config.openai_key, # 'sk....'+ 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(- model=agent_config.llm_config.model,+ model=agent_state.llm_config.model,messages=messages,functions=functions,function_call=function_call,- user=config.anon_clientid,+ user=str(agent_state.user_id),),)- elif agent_config.llm_config.model_endpoint_type == "azure":+ elif agent_state.llm_config.model_endpoint_type == "azure":# azureazure_deployment = (- config.azure_deployment if config.azure_deployment is not None else MODEL_TO_AZURE_ENGINE[agent_config.llm_config.model]+ agent_state.llm_config.azure_deployment+ if agent_state.llm_config.azure_deployment is not None+ else MODEL_TO_AZURE_ENGINE[agent_state.llm_config.model])return azure_openai_chat_completions_request(- resource_name=config.azure_endpoint,+ resource_name=agent_state.llm_config.azure_endpoint,deployment_id=azure_deployment,- api_version=config.azure_version,- api_key=config.azure_key,+ api_version=agent_state.llm_config.azure_version,+ api_key=agent_state.llm_config.azure_key,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=config.anon_clientid,+ user=str(agent_state.user_id),),)else: # local modelreturn get_chat_completion(- model=agent_config.llm_config.model,+ model=agent_state.llm_config.model,messages=messages,functions=functions,function_call=function_call,- context_window=agent_config.llm_config.context_window,- endpoint=agent_config.llm_config.model_endpoint,- endpoint_type=agent_config.llm_config.model_endpoint_type,- wrapper=agent_config.llm_config.model_wrapper,- user=config.anon_clientid,+ context_window=agent_state.llm_config.context_window,+ endpoint=agent_state.llm_config.model_endpoint,+ endpoint_type=agent_state.llm_config.model_endpoint_type,+ wrapper=agent_state.llm_config.model_wrapper,+ user=str(agent_state.user_id),# hintfirst_message=first_message,)