Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
Refactor chroma integration
Sarah Wooders453a7c0c3e4b
diff --git a/memgpt/cli/cli_config.py b/memgpt/cli/cli_config.pyindex e7ede919c..f4df71b02 100644--- a/memgpt/cli/cli_config.py+++ b/memgpt/cli/cli_config.py@@ -406,12 +406,7 @@ def configure_archival_storage(config: MemGPTConfig):if chroma_type == "http":archival_storage_uri = questionary.text("Enter chroma ip (e.g. localhost:8000):", default="localhost:8000").ask()if chroma_type == "persistent":- print(config.config_path, config.archival_storage_path)- default_archival_storage_path = (- config.archival_storage_path if config.archival_storage_path else os.path.join(config.config_path, "chroma")- )- print(default_archival_storage_path)- archival_storage_path = questionary.text("Enter persistent storage location:", default=default_archival_storage_path).ask()+ archival_storage_path = os.path.join(MEMGPT_DIR, "chroma")return archival_storage_type, archival_storage_uri, archival_storage_path@@ -420,7 +415,7 @@ def configure_archival_storage(config: MemGPTConfig):def configure_recall_storage(config: MemGPTConfig):# Configure recall storage backend- recall_storage_options = ["local", "postgres"]+ recall_storage_options = ["local", "postgres", "chroma"]recall_storage_type = questionary.select("Select storage backend for recall data:", recall_storage_options, default=config.recall_storage_type).ask()@@ -431,6 +426,15 @@ def configure_recall_storage(config: MemGPTConfig):"Enter postgres connection string (e.g. postgresql+pg8000://{user}:{password}@{ip}:5432/{database}):",default=config.recall_storage_uri if config.recall_storage_uri else "",).ask()++ # configure chroma+ if recall_storage_type == "chroma":+ chroma_type = questionary.select("Select chroma backend:", ["http", "persistent"], default="http").ask()+ if chroma_type == "http":+ recall_storage_uri = questionary.text("Enter chroma ip (e.g. localhost:8000):", default="localhost:8000").ask()+ if chroma_type == "persistent":+ recall_storage_path = os.path.join(MEMGPT_DIR, "chroma")+return recall_storage_type, recall_storage_uri, recall_storage_pathdiff --git a/memgpt/connectors/chroma.py b/memgpt/connectors/chroma.pyindex 38ed3a1bf..a2e7a43fb 100644--- a/memgpt/connectors/chroma.py+++ b/memgpt/connectors/chroma.py@@ -1,9 +1,9 @@import chromadbimport jsonimport re-from typing import Optional, List, Iterator+from typing import Optional, List, Iterator, Dictfrom memgpt.connectors.storage import StorageConnector, TableType-from memgpt.utils import printd+from memgpt.utils import printd, datetime_to_timestamp, timestamp_to_datetimefrom memgpt.config import AgentConfig, MemGPTConfigfrom memgpt.data_types import Record, Message, Passage@@ -12,17 +12,12 @@ class ChromaStorageConnector(StorageConnector):"""Storage via Chroma"""# WARNING: This is not thread safe. Do NOT do concurrent access to the same collection.+ # Timestamps are converted to integer timestamps for chroma (datetime not supported)def __init__(self, table_type: str, agent_config: Optional[AgentConfig] = None):super().__init__(table_type=table_type, agent_config=agent_config)config = MemGPTConfig.load()- # supported table types- self.supported_types = [TableType.ARCHIVAL_MEMORY]-- if table_type not in self.supported_types:- raise ValueError(f"Table type {table_type} not supported by Chroma")-# create chroma clientif config.archival_storage_path:self.client = chromadb.PersistentClient(config.archival_storage_path)@@ -34,45 +29,77 @@ class ChromaStorageConnector(StorageConnector):# get a collection or create if it doesn't exist alreadyself.collection = self.client.get_or_create_collection(self.table_name)+ self.include = ["id", "documents", "embeddings", "metadatas"]- def get_all_paginated(self, page_size: int) -> Iterator[List[Passage]]:+ def get_all_paginated(self, page_size: int, filters: Optional[Dict]) -> Iterator[List[Record]]:offset = 0+ filters = self.get_filters(filters)while True:# Retrieve a chunk of records with the given page_size- db_passages_chunk = self.collection.get(offset=offset, limit=page_size, include=["embeddings", "documents"])+ db_chunks = self.collection.get(offset=offset, limit=page_size, include=self.include, where=filters)# If the chunk is empty, we've retrieved all records- if not db_passages_chunk:+ if not db_chunks:break- # Yield a list of Passage objects converted from the chunk- yield [Passage(text=p.text, embedding=p.embedding, doc_id=p.doc_id, passage_id=p.id) for p in db_passages_chunk]+ # Yield a list of Record objects converted from the chunk+ yield self.results_to_records(db_chunks)# Increment the offset to get the next chunk in the next iterationoffset += page_size- def get_all(self) -> List[Passage]:- results = self.collection.get(include=["embeddings", "documents"])- return [Passage(text=text, embedding=embedding) for (text, embedding) in zip(results["documents"], results["embeddings"])]-- def get(self, id: str) -> Optional[Passage]:+ def results_to_records(self, results):+ # convert timestamps to datetime+ for metadata in results["metadatas"]:+ if "created_at" in metadata:+ metadata["created_at"] = timestamp_to_datetime(metadata["created_at"])+ return [+ self.type(id=id, text=text, embedding=embedding, **metadatas)+ for (id, text, embedding, metadatas) in zip(results["ids"], results["documents"], results["embeddings"], results["metadatas"])+ ]++ def get_all(self, limit=10, filters: Optional[Dict] = {}) -> List[Record]:+ filters = self.get_filters(filters)+ results = self.collection.get(include=self.include, where=filters)+ return self.results_to_records(results)++ def get(self, id: str, filters: Optional[Dict] = {}) -> Optional[Record]:+ filters = self.get_filters(filters)results = self.collection.get(ids=[id])- return [Passage(text=text, embedding=embedding) for (text, embedding) in zip(results["documents"], results["embeddings"])]-- def insert(self, passage: Passage):- self.collection.add(documents=[passage.text], embeddings=[passage.embedding], ids=[str(self.collection.count())])-- def insert_many(self, passages: List[Passage], show_progress=True):+ return self.results_to_records(results)++ def insert(self, record: Record):+ if record.id is None:+ record.id = str(self.collection.count())+ metadata = vars(record)+ metadata.pop("id")+ metadata.pop("text")+ metadata.pop("embedding")+ self.collection.add(documents=[record.text], embeddings=[record.embedding], ids=[record.id], metadatas=[metadata])++ def insert_many(self, records: List[Record], show_progress=True):count = self.collection.count()- ids = [str(count + i) for i in range(len(passages))]- self.collection.add(- documents=[passage.text for passage in passages], embeddings=[passage.embedding for passage in passages], ids=ids- )-- def query(self, query: str, query_vec: List[float], top_k: int = 10) -> List[Passage]:- results = self.collection.query(query_embeddings=[query_vec], n_results=top_k, include=["embeddings", "documents"])- # get index [0] since query is passed as list- return [Passage(text=text, embedding=embedding) for (text, embedding) in zip(results["documents"][0], results["embeddings"][0])]+ metadatas = []+ ids = []+ documents = [record.text for record in records]+ embeddings = [record.embedding for record in records]+ for record in records:+ if record.id is None:+ count += 1+ ids.append(str(count))+ # TODO: ensure that other record.ids dont match+ metadata = vars(record)+ metadata.pop("id")+ metadata.pop("text")+ metadata.pop("embedding")+ if "created_at" in metadata:+ metadata["created_at"] = datetime_to_timestamp(metadata["created_at"])+ metadata = {key: value for key, value in metadata.items() if value is not None} # null values not allowed+ metadatas.append(metadata)+ if not any(embeddings):+ self.collection.add(documents=documents, ids=ids, metadatas=metadatas)+ else:+ self.collection.add(documents=documents, embeddings=embeddings, ids=ids, metadatas=metadatas)def delete(self):self.client.delete_collection(name=self.table_name)@@ -82,12 +109,35 @@ class ChromaStorageConnector(StorageConnector):printd("Saving chroma")pass- @staticmethod- def list_loaded_data():- client = create_chroma_client()- collections = client.list_collections()- collections = [c.name for c in collections if c.name.startswith("memgpt_") and not c.name.startswith("memgpt_agent_")]- return collections-- def size(self) -> int:+ def size(self, filters: Optional[Dict] = {}) -> int:+ filters = self.get_filters(filters)return self.collection.count()++ def list_data_sources(self):+ raise NotImplementedError++ def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[Record]:+ filters = self.get_filters(filters)+ results = self.collection.query(query_embeddings=[query_vec], n_results=top_k, include=self.include, where=filters)+ return self.results_to_records(results)++ def query_date(self, start_date, end_date, start=None, count=None):+ # TODO: no idea if this is correct+ filters = self.get_filters(filters)+ filters["created_at"] = {+ "$gte": start_date,+ "$lte": end_date,+ }+ results = self.collection.query(where=filters)+ start = 0 if start is None else start+ count = len(results) if count is None else count+ results = results[start : start + count]+ return self.results_to_records(results)++ def query_text(self, query, count=None, start=None, filters: Optional[Dict] = {}):+ filters = self.get_filters(filters)+ results = self.collection.query(where_document={"$contains": {"text": query}}, where=filters)+ start = 0 if start is None else start+ count = len(results) if count is None else count+ results = results[start : start + count]+ return self.results_to_records(results)diff --git a/memgpt/connectors/db.py b/memgpt/connectors/db.pyindex e2da2f04e..7bb70113d 100644--- a/memgpt/connectors/db.py+++ b/memgpt/connectors/db.py@@ -145,6 +145,15 @@ class PostgresStorageConnector(StorageConnector):self.Session = sessionmaker(bind=self.engine)self.Session().execute(text("CREATE EXTENSION IF NOT EXISTS vector")) # Enables the vector extension+ def get_filters(self, filters: Optional[Dict] = {}):+ if filters is not None:+ filter_conditions = {**self.filters, **filters}+ else:+ filter_conditions = self.filters+ print("FILTERS", filter_conditions)++ return [getattr(self.db_model, key) == value for key, value in filter_conditions.items()]+def get_all_paginated(self, page_size: int, filters: Optional[Dict]) -> Iterator[List[Record]]:session = self.Session()offset = 0diff --git a/memgpt/connectors/local.py b/memgpt/connectors/local.pyindex a47c2f53f..8eb4854e7 100644--- a/memgpt/connectors/local.py+++ b/memgpt/connectors/local.py@@ -5,7 +5,8 @@ import reimport pickleimport os-+import json+import globfrom typing import List, Optional, Dictfrom abc import abstractmethod@@ -17,170 +18,269 @@ from llama_index.schema import TextNodefrom memgpt.constants import MEMGPT_DIRfrom memgpt.data_types import Recordfrom memgpt.config import MemGPTConfig-from memgpt.connectors.storage import StorageConnector, Passage+from memgpt.connectors.storage import StorageConnector, TableTypefrom memgpt.config import AgentConfig, MemGPTConfig---class VectorIndexStorageConnector(StorageConnector):-- """Local storage connector based on LlamaIndex"""-- def __init__(self, name: Optional[str] = None, agent_config: Optional[AgentConfig] = None):- from memgpt.embeddings import embedding_model-- config = MemGPTConfig.load()-- # TODO: add asserts to avoid both being passed- if name is None:- self.name = agent_config.name- self.save_directory = agent_config.save_agent_index_dir()- else:- self.name = name- self.save_directory = f"{MEMGPT_DIR}/archival/{name}"-- # llama index contexts- self.embed_model = embedding_model()- self.service_context = ServiceContext.from_defaults(llm=None, embed_model=self.embed_model, chunk_size=config.embedding_chunk_size)- set_global_service_context(self.service_context)-- # load/create index- self.save_path = f"{self.save_directory}/nodes.pkl"- if os.path.exists(self.save_path):- self.nodes = pickle.load(open(self.save_path, "rb"))- else:- self.nodes = []-- # create vectorindex- if len(self.nodes):- self.index = VectorStoreIndex(self.nodes)- else:- self.index = EmptyIndex()-- def get_nodes(self) -> List[TextNode]:- """Get llama index nodes"""- embed_dict = self.index._vector_store._data.embedding_dict- node_dict = self.index._docstore.docs-- nodes = []- for node_id, node in node_dict.items():- vector = embed_dict[node_id]- node.embedding = vector- nodes.append(TextNode(text=node.text, embedding=vector))- return nodes-- def add_nodes(self, nodes: List[TextNode]):- self.nodes += nodes- self.index = VectorStoreIndex(self.nodes)-- def get_all_paginated(self, page_size: int = 100) -> Iterator[List[Passage]]:- """Get all passages in the index"""- nodes = self.get_nodes()- for i in tqdm(range(0, len(nodes), page_size)):- yield [Passage(text=node.text, embedding=node.embedding) for node in nodes[i : i + page_size]]-- def get_all(self, limit: int) -> List[Passage]:- passages = []- for node in self.get_nodes():- assert node.embedding is not None, f"Node embedding is None"- passages.append(Passage(text=node.text, embedding=node.embedding))- if len(passages) >= limit:- break- return passages-- def get(self, id: str) -> Passage:- pass-- def insert(self, passage: Passage):- nodes = [TextNode(text=passage.text, embedding=passage.embedding)]- self.nodes += nodes- if isinstance(self.index, EmptyIndex):- self.index = VectorStoreIndex(self.nodes, service_context=self.service_context, show_progress=True)- else:- self.index.insert_nodes(nodes)-- def insert_many(self, passages: List[Passage]):- nodes = [TextNode(text=passage.text, embedding=passage.embedding) for passage in passages]- self.nodes += nodes- if isinstance(self.index, EmptyIndex):- self.index = VectorStoreIndex(self.nodes, service_context=self.service_context, show_progress=True)- else:- orig_size = len(self.get_nodes())- self.index.insert_nodes(nodes)- assert len(self.get_nodes()) == orig_size + len(- passages- ), f"expected {orig_size + len(passages)} nodes, got {len(self.get_nodes())} nodes"-- def query(self, query: str, query_vec: List[float], top_k: int = 10) -> List[Passage]:- if isinstance(self.index, EmptyIndex): # empty index- return []- # TODO: this may be super slow?- # the nice thing about creating this here is that now we can save the persistent storage manager- retriever = VectorIndexRetriever(- index=self.index, # does this get refreshed?- similarity_top_k=top_k,- )- nodes = retriever.retrieve(query)- results = [Passage(embedding=node.embedding, text=node.text) for node in nodes]- return results-- def save(self):- # assert len(self.nodes) == len(self.get_nodes()), f"Expected {len(self.nodes)} nodes, got {len(self.get_nodes())} nodes"- self.nodes = self.get_nodes()- os.makedirs(self.save_directory, exist_ok=True)- pickle.dump(self.nodes, open(self.save_path, "wb"))-- @staticmethod- def list_loaded_data():- sources = []- for data_source_file in os.listdir(os.path.join(MEMGPT_DIR, "archival")):- name = os.path.basename(data_source_file)- sources.append(name)- return sources-- def size(self):- return len(self.get_nodes())+from memgpt.utils import printd, get_local_time, parse_formatted_time+from memgpt.data_types import Message, Passage, Record++# class VectorIndexStorageConnector(StorageConnector):++# """Local storage connector based on LlamaIndex"""++# def __init__(self, table_type: str, agent_config: Optional[AgentConfig] = None):+# super().__init__(table_type=table_type, agent_config=agent_config)+# config = MemGPTConfig.load()++## TODO: add asserts to avoid both being passed+# if agent_config is not None:+# self.name = agent_config.name+# self.save_directory = agent_config.save_agent_index_dir()+# else:+# self.name = name+# self.save_directory = f"{MEMGPT_DIR}/archival/{name}"++## llama index contexts+# self.embed_model = embedding_model()+# self.service_context = ServiceContext.from_defaults(llm=None, embed_model=self.embed_model, chunk_size=config.embedding_chunk_size)+# set_global_service_context(self.service_context)++## load/create index+# self.save_path = f"{self.save_directory}/nodes.pkl"+# if os.path.exists(self.save_path):+# self.nodes = pickle.load(open(self.save_path, "rb"))+# else:+# self.nodes = []++## create vectorindex+# if len(self.nodes):+# self.index = VectorStoreIndex(self.nodes)+# else:+# self.index = EmptyIndex()++# def load(self, filters: Dict):+## load correct version based off filters+# if "agent_id" in filters and filters["agent_id"] is not None:+## load agent archival memory+# save_directory = self.agent_config.save_agent_index_dir()+# elif "data_source" in filters and filters["data_source"] is not None:+# name = filters["data_source"]+# save_directory = f"{MEMGPT_DIR}/archival/{name}"+# else:+# raise ValueError(f"Cannot load index without agent_id or data_source {filters}")+# save_path = f"{save_directory}/nodes.pkl"+# if os.path.exists(save_path):+# nodes = pickle.load(open(save_path, "rb"))+# else:+# nodes = []+## create vectorindex+# if len(self.nodes):+# self.index = VectorStoreIndex(self.nodes)+# else:+# self.index = EmptyIndex()+++# def get_nodes(self) -> List[TextNode]:+# """Get llama index nodes"""+# embed_dict = self.index._vector_store._data.embedding_dict+# node_dict = self.index._docstore.docs++# nodes = []+# for node_id, node in node_dict.items():+# vector = embed_dict[node_id]+# node.embedding = vector+# nodes.append(TextNode(text=node.text, embedding=vector))+# return nodes++# def add_nodes(self, nodes: List[TextNode]):+# self.nodes += nodes+# self.index = VectorStoreIndex(self.nodes)++# def get_all_paginated(self, page_size: int = 100) -> Iterator[List[Passage]]:+# """Get all passages in the index"""+# nodes = self.get_nodes()+# for i in tqdm(range(0, len(nodes), page_size)):+# yield [Passage(text=node.text, embedding=node.embedding) for node in nodes[i : i + page_size]]++# def get_all(self, limit: int) -> List[Passage]:+# passages = []+# for node in self.get_nodes():+# assert node.embedding is not None, f"Node embedding is None"+# passages.append(Passage(text=node.text, embedding=node.embedding))+# if len(passages) >= limit:+# break+# return passages++# def get(self, id: str) -> Passage:+# pass++# def insert(self, passage: Passage):+# nodes = [TextNode(text=passage.text, embedding=passage.embedding)]+# self.nodes += nodes+# if isinstance(self.index, EmptyIndex):+# self.index = VectorStoreIndex(self.nodes, service_context=self.service_context, show_progress=True)+# else:+# self.index.insert_nodes(nodes)++# def insert_many(self, passages: List[Passage]):+# nodes = [TextNode(text=passage.text, embedding=passage.embedding) for passage in passages]+# self.nodes += nodes+# if isinstance(self.index, EmptyIndex):+# self.index = VectorStoreIndex(self.nodes, service_context=self.service_context, show_progress=True)+# else:+# orig_size = len(self.get_nodes())+# self.index.insert_nodes(nodes)+# assert len(self.get_nodes()) == orig_size + len(+# passages+# ), f"expected {orig_size + len(passages)} nodes, got {len(self.get_nodes())} nodes"++# def query(self, query: str, query_vec: List[float], top_k: int = 10) -> List[Passage]:+# if isinstance(self.index, EmptyIndex): # empty index+# return []+## TODO: this may be super slow?+## the nice thing about creating this here is that now we can save the persistent storage manager+# retriever = VectorIndexRetriever(+# index=self.index, # does this get refreshed?+# similarity_top_k=top_k,+# )+# nodes = retriever.retrieve(query)+# results = [Passage(embedding=node.embedding, text=node.text) for node in nodes]+# return results++# def save(self):+## assert len(self.nodes) == len(self.get_nodes()), f"Expected {len(self.nodes)} nodes, got {len(self.get_nodes())} nodes"+# self.nodes = self.get_nodes()+# os.makedirs(self.save_directory, exist_ok=True)+# pickle.dump(self.nodes, open(self.save_path, "wb"))++# @staticmethod+# def list_loaded_data():+# sources = []+# for data_source_file in os.listdir(os.path.join(MEMGPT_DIR, "archival")):+# name = os.path.basename(data_source_file)+# sources.append(name)+# return sources++# def size(self):+# return len(self.get_nodes())class InMemoryStorageConnector(StorageConnector):"""Really dumb class so we can have a unified storae connector interface - keeps everything in memory"""+ """ Backwards compatible with previous version of recall memory """+# TODO: maybae replace this with sqllite?def __init__(self, table_type: str, agent_config: Optional[AgentConfig] = None):super().__init__(table_type=table_type, agent_config=agent_config)config = MemGPTConfig.load()- self.rows = []+ # supported table types+ self.supported_types = [TableType.RECALL_MEMORY]+ if table_type not in self.supported_types:+ raise ValueError(f"Table type {table_type} not supported by InMemoryStorageConnector")++ # TODO: load if exists+ if agent_config is None:+ # is a data source+ raise ValueError("Cannot load data source from InMemoryStorageConnector")+ else:+ 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_config.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+ filename = os.path.basename(filename).replace(".json", ".persistence.pickle")+ directory = agent_config.save_persistence_manager_dir()+ printd(f"Loading persistence manager from {os.path.join(directory, filename)}")+ with open(filename, "rb") as f:+ data = pickle.load(f)+ self.rows = data["all_messages"]++ # convert to Record class+ self.rows = [self.json_to_message(m) for m in self.rows]- @abstractmethoddef get_all_paginated(self, page_size: int, filters: Optional[Dict] = {}) -> Iterator[List[Record]]:- pass+ raise NotImplementedError- @abstractmethoddef get_all(self, limit: int, filters: Optional[Dict]) -> List[Record]:- pass+ raise NotImplementedError- @abstractmethoddef get(self, id: str) -> Record:- pass+ raise NotImplementedError- @abstractmethoddef insert(self, record: Record):self.rows.append(record)- @abstractmethoddef insert_many(self, records: List[Record]):self.rows += records- @abstractmethoddef query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[Record]:- pass+ raise NotImplementedError++ def json_to_message(self, message_json) -> Message:+ """Convert agent message JSON into Message object"""+ timestamp = message_json["timestamp"]+ message = message_json["message"]++ return Message(+ user_id=self.config.anon_clientid,+ agent_id=self.agent_config.name,+ role=message["role"],+ 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,+ id=message["id"] if "id" in message else None,+ )++ def message_to_json(self, message: Message) -> Dict:+ """Convert Message object into JSON"""+ return {+ "timestamp": message.created_at.strftime("%Y-%m-%d %H:%M:%S %Z%z"),+ "message": {+ "role": message.role,+ "content": message.text,+ "function_name": message.function_name,+ "function_args": message.function_args,+ "function_response": message.function_response,+ "id": message.id,+ },+ }- @abstractmethoddef save(self):"""Save state of storage connector"""- pass+ timestamp = get_local_time().replace(" ", "_").replace(":", "_")+ filename = f"{timestamp}.persistence.pickle"+ os.makedirs(self.config.save_persistence_manager_dir(), exist_ok=True)+ filename = os.path.join(self.config.save_persistence_manager_dir(), filename)++ all_messages = [self.message_to_json(m) for m in self.rows]++ with open(filename, "wb") as fh:+ ## TODO: fix this hacky solution to pickle the retriever+ pickle.dump(+ {+ "all_messages": all_messages,+ },+ fh,+ protocol=pickle.HIGHEST_PROTOCOL,+ )+ printd(f"Saved state to {fh}")- @abstractmethoddef size(self, filters: Optional[Dict] = {}) -> int:- pass+ return len(self.rows)++ def query_date(self, start_date, end_date) -> List[Record]:+ return [row for row in self.rows if row.created_at >= start_date and row.created_at <= end_date]++ def query_text(self, query: str) -> List[Record]:+ return [row for row in self.rows if row.role not in ["system", "function"] and query.lower() in row.text.lower()]diff --git a/memgpt/connectors/storage.py b/memgpt/connectors/storage.pyindex 61f666a51..20b790ad5 100644--- a/memgpt/connectors/storage.py+++ b/memgpt/connectors/storage.py@@ -69,6 +69,7 @@ class StorageConnector:else:filter_conditions = self.filtersprint("FILTERS", filter_conditions)+ return filter_conditionsreturn [getattr(self.db_model, key) == value for key, value in filter_conditions.items()]def generate_table_name(self, agent_config: AgentConfig, table_type: TableType):@@ -139,6 +140,11 @@ class StorageConnector:return PostgresStorageConnector(agent_config=agent_config, table_type=TableType.RECALL_MEMORY)+ elif storage_type == "chroma":+ from memgpt.connectors.chroma import ChromaStorageConnector++ return ChromaStorageConnector(agent_config=agent_config, table_type=TableType.RECALL_MEMORY)+else:raise NotImplementedError(f"Storage type {storage_type} not implemented")diff --git a/memgpt/data_types.py b/memgpt/data_types.pyindex 08c1e11fc..fd6ab5c6e 100644--- a/memgpt/data_types.py+++ b/memgpt/data_types.py@@ -36,6 +36,7 @@ class Message(Record):role: str,text: str,model: str, # model used to make function call+ user: Optional[str] = None, # optional participant namecreated_at: Optional[str] = None,function_name: Optional[str] = None, # name of function calledfunction_args: Optional[str] = None, # args of function called@@ -44,10 +45,13 @@ class Message(Record):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)self.created_at = created_at+ # openai info+ self.role = role # role (agent/user/function)+ self.user = user+# function call info (optional)self.function_name = function_nameself.function_args = function_argsdiff --git a/memgpt/utils.py b/memgpt/utils.pyindex f3b8c39fb..cf101fe14 100644--- a/memgpt/utils.py+++ b/memgpt/utils.py@@ -84,6 +84,21 @@ def united_diff(str1, str2):return "".join(diff)+def parse_formatted_time(formatted_time):+ # parse times returned by memgpt.utils.get_formatted_time()+ return datetime.strptime(formatted_time, "%Y-%m-%d %I:%M:%S %p %Z%z")+++def datetime_to_timestamp(dt):+ # convert datetime object to integer timestamp+ return int(dt.timestamp())+++def timestamp_to_datetime(ts):+ # convert integer timestamp to datetime object+ return datetime.fromtimestamp(ts)++def get_local_time_military():# Get the current time in UTCcurrent_time_utc = datetime.now(pytz.utc)