Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
refactor: fix typing errors (pyright) (#855)
Charles Packer037cc16e32ec
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 6496cb985..879ae918f 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -6,7 +6,7 @@ import osimport jsonfrom pathlib import Pathimport traceback-from typing import List, Tuple+from typing import List, Tuple, Optional, castfrom box import Box@@ -170,9 +170,9 @@ class Agent(object):agent_state: AgentState,interface: AgentInterface,# extras- messages_total=None, # TODO remove?- first_message_verify_mono=True, # TODO move to config?- memgpt_config: MemGPTConfig = None,+ messages_total: Optional[int] = None, # TODO remove?+ first_message_verify_mono: bool = True, # TODO move to config?+ memgpt_config: Optional[MemGPTConfig] = None,):# Hold a copy of the state that was used to init the agentself.agent_state = agent_state@@ -233,6 +233,8 @@ class Agent(object):# Initialize connection to metedata store# self.ms = MetadataStore(self.memgpt_config)+ self._messages: List[Message] = []+# Once the memory object is initialized, use it to "bake" the system messageif "messages" in agent_state.state and agent_state.state["messages"] is not None:# print(f"Agent.__init__ :: loading, state={agent_state.state['messages']}")@@ -241,10 +243,12 @@ class Agent(object):assert all([isinstance(msg, str) for msg in agent_state.state["messages"]])# Convert to IDs, and pull from the database- self._messages = [- self.persistence_manager.recall_memory.storage.get(uuid.UUID(msg_id)) for msg_id in agent_state.state["messages"]+ raw_messages = [+ self.persistence_manager.recall_memory.storage.get(id=uuid.UUID(msg_id)) for msg_id in agent_state.state["messages"]]- assert all([isinstance(msg, Message) for msg in self._messages]), (self._messages, agent_state.state["messages"])+ assert all([isinstance(msg, Message) for msg in raw_messages]), (raw_messages, agent_state.state["messages"])+ self._messages.extend([cast(Message, msg) for msg in raw_messages if msg is not None])+else:# print(f"Agent.__init__ :: creating, state={agent_state.state['messages']}")init_messages = initialize_message_sequence(@@ -259,11 +263,9 @@ class Agent(object):agent_id=self.agent_state.id, user_id=self.agent_state.user_id, model=self.model, openai_message_dict=msg))- self._messages = []+ assert all([isinstance(msg, Message) for msg in init_messages_objs]), (init_messages_objs, init_messages)self.messages_total = 0- self._append_to_messages(added_messages=init_messages_objs)-- assert all([isinstance(msg, Message) for msg in self._messages]), (self._messages, init_messages)+ self._append_to_messages(added_messages=[cast(Message, msg) for msg in init_messages_objs if msg is not None])# Keep track of the total number of messages throughout all timeself.messages_total = messages_total if messages_total is not None else (len(self._messages) - 1) # (-system)@@ -288,7 +290,7 @@ class Agent(object):"""Trim messages from the front, not including the system message"""self.persistence_manager.trim_messages(num)- new_messages = [self.messages[0]] + self.messages[num:]+ new_messages = [self._messages[0]] + self._messages[num:]self._messages = new_messagesdef _prepend_to_messages(self, added_messages: List[Message]):@@ -297,7 +299,7 @@ class Agent(object):self.persistence_manager.prepend_to_messages(added_messages)- new_messages = [self.messages[0]] + added_messages + self.messages[1:] # prepend (no system)+ new_messages = [self._messages[0]] + added_messages + self._messages[1:] # prepend (no system)self._messages = new_messagesself.messages_total += len(added_messages) # still should increment the message counter (summaries are additions too)@@ -382,6 +384,7 @@ class Agent(object):raise DeprecationWarning(response_message)if response_message.tool_calls is not None and len(response_message.tool_calls) > 1:raise NotImplementedError(f">1 tool call not supported")+ assert response_message.tool_calls is not None and len(response_message.tool_calls) > 0# The content if then internal monologue, not chatself.interface.internal_monologue(response_message.content)@@ -437,14 +440,14 @@ class Agent(object):)) # 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+ return messages, False, True # force a heartbeat to allow agent to handle error# Failure case 2: function name is OK, but function args are bad JSONtry:raw_function_args = function_call.argumentsfunction_args = parse_json(raw_function_args)except Exception as e:- error_msg = f"Error parsing JSON for function '{function_name}' arguments: {raw_function_args}"+ error_msg = f"Error parsing JSON for function '{function_name}' arguments: {function_call.arguments}"function_response = package_function_response(False, error_msg)messages.append(Message.dict_to_message(@@ -460,7 +463,7 @@ class Agent(object):)) # 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+ return messages, False, True # force a heartbeat to allow agent to handle error# (Still parsing function args)# Handle requests for immediate heartbeat@@ -469,7 +472,7 @@ class Agent(object):printd(f"{CLI_WARNING_PREFIX}'request_heartbeat' arg parsed was not a bool or None, type={type(heartbeat_request)}, value={heartbeat_request}")- heartbeat_request = None+ heartbeat_request = False# Failure case 3: function failed during executionself.interface.function_message(f"Running {function_name}({function_args})")@@ -516,7 +519,7 @@ class Agent(object):)) # 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+ return messages, False, True # force a heartbeat to allow agent to handle error# If no failures happened along the way: ...# Step 4: send the info on the function call and function response to GPT@@ -546,12 +549,18 @@ class Agent(object):openai_message_dict=response_message.model_dump(),)) # extend conversation with assistant's reply- heartbeat_request = None- function_failed = None+ heartbeat_request = False+ function_failed = Falsereturn messages, heartbeat_request, function_failed- def step(self, user_message, first_message=False, first_message_retry_limit=FIRST_MESSAGE_ATTEMPTS, skip_verify=False):+ def step(+ self,+ user_message: Optional[str], # NOTE: should be json.dump(dict)+ first_message: bool = False,+ first_message_retry_limit: int = FIRST_MESSAGE_ATTEMPTS,+ skip_verify: bool = False,+ ) -> Tuple[List[dict], bool, bool, bool]:"""Top-level event message handler for the MemGPT agent"""try:@@ -581,8 +590,10 @@ class Agent(object):)input_message_sequence = self.messages + [packed_user_message]+ # Alternatively, the requestor can send an empty user messageelse:input_message_sequence = self.messages+ packed_user_message = Noneif len(input_message_sequence) > 1 and input_message_sequence[-1]["role"] != "user":printd(f"{CLI_WARNING_PREFIX}Attempting to run ChatCompletion without user as the last message in the queue")@@ -641,9 +652,7 @@ class Agent(object):print(f"{CLI_WARNING_PREFIX}could not find context_window in config, setting to default {LLM_MAX_TOKENS['DEFAULT']}")print(f"{self.agent_state}")self.agent_state.llm_config.context_window = (- str(LLM_MAX_TOKENS[self.model])- if (self.model is not None and self.model in LLM_MAX_TOKENS)- else str(LLM_MAX_TOKENS["DEFAULT"])+ LLM_MAX_TOKENS[self.model] if (self.model is not None and self.model in LLM_MAX_TOKENS) else LLM_MAX_TOKENS["DEFAULT"])if current_total_tokens > MESSAGE_SUMMARY_WARNING_FRAC * int(self.agent_state.llm_config.context_window):printd(@@ -740,9 +749,7 @@ class Agent(object):print(f"{CLI_WARNING_PREFIX}could not find context_window in config, setting to default {LLM_MAX_TOKENS['DEFAULT']}")print(f"{self.agent_state}")self.agent_state.llm_config.context_window = (- str(LLM_MAX_TOKENS[self.model])- if (self.model is not None and self.model in LLM_MAX_TOKENS)- else str(LLM_MAX_TOKENS["DEFAULT"])+ LLM_MAX_TOKENS[self.model] if (self.model is not None and self.model in LLM_MAX_TOKENS) else LLM_MAX_TOKENS["DEFAULT"])summary = summarize_messages(agent_state=self.agent_state, message_sequence_to_summarize=message_sequence_to_summarize)printd(f"Got summary: {summary}")diff --git a/memgpt/agent_store/chroma.py b/memgpt/agent_store/chroma.pyindex 8b7986714..8b76e83cf 100644--- a/memgpt/agent_store/chroma.py+++ b/memgpt/agent_store/chroma.py@@ -1,12 +1,15 @@-import chromadbimport uuidimport jsonimport re-from typing import Optional, List, Iterator, Dict+from typing import Optional, List, Iterator, Dict, Tuple, cast, Type++import chromadb+from chromadb.api.types import Include, GetResult+from memgpt.agent_store.storage import StorageConnector, TableTypefrom memgpt.utils import printd, datetime_to_timestamp, timestamp_to_datetimefrom memgpt.config import MemGPTConfig-from memgpt.data_types import Record, Message, Passage+from memgpt.data_types import Record, Message, Passage, RecordTypeclass ChromaStorageConnector(StorageConnector):@@ -31,12 +34,12 @@ 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 = ["documents", "embeddings", "metadatas"]+ self.include: Include = ["documents", "embeddings", "metadatas"]# need to be converted to stringsself.uuid_fields = ["id", "user_id", "agent_id", "source_id"]- def get_filters(self, filters: Optional[Dict] = {}):+ def get_filters(self, filters: Optional[Dict] = {}) -> Tuple[list, dict]:# get all filters for queryif filters is not None:filter_conditions = {**self.filters, **filters}@@ -66,13 +69,14 @@ class ChromaStorageConnector(StorageConnector):chroma_filters = chroma_filters[0]return ids, chroma_filters- def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: Optional[int] = 1000, offset=0) -> Iterator[List[Record]]:+ def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: int = 1000, offset: int = 0) -> Iterator[List[RecordType]]:ids, filters = self.get_filters(filters)while True:# Retrieve a chunk of records with the given page_sizeresults = self.collection.get(ids=ids, offset=offset, limit=page_size, include=self.include, where=filters)# If the chunk is empty, we've retrieved all records+ assert results["embeddings"] is not None, f"results['embeddings'] was None"if len(results["embeddings"]) == 0:break@@ -82,7 +86,7 @@ class ChromaStorageConnector(StorageConnector):# Increment the offset to get the next chunk in the next iterationoffset += page_size- def results_to_records(self, results):+ def results_to_records(self, results) -> List[RecordType]:# convert timestamps to datetimefor metadata in results["metadatas"]:if "created_at" in metadata:@@ -92,7 +96,7 @@ class ChromaStorageConnector(StorageConnector):metadata[key] = uuid.UUID(value)if results["embeddings"]: # may not be returned, depending on table typereturn [- self.type(text=text, embedding=embedding, id=uuid.UUID(record_id), **metadatas)+ cast(RecordType, self.type(text=text, embedding=embedding, id=uuid.UUID(record_id), **metadatas)) # type: ignorefor (text, record_id, embedding, metadatas) in zip(results["documents"], results["ids"], results["embeddings"], results["metadatas"])@@ -100,11 +104,11 @@ class ChromaStorageConnector(StorageConnector):else:# no embeddingsreturn [- self.type(text=text, id=uuid.UUID(id), **metadatas)+ cast(RecordType, self.type(text=text, id=uuid.UUID(id), **metadatas)) # type: ignorefor (text, id, metadatas) in zip(results["documents"], results["ids"], results["metadatas"])]- def get_all(self, filters: Optional[Dict] = {}, limit=None) -> List[Record]:+ def get_all(self, filters: Optional[Dict] = {}, limit=None) -> List[RecordType]:ids, filters = self.get_filters(filters)if self.collection.count() == 0:return []@@ -114,20 +118,22 @@ class ChromaStorageConnector(StorageConnector):results = self.collection.get(ids=ids, include=self.include, where=filters)return self.results_to_records(results)- def get(self, id: str) -> Optional[Record]:+ def get(self, id: uuid.UUID) -> Optional[RecordType]:results = self.collection.get(ids=[str(id)])if len(results["ids"]) == 0:return Nonereturn self.results_to_records(results)[0]- def format_records(self, records: List[Record]):+ def format_records(self, records: List[RecordType]):+ assert all([isinstance(r, Passage) for r in records])+ recs = [cast(Passage, r) for r in records]metadatas = []- ids = [str(record.id) for record in records]- documents = [record.text for record in records]- embeddings = [record.embedding for record in records]+ ids = [str(record.id) for record in recs]+ documents = [record.text for record in recs]+ embeddings = [record.embedding for record in recs]# collect/format record metadata- for record in records:+ for record in recs:metadata = vars(record)metadata.pop("id")metadata.pop("text")@@ -151,15 +157,15 @@ class ChromaStorageConnector(StorageConnector):def insert(self, record: Record):ids, documents, embeddings, metadatas = self.format_records([record])- if not any(embeddings):+ if any([e is None for e in embeddings]):raise ValueError("Embeddings must be provided to chroma")- self.collection.add(documents=documents, embeddings=embeddings, ids=ids, metadatas=metadatas)+ self.collection.add(documents=documents, embeddings=[e for e in embeddings if e is not None], ids=ids, metadatas=metadatas)- def insert_many(self, records: List[Record], show_progress=False):+ def insert_many(self, records: List[RecordType], show_progress=False):ids, documents, embeddings, metadatas = self.format_records(records)- if not any(embeddings):+ if any([e is None for e in embeddings]):raise ValueError("Embeddings must be provided to chroma")- self.collection.add(documents=documents, embeddings=embeddings, ids=ids, metadatas=metadatas)+ self.collection.add(documents=documents, embeddings=[e for e in embeddings if e is not None], ids=ids, metadatas=metadatas)def delete(self, filters: Optional[Dict] = {}):ids, filters = self.get_filters(filters)@@ -181,7 +187,7 @@ class ChromaStorageConnector(StorageConnector):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]:+ def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[RecordType]:ids, filters = self.get_filters(filters)results = self.collection.query(query_embeddings=[query_vec], n_results=top_k, include=self.include, where=filters)@@ -189,8 +195,9 @@ class ChromaStorageConnector(StorageConnector):flattened_results = {}for key, value in results.items():if value:- flattened_results[key] = value[0]- assert len(value) == 1, f"Value is size {len(value)}: {value}"+ # value is an Optional[List] type according to chromadb.api.types+ flattened_results[key] = value[0] # type: ignore+ assert len(value) == 1, f"Value is size {len(value)}: {value}" # type: ignoreelse:flattened_results[key] = valuediff --git a/memgpt/agent_store/db.py b/memgpt/agent_store/db.pyindex 87fefe0c0..1d3495f60 100644--- a/memgpt/agent_store/db.py+++ b/memgpt/agent_store/db.py@@ -21,8 +21,8 @@ from memgpt.config import MemGPTConfigfrom memgpt.agent_store.storage import StorageConnector, TableTypefrom memgpt.config import MemGPTConfigfrom memgpt.utils import printd+from memgpt.data_types import Record, Message, Passage, ToolCall, RecordTypefrom memgpt.constants import MAX_EMBEDDING_DIM-from memgpt.data_types import Record, Message, Passage, ToolCallfrom memgpt.metadata import MetadataStorefrom datetime import datetime@@ -252,7 +252,7 @@ class SQLStorageConnector(StorageConnector):all_filters = [getattr(self.db_model, key) == value for key, value in filter_conditions.items()]return all_filters- def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: Optional[int] = 1000, offset=0) -> Iterator[List[Record]]:+ def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: Optional[int] = 1000, offset=0) -> Iterator[List[RecordType]]:filters = self.get_filters(filters)while True:# Retrieve a chunk of records with the given page_size@@ -321,7 +321,7 @@ class SQLStorageConnector(StorageConnector):# return (cursor, list[records])return (next_cursor, records)- def get_all(self, filters: Optional[Dict] = {}, limit=None) -> List[Record]:+ def get_all(self, filters: Optional[Dict] = {}, limit=None) -> List[RecordType]:filters = self.get_filters(filters)with self.session_maker() as session:if limit:@@ -349,7 +349,7 @@ class SQLStorageConnector(StorageConnector):session.add(db_record)session.commit()- def insert_many(self, records: List[Record], show_progress=False):+ def insert_many(self, records: List[RecordType], show_progress=False):iterable = tqdm(records) if show_progress else recordswith self.session_maker() as session:for record in iterable:@@ -357,7 +357,7 @@ class SQLStorageConnector(StorageConnector):session.add(db_record)session.commit()- def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[Record]:+ def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[RecordType]:raise NotImplementedError("Vector query not implemented for SQLStorageConnector")def save(self):@@ -452,7 +452,7 @@ class PostgresStorageConnector(SQLStorageConnector):with self.session_maker() as session:session.execute(text("CREATE EXTENSION IF NOT EXISTS vector")) # Enables the vector extension- def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[Record]:+ def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[RecordType]:filters = self.get_filters(filters)with self.session_maker() as session:results = session.scalars(diff --git a/memgpt/agent_store/lancedb.py b/memgpt/agent_store/lancedb.pyindex 2c3fcadf4..2a69f33c9 100644--- a/memgpt/agent_store/lancedb.py+++ b/memgpt/agent_store/lancedb.py@@ -1,3 +1,5 @@+# type: ignore+import lancedbimport uuidfrom datetime import datetime@@ -149,7 +151,7 @@ class LanceDBConnector(StorageConnector):pass@abstractmethod- def get(self, id: str) -> Optional[Record]:+ def get(self, id: uuid.UUID) -> Optional[Record]:# TODOpassdiff --git a/memgpt/agent_store/storage.py b/memgpt/agent_store/storage.pyindex 87414672b..37ba434bd 100644--- a/memgpt/agent_store/storage.py+++ b/memgpt/agent_store/storage.py@@ -2,10 +2,11 @@We originally tried to use Llama Index VectorIndex, but their limited API was extremely problematic."""-from typing import Any, Optional, List, Iterator+from typing import Any, Optional, List, Iterator, Union, Tuple, Typeimport reimport pickleimport os+import uuidfrom abc import abstractmethodfrom typing import List, Optional, Dict@@ -13,7 +14,7 @@ from tqdm import tqdmfrom memgpt.config import MemGPTConfig-from memgpt.data_types import Record, Passage, Document, Message, Source+from memgpt.data_types import Record, Passage, Document, Message, Source, RecordTypefrom memgpt.utils import printd@@ -40,7 +41,15 @@ DOCUMENT_TABLE_NAME = "memgpt_documents" # original documents (from source)class StorageConnector:"""Defines a DB connection that is user-specific to access data: Documents, Passages, Archival/Recall Memory"""- def __init__(self, table_type: TableType, config: MemGPTConfig, user_id, agent_id=None):+ type: Type[Record]++ def __init__(+ self,+ table_type: Union[TableType.ARCHIVAL_MEMORY, TableType.RECALL_MEMORY, TableType.PASSAGES, TableType.DOCUMENTS],+ config: MemGPTConfig,+ user_id,+ agent_id=None,+ ):self.user_id = user_idself.agent_id = agent_idself.table_type = table_type@@ -74,16 +83,13 @@ class StorageConnector:else:raise ValueError(f"Table type {table_type} not implemented")- def get_filters(self, filters: Optional[Dict] = {}):- # get all filters for query- if filters is not None:- filter_conditions = {**self.filters, **filters}- else:- filter_conditions = self.filters- return filter_conditions-@staticmethod- def get_storage_connector(table_type: TableType, config: MemGPTConfig, user_id, agent_id=None):+ def get_storage_connector(+ table_type: Union[TableType.ARCHIVAL_MEMORY, TableType.RECALL_MEMORY, TableType.PASSAGES, TableType.DOCUMENTS],+ config: MemGPTConfig,+ user_id,+ agent_id=None,+ ):if table_type == TableType.ARCHIVAL_MEMORY or table_type == TableType.PASSAGES:storage_type = config.archival_storage_typeelif table_type == TableType.RECALL_MEMORY:@@ -125,19 +131,19 @@ class StorageConnector:return StorageConnector.get_storage_connector(TableType.RECALL_MEMORY, config, user_id, agent_id)@abstractmethod- def get_filters(self, filters: Optional[Dict] = {}):+ def get_filters(self, filters: Optional[Dict] = {}) -> Union[Tuple[list, dict], dict]:pass@abstractmethod- def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: Optional[int] = 1000) -> Iterator[List[Record]]:+ def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: int = 1000) -> Iterator[List[RecordType]]:pass@abstractmethod- def get_all(self, filters: Optional[Dict] = {}, limit=10) -> List[Record]:+ def get_all(self, filters: Optional[Dict] = {}, limit=10) -> List[RecordType]:pass@abstractmethod- def get(self, id: str) -> Optional[Record]:+ def get(self, id: uuid.UUID) -> Optional[RecordType]:pass@abstractmethod@@ -145,15 +151,15 @@ class StorageConnector:pass@abstractmethod- def insert(self, record: Record):+ def insert(self, record: RecordType):pass@abstractmethod- def insert_many(self, records: List[Record], show_progress=False):+ def insert_many(self, records: List[RecordType], show_progress=False):pass@abstractmethod- def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[Record]:+ def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[RecordType]:pass@abstractmethoddiff --git a/memgpt/cli/cli.py b/memgpt/cli/cli.pyindex 83cceaebe..36a35dbac 100644--- a/memgpt/cli/cli.py+++ b/memgpt/cli/cli.py@@ -28,7 +28,7 @@ from memgpt.constants import MEMGPT_DIR, CLI_WARNING_PREFIX, JSON_ENSURE_ASCIIfrom memgpt.agent import Agentfrom memgpt.embeddings import embedding_modelfrom memgpt.server.constants import WS_DEFAULT_PORT, REST_DEFAULT_PORT-from memgpt.data_types import AgentState, LLMConfig, EmbeddingConfig, User+from memgpt.data_types import AgentState, LLMConfig, EmbeddingConfig, User, Passagefrom memgpt.metadata import MetadataStore, save_agentfrom memgpt.migrate import migrate_all_agents, migrate_all_sources@@ -325,19 +325,21 @@ def server(# Run the commandtyper.secho(f"Running WS (websockets) server: {command} (inside {server_directory})")+ process = Nonetry:# Start the subprocess in a new sessionprocess = subprocess.Popen(command, shell=True, start_new_session=True, cwd=server_directory)process.wait()except KeyboardInterrupt:# Handle CTRL-C- typer.secho("Terminating the server...")- process.terminate()- try:- process.wait(timeout=5)- except subprocess.TimeoutExpired:- process.kill()- typer.secho("Server terminated with kill()")+ if process is not None:+ typer.secho("Terminating the server...")+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ typer.secho("Server terminated with kill()")sys.exit(0)@@ -463,11 +465,6 @@ def run(ms = MetadataStore(config)user = create_default_user_or_exit(config, ms)- # override with command line arguments- if debug:- config.debug = debug- if no_verify:- config.no_verify = no_verify# determine agent to use, if not providedif not yes and not agent:agents = ms.list_agents(user_id=user.id)@@ -482,10 +479,11 @@ def run(agent = questionary.select("Select agent:", choices=agents).ask()# create agent config- if agent and ms.get_agent(agent_name=agent, user_id=user.id): # use existing agent+ agent_state = ms.get_agent(agent_name=agent, user_id=user.id) if agent else None+ if agent and agent_state: # use existing agenttyper.secho(f"\n🔁 Using existing agent {agent}", fg=typer.colors.GREEN)# agent_config = AgentConfig.load(agent)- agent_state = ms.get_agent(agent_name=agent, user_id=user.id)+ # agent_state = ms.get_agent(agent_name=agent, user_id=user_id)printd("Loading agent state:", agent_state.id)printd("Agent state:", agent_state.state)# printd("State path:", agent_config.save_state_dir())@@ -537,7 +535,7 @@ def run(ms.update_agent(agent_state)# create agent- memgpt_agent = Agent(agent_state, interface=interface)+ memgpt_agent = Agent(agent_state, interface=interface())else: # create new agent# create new agent config: override defaults with args if provided@@ -605,7 +603,7 @@ def run(try:memgpt_agent = presets.create_agent_from_preset(agent_state=agent_state,- interface=interface,+ interface=interface(),)save_agent(agent=memgpt_agent, ms=ms)except ValueError as e:@@ -690,7 +688,7 @@ def delete_agent(def attach(agent_name: Annotated[str, typer.Option(help="Specify agent to attach data to")],- data_source: Annotated[str, typer.Option(help="Data source to attach to avent")],+ data_source: Annotated[str, typer.Option(help="Data source to attach to agent")],user_id: uuid.UUID = None,):# use client ID is no user_id provided@@ -704,7 +702,7 @@ def attach(ms = MetadataStore(config)agent = ms.get_agent(agent_name=agent_name, user_id=user_id)- print(agent.id, agent.user_id, user_id)+ assert agent is not None, f"No agent found under agent_name={agent_name}, user_id={user_id}"source = ms.get_source(source_name=data_source, user_id=user_id)assert source is not None, f"Source {data_source} does not exist for user {user_id}"@@ -723,6 +721,7 @@ def attach(# need to associated passage with agent (for filtering)for passage in passages:+ assert isinstance(passage, Passage), f"Generate yielded bad non-Passage type: {type(passage)}"passage.agent_id = agent.id# insert into agent archival memory@@ -735,7 +734,9 @@ def attach(dest_storage.save()# attach to agent- source_id = ms.get_source(source_name=data_source, user_id=user_id).id+ source = ms.get_source(source_name=data_source, user_id=user_id)+ assert source is not None, f"source does not exist for source_name={data_source}, user_id={user_id}"+ source_id = source.idms.attach_source(agent_id=agent.id, source_id=source_id, user_id=user_id)total_agent_passages = dest_storage.size()diff --git a/memgpt/cli/cli_config.py b/memgpt/cli/cli_config.pyindex 2b2cc32cd..c7fc35ca5 100644--- a/memgpt/cli/cli_config.py+++ b/memgpt/cli/cli_config.py@@ -2,7 +2,7 @@ import builtinsimport osimport shutilimport uuid-from typing import Annotated, Optional+from typing import Annotated, Tuple, Optionalfrom enum import Enumfrom typing import Annotated@@ -21,6 +21,9 @@ from memgpt.data_types import User, LLMConfig, EmbeddingConfigfrom memgpt.llm_api_tools import openai_get_model_list, azure_openai_get_model_list, smart_urljoinfrom memgpt.local_llm.constants import DEFAULT_ENDPOINTS, DEFAULT_OLLAMA_MODEL, DEFAULT_WRAPPER_NAMEfrom memgpt.local_llm.utils import get_available_wrappers+from memgpt.llm_api_tools import openai_get_model_list, azure_openai_get_model_list, smart_urljoin+from memgpt.server.utils import shorten_key_middle+from memgpt.data_types import User, LLMConfig, EmbeddingConfig, Sourcefrom memgpt.metadata import MetadataStorefrom memgpt.server.utils import shorten_key_middle@@ -183,15 +186,16 @@ def configure_model(config: MemGPTConfig, credentials: MemGPTCredentials, model_if model_endpoint_type == "openai" or model_endpoint_type == "azure":# Get the model list from the openai / azure endpointhardcoded_model_options = ["gpt-4", "gpt-4-32k", "gpt-4-1106-preview", "gpt-3.5-turbo", "gpt-3.5-turbo-16k"]- fetched_model_options = None+ fetched_model_options = []try:if model_endpoint_type == "openai":- fetched_model_options = openai_get_model_list(url=model_endpoint, api_key=credentials.openai_key)+ fetched_model_options_response = openai_get_model_list(url=model_endpoint, api_key=credentials.openai_key)elif model_endpoint_type == "azure":- fetched_model_options = azure_openai_get_model_list(+ assert credentials.azure_version is not None, f"Missing azure_version"+ fetched_model_options_response = azure_openai_get_model_list(url=model_endpoint, api_key=credentials.azure_key, api_version=credentials.azure_version)- fetched_model_options = [obj["id"] for obj in fetched_model_options["data"] if obj["id"].startswith("gpt-")]+ fetched_model_options = [obj["id"] for obj in fetched_model_options_response["data"] if obj["id"].startswith("gpt-")]except:# NOTE: if this fails, it means the user's key is probably badtyper.secho(@@ -345,30 +349,30 @@ def configure_model(config: MemGPTConfig, credentials: MemGPTCredentials, model_str(2**18), # 262144"custom", # enter yourself]- context_window = questionary.select(+ context_window_input = questionary.select("Select your model's context window (for Mistral 7B models, this is probably 8k / 8192):",choices=context_length_options,default=str(LLM_MAX_TOKENS["DEFAULT"]),).ask()- if context_window is None:+ if context_window_input is None:raise KeyboardInterrupt# If custom, ask for input- if context_window == "custom":+ if context_window_input == "custom":while True:- context_window = questionary.text("Enter context window (e.g. 8192)").ask()- if context_window is None:+ context_window_input = questionary.text("Enter context window (e.g. 8192)").ask()+ if context_window_input is None:raise KeyboardInterrupttry:- context_window = int(context_window)+ context_window = int(context_window_input)breakexcept ValueError:print(f"Context window must be a valid integer")else:- context_window = int(context_window)+ context_window = int(context_window_input)else:# Pull the context length from the models- context_window = LLM_MAX_TOKENS[model]+ context_window = int(LLM_MAX_TOKENS[str(model)])return model, model_wrapper, context_window@@ -578,8 +582,8 @@ def configure():model, model_wrapper, context_window = configure_model(config=config,credentials=credentials,- model_endpoint_type=model_endpoint_type,- model_endpoint=model_endpoint,+ model_endpoint_type=str(model_endpoint_type),+ model_endpoint=str(model_endpoint),)embedding_endpoint_type, embedding_endpoint, embedding_dim, embedding_model = configure_embedding_endpoint(config=config,@@ -623,7 +627,6 @@ def configure():preset=default_preset,persona=default_persona,human=default_human,- agent=default_agent,# storagearchival_storage_type=archival_storage_type,archival_storage_uri=archival_storage_uri,@@ -673,7 +676,10 @@ def list(arg: Annotated[ListChoice, typer.Argument]):table.field_names = ["Name", "LLM Model", "Embedding Model", "Embedding Dim", "Persona", "Human", "Data Source", "Create Time"]for agent in tqdm(ms.list_agents(user_id=user_id)):source_ids = ms.list_attached_sources(agent_id=agent.id)- source_names = [ms.get_source(source_id=source_id).name for source_id in source_ids]+ assert all([source_id is not None and isinstance(source_id, uuid.UUID) for source_id in source_ids])+ sources = [ms.get_source(source_id=source_id) for source_id in source_ids]+ assert all([source is not None and isinstance(source, Source)] for source in sources)+ source_names = [source.name for source in sources if source is not None]table.add_row([agent.name,@@ -720,7 +726,8 @@ def list(arg: Annotated[ListChoice, typer.Argument]):for source in ms.list_sources(user_id=user_id):# get attached agentsagent_ids = ms.list_attached_agents(source_id=source.id)- agent_names = [ms.get_agent(agent_id=agent_id).name for agent_id in agent_ids]+ agent_states = [ms.get_agent(agent_id=agent_id) for agent_id in agent_ids]+ agent_names = [agent_state.name for agent_state in agent_states if agent_state is not None]table.add_row([source.name, source.embedding_model, source.embedding_dim, utils.format_datetime(source.created_at), ",".join(agent_names)]@@ -772,6 +779,7 @@ def delete(option: str, name: str):if option == "source":# delete metadatasource = ms.get_source(source_name=name, user_id=user_id)+ assert source is not None, f"Source {name} does not exist"ms.delete_source(source_id=source.id)# delete from passages@@ -785,6 +793,7 @@ def delete(option: str, name: str):# TODO: should we also delete from agents?elif option == "agent":agent = ms.get_agent(agent_name=name, user_id=user_id)+ assert agent is not None, f"Agent {name} for user_id {user_id} does not exist"# recall memoryrecall_conn = StorageConnector.get_storage_connector(TableType.RECALL_MEMORY, config, user_id=user_id, agent_id=agent.id)diff --git a/memgpt/cli/cli_load.py b/memgpt/cli/cli_load.pyindex 23c3f23ba..ba4b31c90 100644--- a/memgpt/cli/cli_load.py+++ b/memgpt/cli/cli_load.py@@ -13,12 +13,13 @@ from tqdm import tqdmimport numpy as npimport typerimport uuid+from memgpt.embeddings import embedding_model, check_and_split_textfrom memgpt.agent_store.storage import StorageConnectorfrom memgpt.config import MemGPTConfigfrom memgpt.metadata import MetadataStorefrom memgpt.data_types import Source, Passage, Document, User-from memgpt.utils import get_local_time, suppress_stdout+from memgpt.utils import get_utc_time, suppress_stdoutfrom memgpt.agent_store.storage import StorageConnector, TableTypefrom datetime import datetime@@ -43,7 +44,7 @@ def insert_passages_into_source(passages: List[Passage], source_name: str, user_source = ms.get_source(user_id=user_id, source_name=source_name)if not source:# create new- source = Source(user_id=user_id, name=source_name, created_at=get_local_time())+ source = Source(user_id=user_id, name=source_name, created_at=get_utc_time())ms.create_source(source)# make sure user_id is set for passages@@ -55,32 +56,7 @@ def insert_passages_into_source(passages: List[Passage], source_name: str, user_# add and save all passagesstorage.insert_many(passages)- assert orig_size + len(passages) == storage.size(), f"Expected {orig_size + len(passages)} passages, got {storage.size()}"- storage.save()---def insert_passages_into_source(passages: List[Passage], source_name: str, user_id: uuid.UUID, config: MemGPTConfig):- """Insert a list of passages into a source by updating storage connectors and metadata store"""- storage = StorageConnector.get_storage_connector(TableType.PASSAGES, config, user_id)- orig_size = storage.size()- # insert metadata store- ms = MetadataStore(config)- source = ms.get_source(user_id=user_id, source_name=source_name)- if not source:- # create new- source = Source(user_id=user_id, name=source_name, created_at=get_local_time())- ms.create_source(source)-- # make sure user_id is set for passages- for passage in passages:- # TODO: attach source IDs- # passage.source_id = source.id- passage.user_id = user_id- passage.data_source = source_name-- # add and save all passages- storage.insert_many(passages)assert orig_size + len(passages) == storage.size(), f"Expected {orig_size + len(passages)} passages, got {storage.size()}"storage.save()@@ -103,12 +79,11 @@ def store_docs(name, docs, user_id=None, show_progress=True):user = ms.get_user(user_id)if user is None:raise ValueError(f"Cannot find user {user_id} in metadata store. Please run 'memgpt configure'.")-# create data source recorddata_source = Source(user_id=user.id,name=name,- created_at=datetime.now(),+ created_at=get_utc_time(),embedding_model=config.default_embedding_config.embedding_model,embedding_dim=config.default_embedding_config.embedding_dim,)@@ -177,6 +152,10 @@ def load_index(user_id: Annotated[Optional[uuid.UUID], typer.Option(help="User ID to associate with dataset.")] = None,):"""Load a LlamaIndex saved VectorIndex into MemGPT"""+ if user_id is None:+ config = MemGPTConfig.load()+ user_id = uuid.UUID(config.anon_clientid)+try:# load index datastorage_context = StorageContext.from_defaults(persist_dir=dir)@@ -259,7 +238,7 @@ def load_webpage(urls: Annotated[List[str], typer.Option(help="List of urls to load.")],):try:- from llama_index import SimpleWebPageReader+ from llama_index.readers.web import SimpleWebPageReaderdocs = SimpleWebPageReader(html_to_text=True).load_data(urls)store_docs(name, docs)@@ -304,7 +283,7 @@ def load_database(db = DatabaseReader(scheme=scheme, # Database Schemehost=host, # Database Host- port=port, # Database Port+ port=str(port), # Database Portuser=user, # Database Userpassword=password, # Database Passworddbname=dbname, # Database Name@@ -327,6 +306,9 @@ def load_vector_database(user_id: Annotated[Optional[uuid.UUID], typer.Option(help="User ID to associate with dataset.")] = None,):"""Load pre-computed embeddings into MemGPT from a database."""+ if user_id is None:+ config = MemGPTConfig.load()+ user_id = uuid.UUID(config.anon_clientid)try:from sqlalchemy import create_engine, select, MetaData, Table, Inspector@@ -345,7 +327,9 @@ def load_vector_database(config = MemGPTConfig.load()# Prepare a select statement- select_statement = select(table.c[text_column], table.c[embedding_column].cast(Vector(config.embedding_dim)))+ select_statement = select(+ table.c[text_column], table.c[embedding_column].cast(Vector(config.default_embedding_config.embedding_dim))+ )# Execute the query and fetch the resultswith engine.connect() as connection:@@ -356,9 +340,17 @@ def load_vector_database(for text, embedding in result:# assume that embeddings are the same model as in configpassages.append(- Passage(text=text, embedding=embedding, embedding_dim=config.embedding_dim, embedding_model=config.embedding_model)+ Passage(+ text=text,+ embedding=embedding,+ user_id=user_id,+ embedding_dim=config.default_embedding_config.embedding_dim,+ embedding_model=config.default_embedding_config.embedding_model,+ ))- assert config.embedding_dim == len(embedding), f"Expected embedding dimension {config.embedding_dim}, got {len(embedding)}"+ assert config.default_embedding_config.embedding_dim == len(+ embedding+ ), f"Expected embedding dimension {config.default_embedding_config.embedding_dim}, got {len(embedding)}"# create storage connectorconfig = MemGPTConfig.load()diff --git a/memgpt/config.py b/memgpt/config.pyindex cf89726cc..32aea9dd9 100644--- a/memgpt/config.py+++ b/memgpt/config.py@@ -7,6 +7,7 @@ from dataclasses import dataclass, fieldimport configparserimport typerimport questionary+from typing import Optionalimport memgptimport memgpt.utils as utils@@ -46,7 +47,6 @@ class MemGPTConfig:# persona parameterspersona: str = DEFAULT_PERSONAhuman: str = DEFAULT_HUMAN- agent: str = None# model parametersdefault_llm_config: LLMConfig = field(default_factory=LLMConfig)@@ -198,7 +198,6 @@ class MemGPTConfig:set_field(config, "defaults", "preset", self.preset)set_field(config, "defaults", "persona", self.persona)set_field(config, "defaults", "human", self.human)- set_field(config, "defaults", "agent", self.agent)# model defaultsset_field(config, "model", "model", self.default_llm_config.model)diff --git a/memgpt/credentials.py b/memgpt/credentials.pyindex be78f89a5..4e9b9ef95 100644--- a/memgpt/credentials.py+++ b/memgpt/credentials.py@@ -7,6 +7,7 @@ from dataclasses import dataclassimport configparserimport typerimport questionary+from typing import Optionalimport memgptimport memgpt.utils as utils@@ -28,19 +29,19 @@ class MemGPTCredentials:# openai configopenai_auth_type: str = "bearer_token"- openai_key: str = None+ openai_key: Optional[str] = None# azure configazure_auth_type: str = "api_key"- azure_key: str = None- azure_endpoint: str = None- azure_version: str = None- azure_deployment: str = None- azure_embedding_deployment: str = None+ azure_key: Optional[str] = None+ azure_endpoint: Optional[str] = None+ azure_version: Optional[str] = None+ azure_deployment: Optional[str] = None+ azure_embedding_deployment: Optional[str] = None# custom llm API config- openllm_auth_type: str = None- openllm_key: str = None+ openllm_auth_type: Optional[str] = None+ openllm_key: Optional[str] = None@classmethoddef load(cls) -> "MemGPTCredentials":diff --git a/memgpt/data_types.py b/memgpt/data_types.pyindex b1716ba6f..ea5bf5089 100644--- a/memgpt/data_types.py+++ b/memgpt/data_types.py@@ -2,11 +2,11 @@import uuidfrom datetime import datetimefrom abc import abstractmethod-from typing import Optional, List, Dict+from typing import Optional, List, Dict, TypeVarimport numpy as npfrom memgpt.constants import DEFAULT_HUMAN, DEFAULT_MEMGPT_MODEL, DEFAULT_PERSONA, DEFAULT_PRESET, LLM_MAX_TOKENS, MAX_EMBEDDING_DIM-from memgpt.utils import get_local_time, format_datetime+from memgpt.utils import get_local_time, format_datetime, get_utc_timefrom memgpt.models import chat_completion_response@@ -25,6 +25,11 @@ class Record:assert isinstance(self.id, uuid.UUID), f"UUID {self.id} must be a UUID type"+# This allows type checking to work when you pass a Passage into a function expecting List[Record]+# (just use List[RecordType] instead)+RecordType = TypeVar("RecordType", bound="Record")++class ToolCall(object):def __init__(self,@@ -77,7 +82,7 @@ class Message(Record):self.agent_id = agent_idself.text = textself.model = model # model name (e.g. gpt-4)- self.created_at = datetime.now().astimezone() if created_at is None else created_at+ self.created_at = get_utc_time() if created_at is None else created_at# openai infoassert role in ["system", "assistant", "user", "tool"]@@ -435,7 +440,7 @@ class AgentState:# messages: List[dict], # in-context messagesid: Optional[uuid.UUID] = None,state: Optional[dict] = None,- created_at: Optional[str] = None,+ created_at: Optional[datetime] = None,):if id is None:self.id = uuid.uuid4()@@ -466,7 +471,7 @@ class Source:self,user_id: uuid.UUID,name: str,- created_at: Optional[str] = None,+ created_at: Optional[datetime] = None,id: Optional[uuid.UUID] = None,# embedding infoembedding_model: Optional[str] = None,diff --git a/memgpt/metadata.py b/memgpt/metadata.pyindex c3edc5275..4d0873b1c 100644--- a/memgpt/metadata.py+++ b/memgpt/metadata.py@@ -355,13 +355,13 @@ class MetadataStore:session.commit()@enforce_types- def list_attached_sources(self, agent_id: uuid.UUID) -> List[Column]:+ def list_attached_sources(self, agent_id: uuid.UUID) -> List[uuid.UUID]:with self.session_maker() as session:results = session.query(AgentSourceMappingModel).filter(AgentSourceMappingModel.agent_id == agent_id).all()return [r.source_id for r in results]@enforce_types- def list_attached_agents(self, source_id: uuid.UUID):+ def list_attached_agents(self, source_id: uuid.UUID) -> List[uuid.UUID]:with self.session_maker() as session:results = session.query(AgentSourceMappingModel).filter(AgentSourceMappingModel.source_id == source_id).all()return [r.agent_id for r in results]diff --git a/memgpt/utils.py b/memgpt/utils.pyindex 637755656..5c94b9613 100644--- a/memgpt/utils.py+++ b/memgpt/utils.py@@ -776,11 +776,15 @@ def get_local_time(timezone=None):return time_str.strip()+def get_utc_time() -> datetime:+ return datetime.now(pytz.utc)++def format_datetime(dt):return dt.strftime("%Y-%m-%d %I:%M:%S %p %Z%z")-def parse_json(string):+def parse_json(string) -> dict:"""Parse JSON string into JSON with both json and demjson"""result = Nonetry: