Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
Change Message data type to use tool format and create tool_call_id field
Sarah Wooders17506b7e9074
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 3963fb85d..33dff5b4c 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -1,4 +1,5 @@import datetime+import uuidimport globimport osimport json@@ -291,7 +292,7 @@ class Agent(object):"model": self.model,"system": self.system,"functions": self.functions,- "messages": self.messages,+ "messages": self.messages, # TODO: convert to IDs"messages_total": self.messages_total,"memory": self.memory.to_dict(),}@@ -338,7 +339,7 @@ class Agent(object):# load persistence managerpersistence_manager = LocalStateManager.load(agent_config)- messages = state["messages"]+ messages = state["messages"] # TODO: reconstruct messages using recall memory + stored IDsagent = cls(config=agent_config,model=state["model"],@@ -404,6 +405,11 @@ class Agent(object):if response_message.get("function_call"):# 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+ # role: assistant (requesting tool call, set tool call ID)messages.append(response_message) # extend conversation with assistant's reply# Step 3: call the function@@ -417,11 +423,7 @@ 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,- }+ {"role": "function", "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@@ -477,11 +479,7 @@ 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,- }+ {"role": "function", "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@@ -490,11 +488,7 @@ 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,- }+ {"role": "function", "name": function_name, "content": function_response, "tool_call_id": tool_call_id}) # extend conversation with function responseelse:diff --git a/memgpt/connectors/db.py b/memgpt/connectors/db.pyindex 3e5dba73d..a8d98b3c2 100644--- a/memgpt/connectors/db.py+++ b/memgpt/connectors/db.py@@ -120,10 +120,12 @@ def get_db_model(table_name: str, table_type: TableType):model = Column(String, nullable=False)user = Column(String) # optional: multi-agent only- # function info- function_name = Column(String)- function_args = Column(String)- function_response = Column(String)+ # tool call request info+ tool_name = Column(String)+ tool_args = Column(String)++ # tool call response info+ tool_call_id = Column(String)embedding = mapped_column(Vector(config.embedding_dim))@@ -141,9 +143,9 @@ def get_db_model(table_name: str, table_type: TableType):user=self.user,text=self.text,model=self.model,- function_name=self.function_name,- function_args=self.function_args,- function_response=self.function_response,+ tool_name=self.tool_name,+ tool_args=self.tool_args,+ tool_call_id=self.tool_call_id,embedding=self.embedding,created_at=self.created_at,id=self.id,@@ -259,23 +261,42 @@ class SQLStorageConnector(StorageConnector):unique_data_sources = session.query(self.db_model.data_source).filter(*self.filters).distinct().all()return unique_data_sources- def query_date(self, start_date, end_date):+ def query_date(self, start_date, end_date, offset=0, limit=None):session = self.Session()filters = self.get_filters({})- results = (+ query = (session.query(self.db_model).filter(*filters).filter(self.db_model.created_at >= start_date).filter(self.db_model.created_at <= end_date)- .all()+ .offset(offset))+ if limit:+ query = query.limit(limit)+ results = query.all()return [result.to_record() for result in results]- def query_text(self, query):+ def query_text(self, query, offset=0, limit=None):# todo: make fuzz https://stackoverflow.com/questions/42388956/create-a-full-text-search-index-with-sqlalchemy-on-postgresql/42390204#42390204session = self.Session()filters = self.get_filters({})- results = session.query(self.db_model).filter(*filters).filter(func.lower(self.db_model.text).contains(func.lower(query))).all()+ if limit:+ results = (+ session.query(self.db_model)+ .filter(*filters)+ .filter(func.lower(self.db_model.text).contains(func.lower(query)))+ .offset(offset)+ .all()+ )+ else:+ results = (+ session.query(self.db_model)+ .filter(*filters)+ .filter(func.lower(self.db_model.text).contains(func.lower(query)))+ .offset(offset)+ .limit(limit)+ .all()+ )# return [self.type(**vars(result)) for result in results]return [result.to_record() for result in results]diff --git a/memgpt/connectors/storage.py b/memgpt/connectors/storage.pyindex b62fa67a4..0e9b1ccb7 100644--- a/memgpt/connectors/storage.py+++ b/memgpt/connectors/storage.py@@ -178,7 +178,7 @@ class StorageConnector:pass@abstractmethod- def insert_many(self, records: List[Record], show_progress=True):+ def insert_many(self, records: List[Record], show_progress=False):pass@abstractmethoddiff --git a/memgpt/data_types.py b/memgpt/data_types.pyindex 885b2ed07..4e0453ad6 100644--- a/memgpt/data_types.py+++ b/memgpt/data_types.py@@ -36,9 +36,9 @@ class Message(Record):model: str, # model used to make function calluser: Optional[str] = None, # optional participant namecreated_at: Optional[str] = None,- function_name: Optional[str] = None, # name of function called- function_args: Optional[str] = None, # args of function called- function_response: Optional[str] = None, # response of function called+ tool_name: Optional[str] = None, # name of tool used+ tool_args: Optional[str] = None, # args of tool used+ tool_call_id: Optional[str] = None, # id of tool callembedding: Optional[np.ndarray] = None,id: Optional[str] = None,):@@ -53,10 +53,10 @@ class Message(Record):self.role = role # role (agent/user/function)self.user = user- # function call info (optional)- self.function_name = function_name- self.function_args = function_args- self.function_response = function_response+ # tool (i.e. function) call info (optional)+ self.tool_name = tool_name+ self.tool_args = tool_args+ self.tool_call_id = tool_call_id# embedding (optional)self.embedding = embeddingdiff --git a/memgpt/memory.py b/memgpt/memory.pyindex 8871e3637..81b939723 100644--- a/memgpt/memory.py+++ b/memgpt/memory.py@@ -343,7 +343,7 @@ class BaseRecallMemory(RecallMemory):def save(self):self.storage.save()- def size(self):+ def __len__(self):return self.storage.size()diff --git a/memgpt/persistence_manager.py b/memgpt/persistence_manager.pyindex 42a8bba56..b42f5efea 100644--- a/memgpt/persistence_manager.py+++ b/memgpt/persistence_manager.py@@ -123,9 +123,9 @@ class LocalStateManager(PersistenceManager):text=message["content"],model=self.agent_config.model,created_at=parse_formatted_time(timestamp),- function_name=message["function_name"] if "function_name" in message else None,- function_args=message["function_args"] if "function_args" in message else None,- function_response=message["function_response"] if "function_response" in message else None,+ tool_name=message["function_name"] if "function_name" in message else None,+ tool_args=message["function_args"] if "function_args" in message else None,+ tool_call_id=message["tool_call_id"] if "tool_call_id" in message else None,id=message["id"] if "id" in message else None,)