Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
add llama index querying
Sarah Woodersb45b5b6a753f
diff --git a/memgpt/connectors/connector.py b/memgpt/connectors/connector.pyindex 470cb208d..e06d3418b 100644--- a/memgpt/connectors/connector.py+++ b/memgpt/connectors/connector.py@@ -13,7 +13,7 @@ from typing import Listimport osimport typerfrom memgpt.constants import MEMGPT_DIR-from memgpt.utils import estimate_openai_cost, index_docs, save_index+from memgpt.utils import estimate_openai_cost, get_index, save_indexapp = typer.Typer()@@ -45,7 +45,7 @@ def load_directory(# embed docsprint("Indexing documents...")- index = index_docs(docs)+ index = get_index(name, docs)# save connector information into .memgpt metadata filesave_index(index, name)@@ -89,7 +89,7 @@ def load_database(# load datadocs = db.load_data(query=query)- index = index_docs(docs)+ index = get_index(name, docs)save_index(index, name)diff --git a/memgpt/memory.py b/memgpt/memory.pyindex 659076d56..c2dcaf6f7 100644--- a/memgpt/memory.py+++ b/memgpt/memory.py@@ -1,14 +1,26 @@from abc import ABC, abstractmethod+import osimport datetimeimport reimport faissimport numpy as np+from typing import Optional, List, Tuple-from .constants import MESSAGE_SUMMARY_WARNING_TOKENS+from .constants import MESSAGE_SUMMARY_WARNING_TOKENS, MEMGPT_DIRfrom .utils import cosine_similarity, get_local_time, printd, count_tokensfrom .prompts.gpt_summarize import SYSTEM as SUMMARY_PROMPT_SYSTEMfrom .openai_tools import acompletions_with_backoff as acreate, async_get_embedding_with_backoff+from llama_index import (+ VectorStoreIndex,+ get_response_synthesizer,+ load_index_from_storage,+ StorageContext,+)+from llama_index.retrievers import VectorIndexRetriever+from llama_index.query_engine import RetrieverQueryEngine+from llama_index.indices.postprocessor import SimilarityPostprocessor+class CoreMemory(object):"""Held in-context inside the system message@@ -130,10 +142,26 @@ class ArchivalMemory(ABC):@abstractmethoddef insert(self, memory_string):+ """ Insert new archival memory++ :param memory_string: Memory string to insert+ :type memory_string: str+ """pass@abstractmethod- def search(self, query_string, count=None, start=None):+ def search(self, query_string, count=None, start=None) -> Tuple[List[str], int]:+ """ Search archival memory++ :param query_string: Query string+ :type query_string: str+ :param count: Number of results to return (None for all)+ :type count: Optional[int]+ :param start: Offset to start returning results from (None if 0)+ :type start: Optional[int]++ :return: Tuple of (list of results, total number of results)+ """pass@abstractmethod@@ -501,3 +529,72 @@ class DummyRecallMemoryWithEmbeddings(DummyRecallMemory):return matches[start:], len(matches)else:return matches, len(matches)+++class LocalArchivalMemory(ArchivalMemory):+ """ Archival memory built on top of Llama Index """++ def __init__(self, archival_memory_database: Optional[str] = None, top_k: Optional[int] = 100):+ """ Init function for archival memory++ :param archiva_memory_database: name of dataset to pre-fill archival with+ :type archival_memory_database: str+ """++ if archival_memory_database is not None:+ # TODO: load form ~/.memgpt/archival+ directory = f"{MEMGPT_DIR}/archival/{archival_memory_database}"+ assert os.path.exists(directory), f"Archival memory database {archival_memory_database} does not exist"+ storage_context = StorageContext.from_defaults(persist_dir=directory)+ self.index = load_index_from_storage(storage_context)+ else:+ self.index = VectorIndex()+ self.top_k = top_k+ self.retriever = VectorIndexRetriever(+ index=self.index, # does this get refreshed?+ similarity_top_k=self.top_k,+ )++ # configure response synthesizer+ response_synthesizer = get_response_synthesizer()++ # assemble query engine+ self.query_engine = RetrieverQueryEngine(+ retriever=self.retriever,+ #response_synthesizer=response_synthesizer,+ #node_postprocessors=[+ # SimilarityPostprocessor(similarity_cutoff=0) # TODO: tune this+ #]+ )++ # cache for repeated queries+ # TODO: have some mechanism for cleanup otherwise will lead to OOM+ self.cache = {}++ async def insert(self, memory_string):+ self.index.insert(memory_string)++ async def search(self, query_string, count=None, start=None):++ start = start if start else 0+ count = count if count else self.top_k+ count = min(count + start, self.top_k)++ if query_string not in self.cache:+ #self.cache[query_string] = self.query_engine.query(query_string)+ self.cache[query_string] = self.retriever.retrieve(query_string)++ results = self.cache[query_string][start:start+count]+ results = [+ {'timestamp': get_local_time(), 'content': node.node.text}+ for node in results+ ]+ #from pprint import pprint+ #pprint(results)+ return results, len(results)++ def __repr__(self) -> str:+ print(self.index.ref_doc_info)+ return ""++diff --git a/memgpt/persistence_manager.py b/memgpt/persistence_manager.pyindex 4874fe020..3e6bafaf3 100644--- a/memgpt/persistence_manager.py+++ b/memgpt/persistence_manager.py@@ -1,7 +1,7 @@from abc import ABC, abstractmethodimport pickle-from .memory import DummyRecallMemory, DummyRecallMemoryWithEmbeddings, DummyArchivalMemory, DummyArchivalMemoryWithEmbeddings, DummyArchivalMemoryWithFaiss+from .memory import DummyRecallMemory, DummyRecallMemoryWithEmbeddings, DummyArchivalMemory, DummyArchivalMemoryWithEmbeddings, DummyArchivalMemoryWithFaiss, LocalArchivalMemoryfrom .utils import get_local_time, printd@@ -32,13 +32,14 @@ class InMemoryStateManager(PersistenceManager):"""In-memory state manager has nothing to manage, all agents are held in-memory"""recall_memory_cls = DummyRecallMemory- archival_memory_cls = DummyArchivalMemory+ archival_memory_cls = LocalArchivalMemory- def __init__(self):+ def __init__(self, archival_memory_db=None):# Memory held in-state useful for debugging stateful versionsself.memory = Noneself.messages = []self.all_messages = []+ self.archival_memory = LocalArchivalMemory(archival_memory_database=archival_memory_db)@staticmethoddef load(filename):@@ -59,8 +60,8 @@ class InMemoryStateManager(PersistenceManager):# Persistence manager also handles DB-related stateself.recall_memory = self.recall_memory_cls(message_database=self.all_messages)- self.archival_memory_db = []- self.archival_memory = self.archival_memory_cls(archival_memory_database=self.archival_memory_db)++ # TODO: init archival memory here?def trim_messages(self, num):# printd(f"InMemoryStateManager.trim_messages")@@ -142,3 +143,4 @@ class InMemoryStateManagerWithFaiss(InMemoryStateManager):# Persistence manager also handles DB-related stateself.recall_memory = self.recall_memory_cls(message_database=self.all_messages)self.archival_memory = self.archival_memory_cls(index=self.archival_index, archival_memory_database=self.archival_memory_db, k=self.a_k)+diff --git a/memgpt/utils.py b/memgpt/utils.pyindex a8b5a07a4..560f544f1 100644--- a/memgpt/utils.py+++ b/memgpt/utils.py@@ -16,7 +16,7 @@ from tqdm import tqdmimport typerfrom memgpt.openai_tools import async_get_embedding_with_backofffrom memgpt.constants import MEMGPT_DIR-from llama_index import set_global_service_context, ServiceContext, VectorStoreIndex+from llama_index import set_global_service_context, ServiceContext, VectorStoreIndex, load_index_from_storage, StorageContextfrom llama_index.embeddings import OpenAIEmbeddingdef count_tokens(s: str, model: str = "gpt-4") -> int:@@ -375,7 +375,8 @@ def estimate_openai_cost(docs):token_counter.reset_counts()return cost-def index_docs(docs):++def get_index(name, docs):""" Index documents@@ -383,6 +384,15 @@ def index_docs(docs)::type docs: List[Document]"""+ # check if directory exists+ dir = f"{MEMGPT_DIR}/archival/{name}"+ if os.path.exists(dir):+ confirm = typer.confirm(typer.style(f"Index with name {name} already exists -- re-index?", fg="yellow"), default=False)+ if not confirm:+ # return existing index+ storage_context = StorageContext.from_defaults(persist_dir=dir)+ return load_index_from_storage(storage_context)+# TODO: support configurable embeddings# TODO: read from config how to index (open ai vs. local): then embed_mode="local"@@ -414,14 +424,17 @@ def save_index(index, name):# save# TODO: load directory from config# TODO: save to vectordb/local depending on config+dir = f"{MEMGPT_DIR}/archival/{name}"- # check if directory exists- if os.path.exists(dir):- confirm = typer.confirm(typer.style(f"Index with name {name} already exists -- overwrite?", fg="red"), default=False)- if not confirm:- typer.secho("Aborting.", fg="red")- exit()+ ## Avoid overwriting+ ## check if directory exists+ #if os.path.exists(dir):+ # confirm = typer.confirm(typer.style(f"Index with name {name} already exists -- overwrite?", fg="red"), default=False)+ # if not confirm:+ # typer.secho("Aborting.", fg="red")+ # exit()+# create directory, even if it already existsos.makedirs(dir, exist_ok=True)index.storage_context.persist(dir)