Back to all articlesAI आणि एजेंट

रीस्टार्ट टिकवून राहणारी Agent Memory ची अंमलबजावणी (Part 4)

Memory that survives restarts

Write policythe hard part is what to store
Recallrelevance + recency + importance
Consolidationepisodes → durable facts
SQLitedurable across process restarts

A memory round-trip

Recall is a decorator: the agent loop stays unchanged.

  1. 01
    episodeone completed step
  2. 02
    gate: worth storing?write policy decides
  3. 03
    embed + INSERTSQLite + vector
  4. 04
    recall queryscore, then top-k
  5. 05
    inject ordered factsinto the next prompt
  6. 06
    consolidate on scheduleepisodes become facts

Part 3 Agent च्या प्रत्येक run ची सुरुवात शून्यापासून होते. तो त्याच corpus पुन्हा शोधतो, तीच तथ्ये पुन्हा काढतो, आणि प्रक्रिया बाहेर पडताच उत्तर विसरतो. त्याच प्रश्नाला दोनदा विचारल्यास तुम्ही त्याच retrieval साठी दोनदा भरता, आणि तेच उत्तर मिळण्याची हमी नसते.

नेहमीचा उपाय म्हणजे सर्व काही vector database मध्ये ओतणे. हे एका स्पष्ट कारणाने अपयशी ठरते: vector store तुम्हाला similarity देतो, पण memory ला selection हवा आहे. 60 दिवसांपूर्वीचे observation जुने असू शकते हे similarity सांगू शकत नाही; एक-शब्द tool output एका पंक्तीस योग्य नाही हेही; आणि एका विषयावरील दोन वाक्ये नवीन मूल्यासह एकच तथ्य आहेत हेही सांगू शकत नाही. हे धोरणात्मक निर्णय आहेत, आणि ते तुम्ही वाचू शकाल अशा कोडमध्ये असले पाहिजेत.

हा भाग त्या धोरण स्तराची रचना करतो: तीन memory स्तर, स्पष्ट गुणांसह write gate, relevance ला recency व importance ने गुणणारी recall, आणि पुन्हा येणाऱ्या episodes ला facts मध्ये पुढे नेणारी consolidation पायरी. साठवण SQLite — एक फाइल, दोन टेबल, कोणतीही सेवा नाही.

ही अर्थव्यवस्था सांगण्यासारखी आहे, कारण ती गुंतागुंत न्याय्य ठरवते. Part 2 च्या Agent मध्ये एका tool कॉलमध्ये सुमारे 600 token येतात, आणि चार-शोधांच्या run मध्ये तो टाकणाऱ्या पुराव्यावर 2,400 context token खर्च होतात. एका आठवलेल्या fact चा memory block मध्ये सुमारे 30 token खर्च असतो. त्याच संशोधन प्रश्नाला दोनदा विचारल्यावर आठवण ठेवणे हे पुन्हा शोधण्यापेक्षा स्वस्त ठरते — आणि पुन्हा शोधण्यापेक्षा वेगळे म्हणजे, एका memory पंक्तीमुळे मॉडेलला एक आकडा परत मिळवण्यासाठी तीन परिच्छेद पुन्हा वाचावे लागत नाहीत. बचत अनेक run मध्ये वाढते; जोखीम (जुनी, विष दिलेली, किंवा असंबद्ध memories) हाच या लेखाच्या उरलेल्या भागात नियंत्रित करायचा विषय आहे.

तुम्ही तयार करणार आहात

memory.py मॉड्यूल चार घटकांसह:

  • MemoryStore — दोन टेबलसह SQLite साठवण. episodes मध्ये काय घडले ते आहे; facts मध्ये काय खरे आहे ते आहे,एक मानक विषयाच्या कॉलीने.
  • WritePolicy — observation एका पंक्तीस पात्र आहे का ते ठरवणारे स्कोरिंग फंक्शन, मागे UNIQUE dedupe key आहे.
  • AgentMemory — मुख्य इंटरफेस (façade): remember, recall, context_block, consolidate, record_run.
  • PrefixLLM + MemoryAgent — टाकणे व समन्वय, त्यामुळे run नियोजन करण्यापूर्वी आठवते आणि उत्तर दिल्यावर परत लिहिते.

स्तर तुमच्या जवळच्या कोडशी जुळतात. Working memory म्हणजे history यादी — ती AgentLoop च्या आत आहे व Part 3 च्या ContextBudget ने मर्यादित आहे. Episodic memory म्हणजे episodes टेबल. Semantic memory म्हणजे facts टेबल. फक्त शेवटची दोन टिकतात, आणि ही असमानताच रचना आहे: एका run ची कच्ची नोंद उद्या काहीच कामाची नाही, पण तिने शोधलेले तथ्य तसे नाही.

