|
| 1 | +import dataclasses |
| 2 | +import orjson |
| 3 | +from typing import Any, List, Optional |
| 4 | +import numpy as np |
| 5 | +import os |
| 6 | +from memory.base import MemoryProviderSingleton, get_ada_embedding |
| 7 | + |
| 8 | + |
| 9 | +EMBED_DIM = 1536 |
| 10 | +SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIALIZE_DATACLASS |
| 11 | + |
| 12 | + |
| 13 | +def create_default_embeddings(): |
| 14 | + return np.zeros((0, EMBED_DIM)).astype(np.float32) |
| 15 | + |
| 16 | + |
| 17 | +@dataclasses.dataclass |
| 18 | +class CacheContent: |
| 19 | + texts: List[str] = dataclasses.field(default_factory=list) |
| 20 | + embeddings: np.ndarray = dataclasses.field( |
| 21 | + default_factory=create_default_embeddings |
| 22 | + ) |
| 23 | + |
| 24 | + |
| 25 | +class LocalCache(MemoryProviderSingleton): |
| 26 | + |
| 27 | + # on load, load our database |
| 28 | + def __init__(self, cfg) -> None: |
| 29 | + self.filename = f"{cfg.memory_index}.json" |
| 30 | + if os.path.exists(self.filename): |
| 31 | + with open(self.filename, 'rb') as f: |
| 32 | + loaded = orjson.loads(f.read()) |
| 33 | + self.data = CacheContent(**loaded) |
| 34 | + else: |
| 35 | + self.data = CacheContent() |
| 36 | + |
| 37 | + def add(self, text: str): |
| 38 | + """ |
| 39 | + Add text to our list of texts, add embedding as row to our |
| 40 | + embeddings-matrix |
| 41 | +
|
| 42 | + Args: |
| 43 | + text: str |
| 44 | +
|
| 45 | + Returns: None |
| 46 | + """ |
| 47 | + if 'Command Error:' in text: |
| 48 | + return "" |
| 49 | + self.data.texts.append(text) |
| 50 | + |
| 51 | + embedding = get_ada_embedding(text) |
| 52 | + |
| 53 | + vector = np.array(embedding).astype(np.float32) |
| 54 | + vector = vector[np.newaxis, :] |
| 55 | + self.data.embeddings = np.concatenate( |
| 56 | + [ |
| 57 | + vector, |
| 58 | + self.data.embeddings, |
| 59 | + ], |
| 60 | + axis=0, |
| 61 | + ) |
| 62 | + |
| 63 | + with open(self.filename, 'wb') as f: |
| 64 | + out = orjson.dumps( |
| 65 | + self.data, |
| 66 | + option=SAVE_OPTIONS |
| 67 | + ) |
| 68 | + f.write(out) |
| 69 | + return text |
| 70 | + |
| 71 | + def clear(self) -> str: |
| 72 | + """ |
| 73 | + Clears the redis server. |
| 74 | +
|
| 75 | + Returns: A message indicating that the memory has been cleared. |
| 76 | + """ |
| 77 | + self.data = CacheContent() |
| 78 | + return "Obliviated" |
| 79 | + |
| 80 | + def get(self, data: str) -> Optional[List[Any]]: |
| 81 | + """ |
| 82 | + Gets the data from the memory that is most relevant to the given data. |
| 83 | +
|
| 84 | + Args: |
| 85 | + data: The data to compare to. |
| 86 | +
|
| 87 | + Returns: The most relevant data. |
| 88 | + """ |
| 89 | + return self.get_relevant(data, 1) |
| 90 | + |
| 91 | + def get_relevant(self, text: str, k: int) -> List[Any]: |
| 92 | + """" |
| 93 | + matrix-vector mult to find score-for-each-row-of-matrix |
| 94 | + get indices for top-k winning scores |
| 95 | + return texts for those indices |
| 96 | + Args: |
| 97 | + text: str |
| 98 | + k: int |
| 99 | +
|
| 100 | + Returns: List[str] |
| 101 | + """ |
| 102 | + embedding = get_ada_embedding(text) |
| 103 | + |
| 104 | + scores = np.dot(self.data.embeddings, embedding) |
| 105 | + |
| 106 | + top_k_indices = np.argsort(scores)[-k:][::-1] |
| 107 | + |
| 108 | + return [self.data.texts[i] for i in top_k_indices] |
| 109 | + |
| 110 | + def get_stats(self): |
| 111 | + """ |
| 112 | + Returns: The stats of the local cache. |
| 113 | + """ |
| 114 | + return len(self.data.texts), self.data.embeddings.shape |
0 commit comments