Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

Add data_types.py file for standard data types

Sarah Woodersd04145537557
diff --git a/memgpt/connectors/db.py b/memgpt/connectors/db.py
index 6c83e1254..0c10f4f2b 100644
--- a/memgpt/connectors/db.py
+++ b/memgpt/connectors/db.py
@@ -16,7 +16,7 @@ from tqdm import tqdm
import pandas as pd
from memgpt.config import MemGPTConfig
-from memgpt.connectors.storage import StorageConnector, Passage
+from memgpt.connectors.storage import StorageConnector, TableType
from memgpt.config import AgentConfig, MemGPTConfig
from memgpt.constants import MEMGPT_DIR
from memgpt.utils import printd
@@ -24,28 +24,33 @@ from memgpt.utils import printd
Base = declarative_base()
-def get_db_model(table_name: str):
+def get_db_model(table_name: str, table_type: TableType):
config = MemGPTConfig.load()
- class PassageModel(Base):
- """Defines data model for storing Passages (consisting of text, embedding)"""
-
- __abstract__ = True # this line is necessary
-
- # Assuming passage_id is the primary key
- id = Column(BIGINT, primary_key=True, nullable=False, autoincrement=True)
- doc_id = Column(String)
- text = Column(String, nullable=False)
- embedding = mapped_column(Vector(config.embedding_dim))
- metadata_ = Column(JSON(astext_type=Text()))
-
- def __repr__(self):
- return f"<Passage(passage_id='{self.id}', text='{self.text}', embedding='{self.embedding})>"
-
- """Create database model for table_name"""
- class_name = f"{table_name.capitalize()}Model"
- Model = type(class_name, (PassageModel,), {"__tablename__": table_name, "__table_args__": {"extend_existing": True}})
- return Model
+ if table_name == TableType.ARCHIVAL_MEMORY:
+ # create schema for archival memory
+ class PassageModel(Base):
+ """Defines data model for storing Passages (consisting of text, embedding)"""
+
+ __abstract__ = True # this line is necessary
+
+ # Assuming passage_id is the primary key
+ id = Column(BIGINT, primary_key=True, nullable=False, autoincrement=True)
+ doc_id = Column(String)
+ text = Column(String, nullable=False)
+ embedding = mapped_column(Vector(config.embedding_dim))
+ metadata_ = Column(JSON(astext_type=Text()))
+
+ def __repr__(self):
+ return f"<Passage(passage_id='{self.id}', text='{self.text}', embedding='{self.embedding})>"
+
+ """Create database model for table_name"""
+ class_name = f"{table_name.capitalize()}Model"
+ Model = type(class_name, (PassageModel,), {"__tablename__": table_name, "__table_args__": {"extend_existing": True}})
+ return Model
+ else:
+ # TODO: implement recall memory, document store
+ raise NotImplementedError(f"Table type {table_type} not implemented")
class PostgresStorageConnector(StorageConnector):
diff --git a/memgpt/connectors/storage.py b/memgpt/connectors/storage.py
index f44b51600..5e64f39b9 100644
--- a/memgpt/connectors/storage.py
+++ b/memgpt/connectors/storage.py
@@ -15,6 +15,7 @@ from tqdm import tqdm
from memgpt.config import AgentConfig, MemGPTConfig
+from memgpt.data_types import Record
# ENUM representing table types in MemGPT
@@ -30,78 +31,6 @@ class TableType:
# Note: user/agent can borrow from MemGPTConfig/AgentConfig classes
-class Record:
- """Base class for all table records"""
-
- def __init__(self, user_id: str):
- self.user_id = user_id
-
-
-class Message(Record):
- """A message is a single unit of communication, and a standard format accross all storage backends.
-
- It is a string of text with an associated embedding.
- """
-
- def __init__(
- self, user_id: str, agent_id: str, role: str, text: str, embedding: Optional[np.ndarray] = None, message_id: Optional[str] = None
- ):
- super().__init__(user_id)
- self.agent_id = agent_id
- self.role = role
- self.text = text
- self.embedding = embedding # optional
- self.message_id = message_id
- self.message_type = "conversation"
- # todo: self.role = role (?)
-
- def __repr__(self):
- return f"Message(text={self.text}, embedding={self.embedding})"
-
-
-class FunctionCallMessage(Message):
- def __init__(
- self, user_id: str, agent_id: str, role: str, text: str, embedding: Optional[np.ndarray] = None, message_id: Optional[str] = None
- ):
- super().__init__(user_id, agent_id, role, text, None, message_id)
- self.message_type = "function"
-
- # todo: self.role = role (?)
-
- def __repr__(self):
- return f"Message(text={self.text}, embedding={self.embedding})"
-
-
-class Document(Record):
- """A document represent a document loaded into MemGPT, which is broken down into passages."""
-
- def __init__(self, user_id: str, text: str, document_id: Optional[str] = None):
- super().__init__(user_id)
- self.text = text
- self.document_id = document_id
- # TODO: add optional embedding?
-
- def __repr__(self) -> str:
- pass
-
-
-class Passage(Record):
- """A passage is a single unit of memory, and a standard format accross all storage backends.
-
- It is a string of text with an associated embedding.
- """
-
- def __init__(self, user_id: str, text: str, embedding: np.ndarray, doc_id: Optional[str] = None, passage_id: Optional[str] = None):
- super().__init__(user_id)
- self.text = text
- self.embedding = embedding
- self.doc_id = doc_id
- self.passage_id = passage_id
-
- def __repr__(self):
- return f"Passage(text={self.text}, embedding={self.embedding})"
-
-
class StorageConnector:
@staticmethod
def get_archival_storage_connector(name: Optional[str] = None, agent_config: Optional[AgentConfig] = None):
@@ -168,27 +97,27 @@ class StorageConnector:
raise NotImplementedError(f"Storage type {storage_type} not implemented")
@abstractmethod
- def get_all_paginated(self, page_size: int) -> Iterator[List[Passage]]:
+ def get_all_paginated(self, page_size: int) -> Iterator[List[Record]]:
pass
@abstractmethod
- def get_all(self, limit: int) -> List[Passage]:
+ def get_all(self, limit: int) -> List[Record]:
pass
@abstractmethod
- def get(self, id: str) -> Passage:
+ def get(self, id: str) -> Record:
pass
@abstractmethod
- def insert(self, passage: Passage):
+ def insert(self, passage: Record):
pass
@abstractmethod
- def insert_many(self, passages: List[Passage]):
+ def insert_many(self, passages: List[Record]):
pass
@abstractmethod
- def query(self, query: str, query_vec: List[float], top_k: int = 10) -> List[Passage]:
+ def query(self, query: str, query_vec: List[float], top_k: int = 10) -> List[Record]:
pass
@abstractmethod
diff --git a/memgpt/data_types.py b/memgpt/data_types.py
new file mode 100644
index 000000000..0b6dcf292
--- /dev/null
+++ b/memgpt/data_types.py
@@ -0,0 +1,90 @@
+""" This module contains the data types used by MemGPT. Each data type must include a function to create a DB model. """
+from abc import abstractmethod
+from typing import Optional
+import numpy as np
+
+
+# Defining schema objects:
+# Note: user/agent can borrow from MemGPTConfig/AgentConfig classes
+
+
+class Record:
+ """
+ Base class for an agent's memory unit. Each memory unit is represented in the database as a single row.
+ Memory units are searched over by functions defined in the memory classes
+ """
+
+ def __init__(self, user_id: str, agent_id: str, text: str, id: Optional[str] = None):
+ self.user_id = user_id
+ self.agent_id = agent_id
+ self.text = text
+ self.id = id
+ # todo: generate unique uuid
+ # todo: timestamp
+ # todo: self.role = role (?)
+
+ def __repr__(self):
+ pass
+
+
+class Message(Record):
+ """Representation of a message sent from the agent -> user. Also includes function calls."""
+
+ def __init__(
+ self,
+ user_id: str,
+ agent_id: str,
+ role: str,
+ text: str,
+ model: str, # model used to make function call
+ 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
+ embedding: Optional[np.ndarray] = None,
+ id: Optional[str] = None,
+ ):
+ super().__init__(user_id, agent_id, text, id)
+ self.role = role # role (agent/user/function)
+ self.model = model # model name (e.g. gpt-4)
+
+ # function call info (optional)
+ self.function_name = function_name
+ self.function_args = function_args
+ self.function_response = function_response
+
+ # embedding (optional)
+ self.embedding = embedding
+
+ def __repr__(self):
+ pass
+
+
+class Document(Record):
+ """A document represent a document loaded into MemGPT, which is broken down into passages."""
+
+ def __init__(self, user_id: str, text: str, document_id: Optional[str] = None):
+ super().__init__(user_id)
+ self.text = text
+ self.document_id = document_id
+ # TODO: add optional embedding?
+
+ def __repr__(self) -> str:
+ pass
+
+
+class Passage(Record):
+ """A passage is a single unit of memory, and a standard format accross all storage backends.
+
+ It is a string of text with an associated embedding.
+ """
+
+ def __init__(self, user_id: str, text: str, embedding: np.ndarray, doc_id: Optional[str] = None, passage_id: Optional[str] = None):
+ super().__init__(user_id)
+ self.text = text
+ self.embedding = embedding
+ self.doc_id = doc_id
+ self.passage_id = passage_id
+ self.metadata = {}
+
+ def __repr__(self):
+ return f"Passage(text={self.text}, embedding={self.embedding})"
diff --git a/memgpt/memory.py b/memgpt/memory.py
index 5f86eeca0..096738498 100644
--- a/memgpt/memory.py
+++ b/memgpt/memory.py
@@ -192,7 +192,6 @@ class DummyRecallMemory(RecallMemory):
# TODO: replace this with StorageConnector based implementation
def __init__(self, agent_config, restrict_search_to_summaries=False):
- self._message_logs = [] if message_database is None else message_database # consists of full message dicts
# If true, the pool of messages that can be queried are the automated summaries only
# (generated when the conversation window needs to be shortened)