पूर्वअटी

  • Part 1–3. memory.py हा AgentLoop, LLMClient, Message व build_tools ला contracts.py मधून import करतो.
  • Python 3.10+, फक्त standard library (sqlite3, re, math, time).
  • डेटाबेस फाइलसाठी लिहिण्यायोग्य मार्ग. चाचण्यांसाठी :memory: वापरा; खालील चाचण्याही तसेच करत.

अजून embedding मॉडेल नाही. येथे recall हा lexical आहे — stopword काढून token ओव्हरलॅप. हा एक जाणीवपूर्वक घेतलेला व मोजता येणारा मर्यादा आहे: Agent स्वतः तयार केलेल्या शब्दसंग्रहासाठी हे काम करते, पॅराफ्रेजसाठी अपयशी ठरते. Part 5 स्कोरिंग फंक्शनला खऱ्या retriever ने बदलते व हे टेबल-स्वरूप तसेच ठेवते.

write policy हाच कठीण भाग

साठवण सोपी; निवड कठीण. तुम्ही प्रत्येक tool निकाल लिहिल्यास टेबल पायऱ्यांसह रेषीय वाढते व गोंधळ वाढत असताना recall गुणवत्ता घटते. काहीही न लिहिल्यास तुमच्याकडे memory नाही. हा gate असा फंक्शन असला पाहिजे ज्यावर वाद करता येईल, prompt मध्ये दडलेला heuristic नाही.

खालील स्कोर जोडणारा व तपासण्यायोग्य आहे. प्रत्येक नियम एका विशिष्ट अपयशामुळे आहे:

from __future__ import annotations
from dataclasses import dataclass, field
import json
import math
import os
import re
import sqlite3
import time
from contracts import AgentLoop, ErrorCode, LLMClient, Message, ToolResult
SCHEMA = """
CREATE TABLE IF NOT EXISTS episodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dedupe_key TEXT NOT NULL UNIQUE,
run_id TEXT NOT NULL,
kind TEXT NOT NULL,
content TEXT NOT NULL,
importance REAL NOT NULL,
created_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS facts (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
confidence REAL NOT NULL,
mentions INTEGER NOT NULL DEFAULT 1,
updated_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_episodes_created ON episodes(created_at);
"""
def normalize_key(text: str) -> str:
"""Collapse a sentence to a comparison key: lowercase, alphanumeric, first 80 chars."""
cleaned = re.sub(r"[^a-z0-9 ]+", " ", text.lower())
return re.sub(r"\s+", " ", cleaned).strip()[:80]
STOP = frozenset("the and for with that this from are was were what when how why into than then".split())
def tokenize(text: str) -> list[str]:
return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if len(w) > 2 and w not in STOP]
@dataclass
class WritePolicy:
"""Decides what deserves a row. Cheap rules, applied before the write."""
min_importance: float = 0.5
max_content_chars: int = 800
def importance(self, text: str, kind: str, source: str) -> float:
score = 0.2
if 40 <= len(text) <= 600:
score += 0.2
if re.search(r"\d", text):
score += 0.2
if source == "tool":
score += 0.2
if source == "user":
score += 0.3
if kind == "decision":
score += 0.1
return round(min(1.0, score), 2)

वजनाला चार प्रश्नांची उत्तरे म्हणून वाचा. ते सामग्री वाहून नेण्याइतके लांब आहे का? 40–600 अक्षरे म्हणजे observation वाक्य असते, token (ok, no matches) किंवा दस्तऐवजाचा ढीग नाही. त्यात आकडा आहे का? प्रमाण असलेली तथ्येच आठवण्यास योग्य असतात — latency, मर्यादा, गणना, आवृत्त्या. आकडे observation ला खोटे ठरवण्यायोग्य बनवतात: p95 is 240 ms हे नव्या मोजमापाशी तपासता येते, the index is fast हे तपासता येत नाही. ते tool कडून आहे का वापरकर्त्याकडून? दोन्ही पुरावा; वापरकर्त्याची विधाने व tool observation ही Agent च्या स्वतःच्या reasoning पेक्षा वरची आहेत, ती सिस्टीममधील सर्वात कमी विश्वासार्ह स्रोत आहे. ते निर्णय आहे का? निर्णयाला एक दशांश अतिरिक्त मूल्य मिळते, कारण पुढच्या run ला काय आधीच प्रयत्न झाले हे माहीत असणे आवश्यक आहे.

