|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import os |
1 | 4 | import re |
2 | | -from typing import Tuple, List |
| 5 | +import tempfile |
| 6 | +from typing import Optional, Tuple, List |
3 | 7 | import numpy as np |
4 | 8 | from sklearn.feature_extraction.text import TfidfVectorizer |
5 | 9 | from sklearn.metrics.pairwise import cosine_similarity |
6 | 10 |
|
7 | 11 | SLUG = "memory" |
8 | 12 |
|
| 13 | +# Environment variable that opts a run in to file-backed memory. When it is set, |
| 14 | +# the Memory store loads any previously saved items on init and persists after |
| 15 | +# every add(); when it is unset the plugin behaves exactly as before (in-RAM, |
| 16 | +# reset per request). |
| 17 | +MEMORY_FILE_ENV = "OPTILLM_MEMORY_FILE" |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
9 | 21 | class Memory: |
10 | | - def __init__(self, max_size: int = 100): |
| 22 | + def __init__(self, max_size: int = 100, persist_path: Optional[str] = None): |
11 | 23 | self.max_size = max_size |
12 | 24 | self.items: List[str] = [] |
13 | 25 | self.vectorizer = TfidfVectorizer() |
14 | 26 | self.vectors = None |
15 | 27 | self.completion_tokens = 0 |
| 28 | + self.persist_path = persist_path |
| 29 | + if self.persist_path: |
| 30 | + self._load_from_file() |
16 | 31 |
|
17 | 32 | def add(self, item: str): |
18 | 33 | if len(self.items) >= self.max_size: |
19 | 34 | self.items.pop(0) |
20 | 35 | self.items.append(item) |
21 | 36 | self.vectors = None # Reset vectors to force recalculation |
| 37 | + if self.persist_path: |
| 38 | + self._save_to_file() |
| 39 | + |
| 40 | + def _load_from_file(self): |
| 41 | + """Load persisted items from ``persist_path`` (opt-in). |
| 42 | +
|
| 43 | + A missing file (first run) or a corrupt/unreadable one degrades |
| 44 | + gracefully to an empty in-memory store, so persistence can never make a |
| 45 | + request fail at startup. |
| 46 | + """ |
| 47 | + try: |
| 48 | + with open(self.persist_path, "r", encoding="utf-8") as f: |
| 49 | + data = json.load(f) |
| 50 | + except FileNotFoundError: |
| 51 | + return # nothing persisted yet |
| 52 | + except (OSError, ValueError) as e: |
| 53 | + logger.warning("Could not load memory from %s: %s", self.persist_path, e) |
| 54 | + return |
| 55 | + |
| 56 | + if not isinstance(data, list): |
| 57 | + logger.warning( |
| 58 | + "Ignoring memory file %s: expected a JSON list of strings", |
| 59 | + self.persist_path, |
| 60 | + ) |
| 61 | + return |
| 62 | + |
| 63 | + # Keep only strings and honour max_size (most recent items win). |
| 64 | + items = [x for x in data if isinstance(x, str)] |
| 65 | + self.items = items[-self.max_size:] |
| 66 | + self.vectors = None |
| 67 | + |
| 68 | + def _save_to_file(self): |
| 69 | + """Atomically persist the current items to ``persist_path`` (opt-in). |
| 70 | +
|
| 71 | + Writes to a temp file in the same directory and ``os.replace``s it into |
| 72 | + place so a crash mid-write cannot corrupt an existing store. Any I/O |
| 73 | + error is logged and swallowed rather than raised. |
| 74 | + """ |
| 75 | + try: |
| 76 | + directory = os.path.dirname(os.path.abspath(self.persist_path)) |
| 77 | + os.makedirs(directory, exist_ok=True) |
| 78 | + fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp") |
| 79 | + try: |
| 80 | + with os.fdopen(fd, "w", encoding="utf-8") as f: |
| 81 | + json.dump(self.items, f) |
| 82 | + os.replace(tmp_path, self.persist_path) |
| 83 | + finally: |
| 84 | + if os.path.exists(tmp_path): |
| 85 | + os.remove(tmp_path) |
| 86 | + except OSError as e: |
| 87 | + logger.warning("Could not save memory to %s: %s", self.persist_path, e) |
22 | 88 |
|
23 | 89 | def get_relevant(self, query: str, n: int = 10) -> List[str]: |
24 | 90 | if not self.items: |
@@ -91,7 +157,10 @@ def extract_key_information(system_message, text: str, query: str, client, model |
91 | 157 | return margins, response.usage.completion_tokens |
92 | 158 |
|
93 | 159 | def run(system_prompt: str, initial_query: str, client, model: str) -> Tuple[str, int]: |
94 | | - memory = Memory() |
| 160 | + # Opt-in file-backed memory: when OPTILLM_MEMORY_FILE is set, items persist |
| 161 | + # across requests; when unset, behaviour is unchanged (fresh in-RAM store). |
| 162 | + persist_path = os.environ.get(MEMORY_FILE_ENV) or None |
| 163 | + memory = Memory(persist_path=persist_path) |
95 | 164 | query, context = extract_query(initial_query) |
96 | 165 | completion_tokens = 0 |
97 | 166 |
|
|
0 commit comments