|
| 1 | +""" |
| 2 | +SummaryMemory — rolling LLM-generated compression memory backend. |
| 3 | +
|
| 4 | +Strategy: |
| 5 | + Keep the last `window_size` messages verbatim. |
| 6 | + Every time the buffer exceeds `window_size`, compress the overflow |
| 7 | + into a running summary using either: |
| 8 | + - LLM (Groq) when GROQ_API_KEY is set → high fidelity |
| 9 | + - Extractive otherwise → zero-cost fallback |
| 10 | +
|
| 11 | +This is conceptually how long-horizon chat assistants work: |
| 12 | +recent context stays sharp, old context becomes a compressed narrative. |
| 13 | +""" |
| 14 | + |
| 15 | +import os |
| 16 | +import re |
| 17 | +from typing import List, Dict |
| 18 | + |
| 19 | +from .base import BaseMemory |
| 20 | + |
| 21 | + |
| 22 | +# --------------------------------------------------------------------------- |
| 23 | +# Helpers |
| 24 | +# --------------------------------------------------------------------------- |
| 25 | + |
| 26 | +_FACT_PATTERNS = re.compile( |
| 27 | + r"(my \w[\w\s]+ is |i am |i'm |changed to |updated to |now is |" |
| 28 | + r"name|city|age|occupation|company|hobby|language|food|score|subject)", |
| 29 | + re.IGNORECASE, |
| 30 | +) |
| 31 | + |
| 32 | +_COMPRESS_SYSTEM = ( |
| 33 | + "You are a memory compressor for a conversational AI. " |
| 34 | + "Given a batch of conversation messages, extract and preserve EVERY personal fact, " |
| 35 | + "preference, update, and important detail. " |
| 36 | + "Merge these with the existing summary if one is provided. " |
| 37 | + "Output a single, compact paragraph of key facts — no filler, no opinions. " |
| 38 | + "Always prefer the NEWER value when a fact has been updated." |
| 39 | +) |
| 40 | + |
| 41 | + |
| 42 | +def _extractive_compress(messages: List[Dict], existing_summary: str = "") -> str: |
| 43 | + """ |
| 44 | + Zero-cost fallback: keep only lines that look like personal facts. |
| 45 | + Merges with any existing summary. |
| 46 | + """ |
| 47 | + kept: List[str] = [] |
| 48 | + |
| 49 | + # Re-include existing summary lines |
| 50 | + if existing_summary: |
| 51 | + kept.append(existing_summary) |
| 52 | + |
| 53 | + for msg in messages: |
| 54 | + content = msg.get("content", "") |
| 55 | + if _FACT_PATTERNS.search(content): |
| 56 | + kept.append(content.strip()) |
| 57 | + |
| 58 | + merged = " | ".join(kept) |
| 59 | + return merged[:800] if merged else "" |
| 60 | + |
| 61 | + |
| 62 | +def _llm_compress(messages: List[Dict], existing_summary: str, model: str) -> str: |
| 63 | + """LLM-powered compression via Groq.""" |
| 64 | + from utils.llm import chat |
| 65 | + |
| 66 | + batch_text = "\n".join( |
| 67 | + f"{m['role'].upper()}: {m['content']}" for m in messages |
| 68 | + ) |
| 69 | + user_content = "" |
| 70 | + if existing_summary: |
| 71 | + user_content += f"Existing summary:\n{existing_summary}\n\n" |
| 72 | + user_content += f"New messages to absorb:\n{batch_text}" |
| 73 | + |
| 74 | + result = chat( |
| 75 | + [ |
| 76 | + {"role": "system", "content": _COMPRESS_SYSTEM}, |
| 77 | + {"role": "user", "content": user_content}, |
| 78 | + ], |
| 79 | + model=model, |
| 80 | + temperature=0.0, |
| 81 | + max_tokens=200, |
| 82 | + ) |
| 83 | + # Fallback if LLM call failed |
| 84 | + if result.startswith("[LLM_ERROR"): |
| 85 | + return _extractive_compress(messages, existing_summary) |
| 86 | + return result.strip() |
| 87 | + |
| 88 | + |
| 89 | +# --------------------------------------------------------------------------- |
| 90 | +# SummaryMemory |
| 91 | +# --------------------------------------------------------------------------- |
| 92 | + |
| 93 | +class SummaryMemory(BaseMemory): |
| 94 | + """ |
| 95 | + Rolling-summary memory backend. |
| 96 | +
|
| 97 | + Parameters |
| 98 | + ---------- |
| 99 | + window_size : int |
| 100 | + Number of most-recent messages kept verbatim. |
| 101 | + use_llm : bool | None |
| 102 | + True → always use Groq for compression. |
| 103 | + False → always use extractive fallback. |
| 104 | + None → auto-detect from GROQ_API_KEY env var. |
| 105 | + model : str |
| 106 | + Groq model name used for compression calls. |
| 107 | + """ |
| 108 | + |
| 109 | + name = "summary" |
| 110 | + |
| 111 | + def __init__( |
| 112 | + self, |
| 113 | + window_size: int = 20, |
| 114 | + use_llm: bool | None = None, |
| 115 | + model: str = "llama-3.1-8b-instant", |
| 116 | + ) -> None: |
| 117 | + self.window_size = window_size |
| 118 | + self.model = model |
| 119 | + self._use_llm: bool = ( |
| 120 | + bool(os.getenv("GROQ_API_KEY")) if use_llm is None else use_llm |
| 121 | + ) |
| 122 | + |
| 123 | + self.recent: List[Dict] = [] |
| 124 | + self.summary: str = "" |
| 125 | + |
| 126 | + # ------------------------------------------------------------------ |
| 127 | + # BaseMemory interface |
| 128 | + # ------------------------------------------------------------------ |
| 129 | + |
| 130 | + def add_message(self, role: str, content: str, turn: int) -> None: |
| 131 | + self.recent.append({"role": role, "content": content, "turn": turn}) |
| 132 | + # Compress whenever the verbatim buffer grows past the window |
| 133 | + if len(self.recent) > self.window_size: |
| 134 | + self._compress() |
| 135 | + |
| 136 | + def get_context(self, query: str, current_turn: int) -> List[Dict]: |
| 137 | + context: List[Dict] = [] |
| 138 | + if self.summary: |
| 139 | + context.append({ |
| 140 | + "role": "system", |
| 141 | + "content": f"[Conversation summary] {self.summary}", |
| 142 | + }) |
| 143 | + for msg in self.recent: |
| 144 | + context.append({"role": msg["role"], "content": msg["content"]}) |
| 145 | + return context |
| 146 | + |
| 147 | + def reset(self) -> None: |
| 148 | + self.recent = [] |
| 149 | + self.summary = "" |
| 150 | + |
| 151 | + # ------------------------------------------------------------------ |
| 152 | + # Internal |
| 153 | + # ------------------------------------------------------------------ |
| 154 | + |
| 155 | + def _compress(self) -> None: |
| 156 | + """Move the overflow (everything before the window) into the summary.""" |
| 157 | + overflow = self.recent[: len(self.recent) - self.window_size] |
| 158 | + self.recent = self.recent[-self.window_size :] |
| 159 | + |
| 160 | + if self._use_llm: |
| 161 | + self.summary = _llm_compress(overflow, self.summary, self.model) |
| 162 | + else: |
| 163 | + self.summary = _extractive_compress(overflow, self.summary) |
| 164 | + |
| 165 | + # ------------------------------------------------------------------ |
| 166 | + # Diagnostics |
| 167 | + # ------------------------------------------------------------------ |
| 168 | + |
| 169 | + @property |
| 170 | + def mode(self) -> str: |
| 171 | + return "llm" if self._use_llm else "extractive" |
| 172 | + |
| 173 | + def __repr__(self) -> str: |
| 174 | + return ( |
| 175 | + f"SummaryMemory(window={self.window_size}, " |
| 176 | + f"mode={self.mode}, " |
| 177 | + f"recent={len(self.recent)}, " |
| 178 | + f"summary_len={len(self.summary)})" |
| 179 | + ) |
0 commit comments