वजनापेक्षा क्रम जास्त महत्त्वाचा आहे. या वजनांसह, ok ला 0.4 गुण मिळतो व तो टाकला जातो; आकडा असलेल्या 90-अक्षरी tool निकालाला 0.8 मिळतो व तो ठेवला जातो. या विभागाच्या शेवटच्या demo मध्ये हेच दिसते: तीन observation दिले, दोन पंक्त्या लिहिल्या.

स्कोरच्या बाहेर दोन रक्षक आहेत. max_content_chars=800 मोठे ढीग डेटाबेशी पोहोचण्यापूर्वीच टाकतो — 4,000-अक्षरी search निकाल म्हणजे दस्तऐवज, आणि दस्तऐवज retrieval index च्या (Part 5) मालकीचे असतात, प्रत्येक भविष्यातील run मध्ये पुन्हा टाकल्या जाणाऱ्या memory पंक्तीचे नाही. dedupe_key UNIQUE अट धोरण बदलल्यावरही दुब लिहिणे अशक्य करते, कारण insert IntegrityError उभा करतो व store तो पसरवल्याशिवाय False परत करतो.

Dedupe key बाबत इशारा देणे आवश्यक आहे. हा मानक मजकूराच्या पहिल्या 80 अक्षरांवर कापलेला आहे, म्हणून 80-अक्षरी सुरुवात सामायिक करणारी दोन observation एकत्र सुरकुतात. हे पुन्हा येणाऱ्या वाक्यासाठी बरोबर आहे, पण search returned 12 results for agent loop सारख्या template लॉग पंक्तीसाठी चूक आहे, जिथे फक्त शेवटचा आकडा बदलतो. तुमची tool टेंपलेटेड output देत असल्यास सामग्रीऐवजी (tool, argument_hash) ला key करा — Part 2 मध्ये idempotency साठी तुम्ही बनवलेला तोच key.

Recall: relevance फक्त एक तृतीयांश

आठवलेले तथ्य तेव्हा उपयुक्त ठरते जेव्हा ते वर्तमान उद्दिष्टाविषयी असेल, अजून खरे राहण्याइतके नवीन असेल, आणि token साठी किमतीचे म्हणून महत्त्वाचे असेल. हे तीन घटक गुणणे कच्चे आहे, पण त्यातील एकाही घटकापेक्षा चांगले आहे, आणि प्रत्येक घटक तपासता येईल.

@dataclass
class Episode:
id: int
content: str
kind: str
importance: float
created_at: float
score: float = 0.0
@dataclass
class Fact:
key: str
value: str
confidence: float
mentions: int
updated_at: float
score: float = 0.0
class MemoryStore:
"""SQLite-backed persistence. One connection, two tables, no ORM."""
def __init__(self, path: str = ":memory:") -> None:
self.conn = sqlite3.connect(path)
self.conn.row_factory = sqlite3.Row
self.conn.executescript(SCHEMA)
def add_episode(self, dedupe_key: str, run_id: str, kind: str, content: str,
importance: float, now: float) -> bool:
try:
self.conn.execute(
"INSERT INTO episodes (dedupe_key, run_id, kind, content, importance, created_at)"
" VALUES (?, ?, ?, ?, ?, ?)",
(dedupe_key, run_id, kind, content, importance, now),
)
self.conn.commit()
return True
except sqlite3.IntegrityError:
return False
def load_episodes(self, limit: int = 500) -> list[Episode]:
rows = self.conn.execute(
"SELECT id, content, kind, importance, created_at FROM episodes"
" ORDER BY created_at DESC LIMIT ?", (limit,)
).fetchall()
return [Episode(r["id"], r["content"], r["kind"], r["importance"], r["created_at"])
for r in rows]
def upsert_fact(self, key: str, value: str, confidence: float, now: float) -> None:
self.conn.execute(
"INSERT INTO facts (key, value, confidence, mentions, updated_at) VALUES (?, ?, ?, 1, ?)"
" ON CONFLICT(key) DO UPDATE SET"
" value = excluded.value,"
" confidence = MIN(0.95, facts.confidence + 0.15),"
" mentions = facts.mentions + 1,"
" updated_at = excluded.updated_at",
(key, value, confidence, now),
)
self.conn.commit()
def load_facts(self) -> list[Fact]:
rows = self.conn.execute(
"SELECT key, value, confidence, mentions, updated_at FROM facts"
" ORDER BY confidence DESC, updated_at DESC"
).fetchall()
return [Fact(r["key"], r["value"], r["confidence"], r["mentions"], r["updated_at"])
for r in rows]
def close(self) -> None:
self.conn.close()
@dataclass
class Retriever:
half_life_days: float = 14.0
recency_weight: float = 0.5
def score(self, query_tokens: set[str], text: str, importance: float,
age_days: float) -> float:
overlap = len(query_tokens & set(tokenize(text)))
if overlap == 0:
return 0.0
relevance = overlap / math.sqrt(len(query_tokens) + 1)
recency = 0.5 ** (age_days / self.half_life_days)
return relevance * (1.0 + self.recency_weight * recency) * (0.5 + importance)

