memory.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. from . import json
  2. import chromadb
  3. from llama_index.core import Document
  4. from llama_index.core.retrievers import VectorIndexRetriever
  5. from llama_index.core import VectorStoreIndex
  6. from llama_index.vector_stores.chroma import ChromaVectorStore
  7. class LongTermMemory:
  8. def __init__(self):
  9. db = chromadb.Client()
  10. self.collection = db.get_or_create_collection(name="memories")
  11. vector_store = ChromaVectorStore(chroma_collection=self.collection)
  12. self.index = VectorStoreIndex.from_vector_store(vector_store)
  13. self.thought_idx = 0
  14. def add_event(self, event):
  15. doc = Document(
  16. text=json.dumps(event),
  17. doc_id=str(self.thought_idx),
  18. extra_info={
  19. "type": event["action"],
  20. "idx": self.thought_idx,
  21. },
  22. )
  23. self.thought_idx += 1
  24. self.index.insert(doc)
  25. def search(self, query, k=10):
  26. retriever = VectorIndexRetriever(
  27. index=self.index,
  28. similarity_top_k=k,
  29. )
  30. results = retriever.retrieve(query)
  31. return [r.get_text() for r in results]