Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
initial llama index data loading implementation
Sarah Wooders942666d3b541
diff --git a/memgpt/connectors/connector.py b/memgpt/connectors/connector.pynew file mode 100644index 000000000..2b3c22a28--- /dev/null+++ b/memgpt/connectors/connector.py@@ -0,0 +1,66 @@+"""+This file contains functions for loading data into MemGPT's archival storage.++Data can be loaded with the following command, once a load function is defined:+```+memgpt load <data-connector-type> --name <dataset-name> [ADDITIONAL ARGS]+```++"""++from llama_index import download_loader+from llama_index.embeddings import OpenAIEmbedding+from typing import List+import os+import typer+from memgpt.constants import MEMGPT_DIR+from memgpt.utils import estimate_openai_cost, index_docs, save_index++app = typer.Typer()+++[email protected]("directory")+def load_directory(+ name: str = typer.Option(help="Name of dataset to load."),+ input_dir: str = typer.Option(None, help="Path to directory containing dataset."),+ input_files: List[str] = typer.Option(None, help="List of paths to files containing dataset."),+ recursive: bool = typer.Option(False, help="Recursively search for files in directory."),+):+ from llama_index import SimpleDirectoryReader++ if recursive:+ assert input_dir is not None, "Must provide input directory if recursive is True."+ reader = SimpleDirectoryReader(+ input_dir=input_dir,+ recursive=True,+ )+ else:+ reader = SimpleDirectoryReader(+ input_files=input_files+ )++ # load docs+ print("Loading data...")+ docs = reader.load_data()++ # embed docs+ print("Indexing documents...")+ index = index_docs(docs)+ # save connector information into .memgpt metadata file+ save_index(index, name)+[email protected]("webpage")+def load_webpage(+ name: str = typer.Option(help="Name of dataset to load."),+ urls: List[str] = typer.Option(None, help="List of urls to load."),+):+ from llama_index import SimpleWebPageReader+ docs = SimpleWebPageReader(html_to_text=True).load_data(urls)++ # embed docs+ print("Indexing documents...")+ index = index_docs(docs)+ # save connector information into .memgpt metadata file+ save_index(index, name)+diff --git a/memgpt/main.py b/memgpt/main.pyindex e0bc5bc43..b27c2e036 100644--- a/memgpt/main.py+++ b/memgpt/main.py@@ -28,9 +28,11 @@ from memgpt.persistence_manager import (from memgpt.config import Configfrom memgpt.constants import MEMGPT_DIR+from memgpt.connectors import connectorimport asyncioapp = typer.Typer()+app.add_typer(connector.app, name="load")def clear_line():diff --git a/memgpt/utils.py b/memgpt/utils.pyindex 441fb50e5..92c829780 100644--- a/memgpt/utils.py+++ b/memgpt/utils.py@@ -1,5 +1,4 @@from datetime import datetime-import asyncioimport csvimport difflib@@ -14,9 +13,11 @@ import globimport sqlite3import fitzfrom tqdm import tqdm+import 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.embeddings import OpenAIEmbeddingdef count_tokens(s: str, model: str = "gpt-4") -> int:encoding = tiktoken.encoding_for_model(model)@@ -338,3 +339,83 @@ def read_database_as_list(database_name):except Exception as e:result_list.append(f"Error: {str(e)}")return result_list++++def estimate_openai_cost(docs):+ """ Estimate OpenAI embedding cost++ :param docs: Documents to be embedded+ :type docs: List[Document]+ :return: Estimated cost+ :rtype: float+ """+ from llama_index import MockEmbedding+ from llama_index.callbacks import CallbackManager, TokenCountingHandler+ import tiktoken++ embed_model = MockEmbedding(embed_dim=1536)++ token_counter = TokenCountingHandler(+ tokenizer=tiktoken.encoding_for_model("gpt-3.5-turbo").encode+ )++ callback_manager = CallbackManager([token_counter])++ set_global_service_context(+ ServiceContext.from_defaults(+ embed_model=embed_model,+ callback_manager=callback_manager+ )+ )+ index = VectorStoreIndex.from_documents(docs)++ # estimate cost+ cost = 0.0001 * token_counter.total_embedding_token_count / 1000+ token_counter.reset_counts()+ return cost++def index_docs(docs):++ """ Index documents++ :param docs: Documents to be embedded+ :type docs: List[Document]+ """++ # TODO: support configurable embeddings+ # TODO: read from config how to index (open ai vs. local): then embed_mode="local"++ estimated_cost = estimate_openai_cost(docs)+ # TODO: prettier cost formatting+ confirm = typer.confirm(typer.style(f"Open AI embedding cost will be approximately ${estimated_cost} - continue?", fg="yellow"), default=True)++ if not confirm:+ typer.secho("Aborting.", fg="red")+ exit()++ embed_model = OpenAIEmbedding()+ service_context = ServiceContext.from_defaults(embed_model=embed_model, chunk_size = 300)+ set_global_service_context(service_context)++ # index documents+ index = VectorStoreIndex.from_documents(docs)+ return index++def save_index(index, name):++ """ Save index to a specificed name in ~/.memgpt++ :param index: Index to save+ :type index: VectorStoreIndex+ :param name: Name of index+ :type name: str+ """+ # save+ # TODO: load directory from config+ # TODO: save to vectordb/local depending on config+ dir = f"{MEMGPT_DIR}/archival/{name}"+ # create directory, even if it already exists+ os.makedirs(dir, exist_ok=True)+ index.storage_context.persist(dir)+ print(dir)