score चे तीन गुणधर्म भार सांभाळतात.

शून्य ओव्हरलॅप म्हणजे छोटा गुण नाही, शून्य गुण. Lexical जुळणीत, असंबद्ध episode कडे कोणतीही खूण नसते, आणि तिला recency बोनसने आत सोडणे context block दूषित करते. आधी परत येणे हेच test_relevance_filters_unrelated_episodes चाचणी पूर्ण करते.

Relevance चे sqrt(len(query_tokens) + 1) ने मानकीकरण. नसल्यास लांब उद्दिष्ट जास्त जुळणी गोळा करते व लांब प्रश्न क्रमांकनावर प्रभुत्व गाजवतात, म्हणून वापरकर्त्याचा प्रश्न लांबल्यावर recall संचाचा आकार बदलतो. वर्गमूळ त्याला दाबते, पण लांब प्रश्नांना शून्य गुण मिळू देत नाही.

Recency हा कट-ऑफ नाही, अर्ध-आयुष्य (half-life) आहे. 0.5 ** (age_days / 14) आज 1.0 देतो, दोन आठवड्यांत 0.5, 60 दिवसांत 0.05. 30 दिवसांवर कडा (cliff) असल्यास तथ्य पूर्ण विश्वासार्ह किंवा अदृश्य ठरेल; क्षयामुळे importance घटक एका जुन्या पण मौल्यवान observation ला खेळात ठेवू शकतो, त्याच वेळी जुनी क्षुल्लक माहिती खाली ढकलतो. recency_weight=0.5 म्हणजे recency एका गुणाला जास्तीत जास्त 50% हलवू शकतो — दोन सारख्या तथ्यांमध्ये टाय ब्रेक करण्यास पुरेसे, relevance पूर्णपणे मागे टाकण्यास पुरेसे नाही.

1.0 + 0.5*recency व 0.5 + importance मधील असमानता जाणूनबुजून केली आहे: importance ला 0.5 चा आधार आहे, त्यामुळे एक जुना पण अत्यंत महत्त्वाचा episode अजून गुण मिळवतो, तर recency हा मर्यादित बोनस आहे.

Read path हा पूर्ण scan आहे, अन्यथा सांगणे प्रामाणिक ठरणार नाही. load_episodes() 500 पंक्त्या पर्यंत आणतो व प्रत्येकाला Python मध्ये गुण देतो — 500 वर ~2 ms, 50,000 वर ~200 ms, हा ते प्रति-पायरी बोलवणे थांबवण्याचा बिंदू आहे. स्वरूप न बदलता दोन उपाय काम करतात: SQL मध्ये वेळ-window टाका (WHERE created_at > ?), म्हणजे scan तुम्हाला खरोखर हव्या असलेल्या recency ने मर्यादित होतो; आणि प्रत्येक episode चे token संच cache करा, म्हणजे tokenize एका प्रश्नासाठी एकदा नाही तर एका पंक्तीसाठी एकदा चालतो. पहिला उपाय एक-ओळीचा बदल आहे व सामान्यतः candidate संच 80% कमी करतो; दुसरा म्हणजे episode id ते frozenset चा dict, लिहिण्यावेळी रद्द केला जातो.

Consolidation: episodes ला facts मध्ये बदलणे

Episodes लिहिण्यास स्वस्त, टाकण्यास महाग — जवळपास-डुप्लिकेटने भरलेला context block तेच तीनदा सांगण्यासाठी token खर्च करतो. Consolidation एका विषयावरील पुन्हा येणाऱ्या observation ला एका fact पंक्तीत गुंडाळतो.

