AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
refactor: Reduce breakage in vector memory module and split MemoryItem class
Reinier van der Leeref35702c4bc5
diff --git a/autogpts/autogpt/autogpt/commands/file_operations.py b/autogpts/autogpt/autogpt/commands/file_operations.pyindex 7525ae69c8..ba2be0005e 100644--- a/autogpts/autogpt/autogpt/commands/file_operations.py+++ b/autogpts/autogpt/autogpt/commands/file_operations.py@@ -14,7 +14,7 @@ from autogpt.agents.agent import Agentfrom autogpt.agents.utils.exceptions import DuplicateOperationErrorfrom autogpt.command_decorator import commandfrom autogpt.core.utils.json_schema import JSONSchema-from autogpt.memory.vector import MemoryItem, VectorMemory+from autogpt.memory.vector import MemoryItemFactory, VectorMemoryfrom .decorators import sanitize_path_argfrom .file_operations_utils import read_textual_file@@ -184,7 +184,7 @@ def ingest_file(content = read_file(filename)# TODO: differentiate between different types of files- file_memory = MemoryItem.from_text_file(content, filename)+ file_memory = MemoryItemFactory.from_text_file(content, filename)logger.debug(f"Created memory: {file_memory.dump(True)}")memory.add(file_memory)diff --git a/autogpts/autogpt/autogpt/memory/vector/__init__.py b/autogpts/autogpt/autogpt/memory/vector/__init__.pyindex f996265bb8..f7f38412d0 100644--- a/autogpts/autogpt/autogpt/memory/vector/__init__.py+++ b/autogpts/autogpt/autogpt/memory/vector/__init__.py@@ -1,6 +1,6 @@from autogpt.config import Config-from .memory_item import MemoryItem, MemoryItemRelevance+from .memory_item import MemoryItem, MemoryItemFactory, MemoryItemRelevancefrom .providers.base import VectorMemoryProvider as VectorMemoryfrom .providers.json_file import JSONFileMemoryfrom .providers.no_memory import NoMemory@@ -144,6 +144,7 @@ def get_supported_memory_backends():__all__ = ["get_memory","MemoryItem",+ "MemoryItemFactory","MemoryItemRelevance","JSONFileMemory","NoMemory",diff --git a/autogpts/autogpt/autogpt/memory/vector/memory_item.py b/autogpts/autogpt/autogpt/memory/vector/memory_item.pyindex 8d127235e1..8d03d0209b 100644--- a/autogpts/autogpt/autogpt/memory/vector/memory_item.py+++ b/autogpts/autogpt/autogpt/memory/vector/memory_item.py@@ -9,7 +9,11 @@ import numpy as npfrom pydantic import BaseModelfrom autogpt.config import Config-from autogpt.core.resource.model_providers import ChatMessage+from autogpt.core.resource.model_providers import (+ ChatMessage,+ ChatModelProvider,+ EmbeddingModelProvider,+)from autogpt.processing.text import chunk_content, split_text, summarize_textfrom .utils import Embedding, get_embedding@@ -19,7 +23,6 @@ logger = logging.getLogger(__name__)MemoryDocType = Literal["webpage", "text_file", "code_file", "agent_history"]-# FIXME: implement validators instead of allowing arbitrary typesclass MemoryItem(BaseModel, arbitrary_types_allowed=True):"""Memory object containing raw content as well as embeddings"""@@ -34,8 +37,56 @@ class MemoryItem(BaseModel, arbitrary_types_allowed=True):def relevance_for(self, query: str, e_query: Embedding | None = None):return MemoryItemRelevance.of(self, query, e_query)- @staticmethod- def from_text(+ def dump(self, calculate_length=False) -> str:+ n_chunks = len(self.e_chunks)+ return f"""+=============== MemoryItem ===============+Size: {n_chunks} chunks+Metadata: {json.dumps(self.metadata, indent=2)}+---------------- SUMMARY -----------------+{self.summary}+------------------ RAW -------------------+{self.raw_content}+==========================================+"""++ def __eq__(self, other: MemoryItem):+ return (+ self.raw_content == other.raw_content+ and self.chunks == other.chunks+ and self.chunk_summaries == other.chunk_summaries+ # Embeddings can either be list[float] or np.ndarray[float32],+ # and for comparison they must be of the same type+ and np.array_equal(+ self.e_summary+ if isinstance(self.e_summary, np.ndarray)+ else np.array(self.e_summary, dtype=np.float32),+ other.e_summary+ if isinstance(other.e_summary, np.ndarray)+ else np.array(other.e_summary, dtype=np.float32),+ )+ and np.array_equal(+ self.e_chunks+ if isinstance(self.e_chunks[0], np.ndarray)+ else [np.array(c, dtype=np.float32) for c in self.e_chunks],+ other.e_chunks+ if isinstance(other.e_chunks[0], np.ndarray)+ else [np.array(c, dtype=np.float32) for c in other.e_chunks],+ )+ )+++class MemoryItemFactory:+ def __init__(+ self,+ llm_provider: ChatModelProvider,+ embedding_provider: EmbeddingModelProvider,+ ):+ self.llm_provider = llm_provider+ self.embedding_provider = embedding_provider++ async def from_text(+ self,text: str,source_type: MemoryDocType,config: Config,@@ -52,9 +103,19 @@ class MemoryItem(BaseModel, arbitrary_types_allowed=True):chunks = [chunkfor chunk, _ in (- split_text(text, config.embedding_model, config)+ split_text(+ text=text,+ config=config,+ max_chunk_length=1000, # arbitrary, but shorter ~= better+ tokenizer=self.llm_provider.get_tokenizer(config.fast_llm),+ )if source_type != "code_file"- else chunk_content(text, config.embedding_model)+ # TODO: chunk code based on structure/outline+ else chunk_content(+ content=text,+ max_chunk_length=1000,+ tokenizer=self.llm_provider.get_tokenizer(config.fast_llm),+ ))]logger.debug("Chunks: " + str(chunks))@@ -62,34 +123,38 @@ class MemoryItem(BaseModel, arbitrary_types_allowed=True):chunk_summaries = [summaryfor summary, _ in [- summarize_text(- text_chunk,- config,+ await summarize_text(+ text=text_chunk,instruction=how_to_summarize,question=question_for_summary,+ llm_provider=self.llm_provider,+ config=config,)for text_chunk in chunks]]logger.debug("Chunk summaries: " + str(chunk_summaries))- e_chunks = get_embedding(chunks, config)+ e_chunks = get_embedding(chunks, config, self.embedding_provider)summary = (chunk_summaries[0]if len(chunks) == 1- else summarize_text(- "\n\n".join(chunk_summaries),- config,- instruction=how_to_summarize,- question=question_for_summary,+ else (+ await summarize_text(+ text="\n\n".join(chunk_summaries),+ instruction=how_to_summarize,+ question=question_for_summary,+ llm_provider=self.llm_provider,+ config=config,+ ))[0])logger.debug("Total summary: " + summary)# TODO: investigate search performance of weighted average vs summary# e_average = np.average(e_chunks, axis=0, weights=[len(c) for c in chunks])- e_summary = get_embedding(summary, config)+ e_summary = get_embedding(summary, config, self.embedding_provider)metadata["source_type"] = source_type@@ -103,17 +168,14 @@ class MemoryItem(BaseModel, arbitrary_types_allowed=True):metadata=metadata,)- @staticmethod- def from_text_file(content: str, path: str, config: Config):- return MemoryItem.from_text(content, "text_file", config, {"location": path})+ def from_text_file(self, content: str, path: str, config: Config):+ return self.from_text(content, "text_file", config, {"location": path})- @staticmethod- def from_code_file(content: str, path: str):+ def from_code_file(self, content: str, path: str):# TODO: implement tailored code memories- return MemoryItem.from_text(content, "code_file", {"location": path})+ return self.from_text(content, "code_file", {"location": path})- @staticmethod- def from_ai_action(ai_message: ChatMessage, result_message: ChatMessage):+ def from_ai_action(self, ai_message: ChatMessage, result_message: ChatMessage):# The result_message contains either user feedback# or the result of the command specified in ai_message@@ -138,7 +200,7 @@ class MemoryItem(BaseModel, arbitrary_types_allowed=True):f"Human Feedback: {user_input}")- return MemoryItem.from_text(+ return self.from_text(text=memory_content,source_type="agent_history",how_to_summarize=(@@ -148,11 +210,10 @@ class MemoryItem(BaseModel, arbitrary_types_allowed=True):),)- @staticmethoddef from_webpage(- content: str, url: str, config: Config, question: str | None = None+ self, content: str, url: str, config: Config, question: str | None = None):- return MemoryItem.from_text(+ return self.from_text(text=content,source_type="webpage",config=config,@@ -160,48 +221,6 @@ class MemoryItem(BaseModel, arbitrary_types_allowed=True):question_for_summary=question,)- def dump(self, calculate_length=False) -> str:- if calculate_length:- token_length = self.llm_provider.count_tokens(- self.raw_content, Config().embedding_model- )- n_chunks = len(self.e_chunks)- return f"""-=============== MemoryItem ===============-Size: {f'{token_length} tokens in ' if calculate_length else ''}{n_chunks} chunks-Metadata: {json.dumps(self.metadata, indent=2)}----------------- SUMMARY ------------------{self.summary}------------------- RAW --------------------{self.raw_content}-==========================================-"""-- def __eq__(self, other: MemoryItem):- return (- self.raw_content == other.raw_content- and self.chunks == other.chunks- and self.chunk_summaries == other.chunk_summaries- # Embeddings can either be list[float] or np.ndarray[float32],- # and for comparison they must be of the same type- and np.array_equal(- self.e_summary- if isinstance(self.e_summary, np.ndarray)- else np.array(self.e_summary, dtype=np.float32),- other.e_summary- if isinstance(other.e_summary, np.ndarray)- else np.array(other.e_summary, dtype=np.float32),- )- and np.array_equal(- self.e_chunks- if isinstance(self.e_chunks[0], np.ndarray)- else [np.array(c, dtype=np.float32) for c in self.e_chunks],- other.e_chunks- if isinstance(other.e_chunks[0], np.ndarray)- else [np.array(c, dtype=np.float32) for c in other.e_chunks],- )- )-class MemoryItemRelevance(BaseModel):"""diff --git a/autogpts/autogpt/autogpt/memory/vector/utils.py b/autogpts/autogpt/autogpt/memory/vector/utils.pyindex 1023230c15..b8b87a4913 100644--- a/autogpts/autogpt/autogpt/memory/vector/utils.py+++ b/autogpts/autogpt/autogpt/memory/vector/utils.py@@ -5,6 +5,7 @@ from typing import Any, Sequence, overloadimport numpy as npfrom autogpt.config import Config+from autogpt.core.resource.model_providers import EmbeddingModelProviderlogger = logging.getLogger(__name__)@@ -16,23 +17,32 @@ TText = Sequence[int]@overload-def get_embedding(input: str | TText, config: Config) -> Embedding:+async def get_embedding(+ input: str | TText, config: Config, embedding_provider: EmbeddingModelProvider+) -> Embedding:...@overload-def get_embedding(input: list[str] | list[TText], config: Config) -> list[Embedding]:+async def get_embedding(+ input: list[str] | list[TText],+ config: Config,+ embedding_provider: EmbeddingModelProvider,+) -> list[Embedding]:...-def get_embedding(- input: str | TText | list[str] | list[TText], config: Config+async def get_embedding(+ input: str | TText | list[str] | list[TText],+ config: Config,+ embedding_provider: EmbeddingModelProvider,) -> Embedding | list[Embedding]:"""Get an embedding from the ada model.Args:input: Input text to get embeddings for, encoded as a string or array of tokens.Multiple inputs may be given as a list of strings or token arrays.+ embedding_provider: The provider to create embeddings.Returns:List[float]: The embedding.@@ -52,25 +62,30 @@ def get_embedding(return [_get_embedding_with_plugin(i, config) for i in input]model = config.embedding_model- kwargs = {"model": model}- kwargs.update(config.get_openai_credentials(model))logger.debug(f"Getting embedding{f's for {len(input)} inputs' if multiple else ''}"f" with model '{model}'"- + (f" via Azure deployment '{kwargs['engine']}'" if config.use_azure else ""))- embeddings = embedding_provider.create_embedding(- input,- **kwargs,- ).data-if not multiple:- return embeddings[0]["embedding"]-- embeddings = sorted(embeddings, key=lambda x: x["index"])- return [d["embedding"] for d in embeddings]+ return (+ await embedding_provider.create_embedding(+ text=input,+ model_name=model,+ embedding_parser=lambda e: e,+ )+ ).embedding+ else:+ embeddings = []+ for text in input:+ result = await embedding_provider.create_embedding(+ text=text,+ model_name=model,+ embedding_parser=lambda e: e,+ )+ embeddings.append(result.embedding)+ return embeddingsdef _get_embedding_with_plugin(text: str, config: Config) -> Embedding:diff --git a/autogpts/autogpt/tests/unit/test_file_operations.py b/autogpts/autogpt/tests/unit/test_file_operations.pyindex 7ef9707ed2..21ebd0b329 100644--- a/autogpts/autogpt/tests/unit/test_file_operations.py+++ b/autogpts/autogpt/tests/unit/test_file_operations.py@@ -26,7 +26,7 @@ def mock_MemoryItem_from_text(mocker: MockerFixture, mock_embedding: Embedding, config: Config):mocker.patch.object(- file_ops.MemoryItem,+ file_ops.MemoryItemFactory,"from_text",new=lambda content, source_type, config, metadata: MemoryItem(raw_content=content,