memory.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import threading
  2. import chromadb
  3. import llama_index.embeddings.openai.base as llama_openai
  4. from llama_index.core import Document, VectorStoreIndex
  5. from llama_index.core.retrievers import VectorIndexRetriever
  6. from llama_index.vector_stores.chroma import ChromaVectorStore
  7. from openai._exceptions import APIConnectionError, InternalServerError, RateLimitError
  8. from tenacity import (
  9. retry,
  10. retry_if_exception_type,
  11. stop_after_attempt,
  12. wait_random_exponential,
  13. )
  14. from opendevin.core.config import LLMConfig
  15. from opendevin.core.logger import opendevin_logger as logger
  16. from opendevin.core.utils import json
  17. # TODO: this could be made configurable
  18. num_retries: int = 10
  19. retry_min_wait: int = 3
  20. retry_max_wait: int = 300
  21. # llama-index includes a retry decorator around openai.get_embeddings() function
  22. # it is initialized with hard-coded values and errors
  23. # this non-customizable behavior is creating issues when it's retrying faster than providers' rate limits
  24. # this block attempts to banish it and replace it with our decorator, to allow users to set their own limits
  25. if hasattr(llama_openai.get_embeddings, '__wrapped__'):
  26. original_get_embeddings = llama_openai.get_embeddings.__wrapped__
  27. else:
  28. logger.warning('Cannot set custom retry limits.')
  29. num_retries = 1
  30. original_get_embeddings = llama_openai.get_embeddings
  31. def attempt_on_error(retry_state):
  32. logger.error(
  33. f'{retry_state.outcome.exception()}. Attempt #{retry_state.attempt_number} | You can customize these settings in the configuration.',
  34. exc_info=False,
  35. )
  36. return None
  37. @retry(
  38. reraise=True,
  39. stop=stop_after_attempt(num_retries),
  40. wait=wait_random_exponential(min=retry_min_wait, max=retry_max_wait),
  41. retry=retry_if_exception_type(
  42. (RateLimitError, APIConnectionError, InternalServerError)
  43. ),
  44. after=attempt_on_error,
  45. )
  46. def wrapper_get_embeddings(*args, **kwargs):
  47. return original_get_embeddings(*args, **kwargs)
  48. llama_openai.get_embeddings = wrapper_get_embeddings
  49. class EmbeddingsLoader:
  50. """Loader for embedding model initialization."""
  51. @staticmethod
  52. def get_embedding_model(strategy: str, llm_config: LLMConfig):
  53. supported_ollama_embed_models = [
  54. 'llama2',
  55. 'mxbai-embed-large',
  56. 'nomic-embed-text',
  57. 'all-minilm',
  58. 'stable-code',
  59. ]
  60. if strategy in supported_ollama_embed_models:
  61. from llama_index.embeddings.ollama import OllamaEmbedding
  62. return OllamaEmbedding(
  63. model_name=strategy,
  64. base_url=llm_config.embedding_base_url,
  65. ollama_additional_kwargs={'mirostat': 0},
  66. )
  67. elif strategy == 'openai':
  68. from llama_index.embeddings.openai import OpenAIEmbedding
  69. return OpenAIEmbedding(
  70. model='text-embedding-ada-002',
  71. api_key=llm_config.api_key,
  72. )
  73. elif strategy == 'azureopenai':
  74. from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding
  75. return AzureOpenAIEmbedding(
  76. model='text-embedding-ada-002',
  77. deployment_name=llm_config.embedding_deployment_name,
  78. api_key=llm_config.api_key,
  79. azure_endpoint=llm_config.base_url,
  80. api_version=llm_config.api_version,
  81. )
  82. elif (strategy is not None) and (strategy.lower() == 'none'):
  83. # TODO: this works but is not elegant enough. The incentive is when
  84. # an agent using embeddings is not used, there is no reason we need to
  85. # initialize an embedding model
  86. return None
  87. else:
  88. from llama_index.embeddings.huggingface import HuggingFaceEmbedding
  89. return HuggingFaceEmbedding(model_name='BAAI/bge-small-en-v1.5')
  90. class LongTermMemory:
  91. """Handles storing information for the agent to access later, using chromadb."""
  92. def __init__(self, llm_config: LLMConfig, memory_max_threads: int = 1):
  93. """Initialize the chromadb and set up ChromaVectorStore for later use."""
  94. db = chromadb.Client(chromadb.Settings(anonymized_telemetry=False))
  95. self.collection = db.get_or_create_collection(name='memories')
  96. vector_store = ChromaVectorStore(chroma_collection=self.collection)
  97. embedding_strategy = llm_config.embedding_model
  98. embed_model = EmbeddingsLoader.get_embedding_model(
  99. embedding_strategy, llm_config
  100. )
  101. self.index = VectorStoreIndex.from_vector_store(vector_store, embed_model)
  102. self.sema = threading.Semaphore(value=memory_max_threads)
  103. self.thought_idx = 0
  104. self._add_threads: list[threading.Thread] = []
  105. def add_event(self, event: dict):
  106. """Adds a new event to the long term memory with a unique id.
  107. Parameters:
  108. - event (dict): The new event to be added to memory
  109. """
  110. id = ''
  111. t = ''
  112. if 'action' in event:
  113. t = 'action'
  114. id = event['action']
  115. elif 'observation' in event:
  116. t = 'observation'
  117. id = event['observation']
  118. doc = Document(
  119. text=json.dumps(event),
  120. doc_id=str(self.thought_idx),
  121. extra_info={
  122. 'type': t,
  123. 'id': id,
  124. 'idx': self.thought_idx,
  125. },
  126. )
  127. self.thought_idx += 1
  128. logger.debug('Adding %s event to memory: %d', t, self.thought_idx)
  129. thread = threading.Thread(target=self._add_doc, args=(doc,))
  130. self._add_threads.append(thread)
  131. thread.start() # We add the doc concurrently so we don't have to wait ~500ms for the insert
  132. def _add_doc(self, doc):
  133. with self.sema:
  134. self.index.insert(doc)
  135. def search(self, query: str, k: int = 10):
  136. """Searches through the current memory using VectorIndexRetriever
  137. Parameters:
  138. - query (str): A query to match search results to
  139. - k (int): Number of top results to return
  140. Returns:
  141. - list[str]: list of top k results found in current memory
  142. """
  143. retriever = VectorIndexRetriever(
  144. index=self.index,
  145. similarity_top_k=k,
  146. )
  147. results = retriever.retrieve(query)
  148. return [r.get_text() for r in results]