class AgentMemory:
"""Write policy + hybrid recall + consolidation over a MemoryStore."""
def __init__(self, store: MemoryStore, policy: WritePolicy | None = None,
retriever: Retriever | None = None, clock=time.time) -> None:
self.store = store
self.policy = policy or WritePolicy()
self.retriever = retriever or Retriever()
self.clock = clock
def remember(self, run_id: str, text: str, kind: str = "observation",
source: str = "tool") -> bool:
text = text.strip()
if not text or len(text) > self.policy.max_content_chars:
return False
importance = self.policy.importance(text, kind, source)
if importance < self.policy.min_importance:
return False
return self.store.add_episode(normalize_key(text), run_id, kind, text,
importance, self.clock())
def record_run(self, run_id: str, goal: str, answer: str, steps: int) -> bool:
summary = "goal: %s | answer: %s | steps: %d" % (goal[:120], answer[:200], steps)
return self.remember(run_id, summary, kind="run", source="user")
def recall(self, query: str, k: int = 5, now: float | None = None) -> list[Episode]:
now = self.clock() if now is None else now
q = set(tokenize(query))
if not q:
return []
scored = []
for ep in self.store.load_episodes():
age_days = max(0.0, (now - ep.created_at) / 86400.0)
ep.score = self.retriever.score(q, ep.content, ep.importance, age_days)
if ep.score > 0:
scored.append(ep)
scored.sort(key=lambda e: e.score, reverse=True)
return scored[:k]
def context_block(self, query: str, k: int = 5, max_chars: int = 1100) -> str:
lines = []
for fact in self.store.load_facts()[:5]:
lines.append("- fact[%s]: %s (confidence %.2f)" % (fact.key, fact.value, fact.confidence))
for ep in self.recall(query, k=k):
lines.append("- episode[%d]: %s" % (ep.id, ep.content[:200]))
if not lines:
return ""
text = "MEMORY (cite as fact[key] or episode[id]; ignore if contradicted by new evidence):\n"
text += "\n".join(lines)
return text[:max_chars]
def consolidate(self) -> int:
"""Fold repeated 'key: value' observations into facts. Returns facts touched."""
touched = 0
for ep in self.store.load_episodes():
if ep.kind != "observation":
continue
m = re.match(r"^([a-z][a-z0-9 _-]{2,40})\s*[:=]\s*(.{3,200})$", ep.content.strip(), re.I)
if not m:
continue
key = normalize_key(m.group(1))
self.store.upsert_fact(key, m.group(2).strip(), 0.5, ep.created_at)
touched += 1
return touched

upsert_fact मध्येच रसाचे अर्थलक्षण आहे. Conflict वर तो मूल्यावर लिहितो, mentions वाढवतो, आणि confidence ला 0.15 ने वाढवतो, 0.95 वर मर्यादित ठेवतो. पुन्हा लिहिणे हे योग्य डिफॉल्ट आहे: एका key चे नवीन मोजमाप बहुतांशी चांगले असते, आणि दोन्ही ठेवल्यास कोणते नवीन आहे हे न कळता मॉडेलला दोन आकड्यांमध्ये निर्णय घ्यावा लागतो. Mentions ची संख्या म्हणजे पुरावा: एक mention म्हणजे किस्सा, तीन म्हणजे नमुना, व confidence ते दर्शवतो. 0.95 ची मर्यादा एका तथ्याला शंभरदा पुन्हा सांगितल्यावर अखंडित करता न येणारे करू न देण्यासाठी आहे — नवीन observation ने नेहमी ते बदलू शकले पाहिजे.

consolidate जाणूनबुजून साधा आहे: key: value किंवा key = value साठी regex, फक्त observation वर. हा offline चालतो, काहीही खर्च नाही, व तथ्य कल्पू शकत नाही. Extraction दर हा प्रामाणिक इशारा आहे — मोकळ्या गद्यात तो बहुतांश तथ्ये चुकवतो. हे स्वीकार्य आहे, कारण तो काढलेली तथ्ये खऱ्या observation चे शब्दशः उपखंड आहेत, आणि Part 5 एक retriever आणतो जो प्रति-प्रश्न reasoning अत्यावश्यक करत नाही.

context_block चे शीर्षक हा छोटा पण खरा अभियांत्रिकी भाग आहे. cite as fact[key] or episode[id] आठवणीला पंक्तीशी जोडून दर्शवते, आणि ignore if contradicted by new evidence असे अपयश रोखते जिथे जुने तथ्य, prompt मध्ये आधी टाकल्यामुळे नव्या tool निकालावर मात करते.

टाकण्याचा क्रम, व तो decorator का आहे

PrefixLLM पहिल्या system संदेशाला पुन्हा लिहितो. context बजेट मोजण्याच्या आधी हा चालला पाहिजे, नाहीतर memory block बजेटने आधीच context बसला असे ठरवल्यावर जोडला जाईल व विनंती overflow होईल.

class PrefixLLM(LLMClient):
"""Injects a memory block into the system message before anything else sees it."""
def __init__(self, inner: LLMClient, prefix: str) -> None:
self.inner = inner
self.prefix = prefix
def complete(self, messages: list[Message], tools: list[dict]) -> dict:
if not self.prefix:
return self.inner.complete(messages, tools)
patched = [
Message(role=m.role, content=m.content + "\n\n" + self.prefix, name=m.name)
if m.role == "system" and i == 0 else m
for i, m in enumerate(messages)
]
return self.inner.complete(patched, tools)
class MemoryAgent:
"""One run = recall, inject, execute, write back. Memories never outlive the loop silently."""
def __init__(self, llm: LLMClient, tools: list, memory: AgentMemory, max_steps: int = 8) -> None:
self.llm = llm
self.tools = tools
self.memory = memory
self.max_steps = max_steps
self.last_trace: list[dict] = []
def run(self, goal: str, run_id: str = "run") -> str:
block = self.memory.context_block(goal)
loop = AgentLoop(PrefixLLM(self.llm, block), self.tools, self.max_steps)
answer = loop.run(goal)
self.last_trace = loop.trace
self.memory.record_run(run_id, goal, answer, len(loop.trace))
return answer

संपूर्ण stack MemoryAgent → PrefixLLM → BudgetedLLM → RetryingLLM → HTTPClient. उजवीकडून डावीकडे वाचा: आधी HTTP, त्याभोवती retries, retries भोवती budget, budget च्या बाहेर memory prefix. बजेटने context मोजल्यावर टाकलेला memory block बजेटला दिसत नाही व window overflow करतो — Part 3 चीच तो क्रम चूक, एक स्तर वर.

MemoryAgent प्रत्येक run साठी नवा AgentLoop तयार करतो, म्हणून history कधीही run मध्ये लीक होत नाही. Working memory ला अगदी एक run इतकी लांबी हवी; loop पुन्हा वापरल्यास प्रश्नांना ओलांडून वाढणारी history व दुसरा प्रश्न विचारण्यापूर्वीच संक्षिप्त करू लागणारा बजेट मिळतो.

हे demo_memory.py म्हणून चालवा, म्हणजे write policy output मध्ये दिसते:

from memory import AgentMemory, MemoryStore
def demo() -> None:
store = MemoryStore(":memory:")
memory = AgentMemory(store, clock=lambda: 1_700_000_000.0)
memory.remember("r0", "Agent loop: repeats observe decide act over 3 phases", source="tool")
memory.remember("r0", "token budget: cap input at 6000 tokens per call", source="tool")
memory.remember("r0", "ok", source="tool")
print("consolidated facts:", memory.consolidate())
print(memory.context_block("how does the agent loop work?"))
print("episodes stored:", len(store.load_episodes()))
if __name__ == "__main__":
demo()
consolidated facts: 2
MEMORY (cite as fact[key] or episode[id]; ignore if contradicted by new evidence):
- fact[token budget]: cap input at 6000 tokens per call (confidence 0.50)
- fact[agent loop]: repeats observe decide act over 3 phases (confidence 0.50)
- episode[1]: Agent loop: repeats observe decide act over 3 phases
episodes stored: 2

तीन observation दिले, दोन साठवले. ok ला 0.4 गुण मिळाले व ते टेबलपर्यंत पोहोचले नाही. Recall block मध्ये fact व ते निर्माण करणारा episode दोघे आहेत, कारण दोघेही प्रश्नाशी जुळतात — ही पुनरावृत्ती दोन पंक्त्यांत ठीक आहे, consolidation व max_chars हेच ते मर्यादित करण्यासाठी आहेत.

अपयश प्रकार व त्यांना हाताळण्याचा मार्ग

अपयश प्रत्यक्षात काय होते येथे हाताळणी अजून खराब
प्रत्येक tool निकाल साठवला गेला टेबल पायऱ्यांसह वाढते, recall गोंधळाने भरते Importance gate 0.5 पेक्षा कमी टाकतो बोलका पण निरुपयोगी tool अजूनही 0.8 मिळवतो
त्याच वाक्याची दर run ला नोंद duplicate पंक्त्या recall दाबतात dedupe_key UNIQUE + IntegrityError → False template लॉगच्या 80-अक्षरी सुरुवातीत टकराव
जुने तथ्य नव्या पुराव्यावर मात करते आधी टाकल्यामुळे जुने मूल्य जिंकते Recency क्षय + confidence मर्यादा + शीर्षक सूचना विरोध-शोध नाही; शेवटची नोंद जिंकते
Memory सदैव वाढते टेबल scan recall मंद करतो load_episodes(limit=500) scan मर्यादित करतो जुन्या पंक्त्या कधीही काढल्या जात नाहीत; retention job हवा
विष दिलेली memory tool निकालातील सूचना एका “fact” चे रूप घेते काहीही नाही — शब्दशः साठवले जाते Prompt-injection संरक्षण Part 11 मध्ये येईल
रिक्त recall मॉडेल काहीही माहीत नसल्यासारखे वागते context_block "" परत करतो, PrefixLLM तसेच सोडतो memory पाहिली हा संकेत मॉडेलकडे नाही
घड्याळ विषमता किंवा आयात केलेल्या पंक्त्या ऋण वय recency वाढवते max(0.0, ...) वय आवळते भविष्यातील पंक्त्यांना पूर्ण विश्वास मिळतो

विष देणारी पंक्ती तुम्हाला चिंता वाटली पाहिजे. Memory store म्हणजे अशा मजकुराची टिकाऊ साठवण जे मॉडेल नंतर सूचना म्हणून वाचते. अविश्वसनीय tool परत केलेली कोणतीही गोष्ट fact बनून प्रत्येक भविष्यातील run मध्ये पुन्हा टाकली जाऊ शकते. Part 11 provenance व स्वच्छता जोडेपर्यंत source="tool" memories ला अविश्वसनीय माना व ignore if contradicted सूचना ठेवा — हा एक शमन आहे, संरक्षण नाही.

तडजोडी (Trade-offs)

निर्णय पर्याय आम्ही हा का निवडला खर्च
SQLite फाइल Vector database एक फाइल, व्यवहार, सेवा नाही Semantic शोध नाही; फक्त lexical
Lexical ओव्हरलॅप स्कोरिंग Embedding समानता निश्चित, शून्य खर्च, debug करता येणारे पॅराफ्रेज व समानार्थी शब्दांवर अपयश
लिहिण्यावेळी importance gate सर्व साठवून वाचताना गाळणे टेबल छोटे, scan वेगवान राहते टाकलेली observation परत मिळत नाही
Conflict वर facts पुन्हा लिहिणे Append-only fact इतिहास नवीन मूल्य बहुतांशी बरोबर; वाचन सोपे ‘गेल्या आठवड्यात आम्ही काय मानत होतो’ सांगता येत नाही
Regex consolidation LLM extraction Offline, मोफत, तथ्य कल्पू शकत नाही मोकळ्या गद्यात कमी recall
प्रत्येक run ला नवा AgentLoop एक loop पुन्हा वापरणे Working memory एका run पुरती राहते प्रत्येक run ला trace व specs पुन्हा तयार
14-दिवसांचे half-life क्षय नाही तांत्रिक तथ्यांमध्ये जुन्याला मर्यादा घालते schema व्याख्यांसारख्या स्थिर तथ्यांसाठी चूक

Half-life हा असा parameter आहे ज्याला प्रत्येक डोमेननुसार पुन्हा पाहणे योग्य. चौदा दिवस latency व किंमतींच्या मोजमापांना जुळतात; schema किंवा उत्पादनाचे नाव एक वर्ष स्थिर असते, आणि त्याला क्षीण करणे केवळ नुकसान आहे. प्रामाणिक उपाय म्हणजे एका सार्वत्रिक आकड्याऐवजी kind नुसार half-life — हा Retriever मध्ये दहा-ओळींचा बदल व चांगला पहिला व्यायाम आहे.

चाचणी

अकरा चाचण्या, in-memory database, 20 ms च्या आत. या सहा अपरिवर्तनीय गुणधर्म (invariants) पकडतात:

import os
import tempfile
import unittest
from contracts import Message, ScriptedLLM, build_tools
from memory import (
AgentMemory, MemoryAgent, MemoryStore, PrefixLLM, WritePolicy,
normalize_key, tokenize,
)
DAY = 86400.0
NOW = 1_700_000_000.0
def fresh(clock=NOW):
store = MemoryStore(":memory:")
return AgentMemory(store, clock=lambda: clock), store
class TestMemory(unittest.TestCase):
def test_trivial_text_is_dropped(self):
memory, store = fresh()
self.assertFalse(memory.remember("r1", "ok", source="tool"))
self.assertEqual(store.load_episodes(), [])
def test_duplicate_content_is_stored_once(self):
memory, store = fresh()
text = "Retries are allowed only for rate_limited, timeout and upstream_error codes."
self.assertTrue(memory.remember("r1", text, source="tool"))
self.assertFalse(memory.remember("r2", text, source="tool"))
self.assertEqual(len(store.load_episodes()), 1)
def test_recent_episode_outranks_older_identical_one(self):
store = MemoryStore(":memory:")
old = AgentMemory(store, clock=lambda: NOW - 60 * DAY)
old.remember("r0", "Search index latency is 240 ms at p95 on the local corpus.")
new = AgentMemory(store, clock=lambda: NOW)
new.remember("r1", "Search index latency is 190 ms at p95 on the local corpus.")
hits = new.recall("search index latency", now=NOW)
self.assertGreater(hits[0].created_at, hits[1].created_at)
def test_repeated_observation_becomes_a_fact(self):
memory, store = fresh()
memory.remember("r1", "embedding dims: 768 for the base model", source="tool")
memory.remember("r2", "embedding dims: 1024 for the large model", source="tool")
memory.consolidate()
facts = store.load_facts()
self.assertEqual(len(facts), 1)
self.assertEqual(facts[0].key, "embedding dims")
self.assertEqual(facts[0].mentions, 2)
self.assertGreater(facts[0].confidence, 0.5)
def test_memory_survives_reopen(self):
path = os.path.join(tempfile.mkdtemp(), "memory.db")
first = MemoryStore(path)
AgentMemory(first, clock=lambda: NOW).remember(
"r1", "The corpus has 412 documents and 9 topic clusters.")
first.close()
second = MemoryStore(path)
self.assertEqual(len(second.load_episodes()), 1)
second.close()
def test_prefix_lands_in_system_message_only(self):
seen = {}
class Capture(ScriptedLLM):
def complete(self, messages, tools):
seen["messages"] = list(messages)
return {"type": "final", "content": "done"}
llm = PrefixLLM(Capture([]), "MEMORY: fact[loop] repeats")
llm.complete([Message("system", "sys"), Message("user", "goal")], [])
self.assertIn("MEMORY", seen["messages"][0].content)
self.assertEqual(seen["messages"][1].content, "goal")
if __name__ == "__main__":
unittest.main()

test_memory_survives_reopen हा संपूर्ण रचनेला न्याय्य ठरवतो. एक in-memory dict इतर सर्व चाचण्या उत्तीर्ण करतो, पण यात अपयशी ठरतो, आणि टिकाऊपणा हाच मुख्य उद्देश आहे — रीस्टार्टवर विसरणारा Agent म्हणजे फक्त महाग cache.

test_recent_episode_outranks_older_identical_one 60-दिवसांचा प्रकरण कोड करतो: 0.5 ** (60/14) = 0.051, म्हणून जुन्या episode कडे relevance गुण राहतो पण recency बोनस जातो. half_life_days ट्यून केल्यावर ही चाचणी अपयशी झाल्यास ते अपयश गूढ नसून माहितीपूर्ण आहे.

व्यायाम

  1. प्रकारनिहाय half-life. एका schema तथ्याला एक वर्ष स्थिरता आहे; latency मोजमाप आठवड्यात जुने होते. half_life_by_kind ला Retriever मध्ये जोडा, डिफॉल्टकडे परत जाण्याची सोय ठेवा, आणि एका प्रश्नासाठी 200-दिवसांचे जुने schema तथ्य 2-दिवसांच्या latency तथ्यावर मात करते हे दाखवणारी चाचणी लिहा.
  2. विरोध शोधणे. upsert_fact पुन्हा लिहिण्यापूर्वी नवीन मूल्याची तुलना जुन्याशी करा. दोन्हीत आकडे असून 20% पेक्षा जास्त फरक असल्यास नवीन मूल्य साठवा, पण दोन्ही वेळा असलेली एक conflicts पंक्ती नोंदवा. विरोध असल्यास context_block ने काय दाखवावे?
  3. मूल्यासह retention. prune(max_rows=5000) पद्धत जोडा व सर्वात कमी गुणाच्या episode काढा — वय नाही, गुण वापरा — तथ्यात उल्लेख केलेले काहीही ठेवा. 5,000-पंक्तीच्या टेबलवर दहा प्रश्नांच्या हाताने लेबल केलेल्या संचाचा वापर करून आधी व नंतर recall अचूकता कशी बदलते ते मोजा.

व्यायाम 2 memory ला database पासून वेगळे करतो: तथ्ये साठवणे सोपे आहे, विरोधी दोन तथ्यांपैकी कोणते मानायचे हे ठरवणे हा खरा प्रश्न आहे.

पुढे काय

तुमच्याकडे आता run पलिकडे आठवण ठेवणारा Agent आहे. तो करू शकत नसलेली गोष्ट म्हणजे मोठ्या corpus मधील परिच्छेद शोधणे — search हा Part 1 चा पाच-प्रवेशी dictionary आहे, आणि lexical recall फक्त Agent स्वतः लिहिलेल्या मजकुरावर काम करतो.

Part 5, Building a RAG retriever, त्या stub ला खऱ्या retrieval ने बदलतो: chunking रणनीती व उत्तर गुणवत्तेवर त्यांचा परिणाम, BM25 व embeddings एकत्र करणारी hybrid recall, आणि अचूकतेसाठी विलंब देवाणघेवाण करणारा reranker. MemoryStore स्वरूप तसेच राहते; search tool ला backend मिळतो, आणि तुम्ही आत्ता बनवलेला Retriever इंटरफेस episodes ऐवजी passages साठी पुन्हा वापरला जातो.

Get Ball — Ball

Get Ball

Reading in English? Switch language in the menu.