Lesson 67 — Beginner

Agent Memory Basics

Bina memory ke agent har turn par blank ho jaata hai. Is lesson mein pehle farak samjhenge conversation history, state, short-term aur long-term memory mein; phir memory ke chaaro operations (write → retrieve → update → forget), "kya yaad rakhein" wali selectivity aur trimming/summarization dekhenge.

⏱ 20 min• Beginner• MCP — Model Context Protocol

History, state, short-term, long-term

WHAT

History = messages jo abhi chal rahe conversation mein hain. State = task ki working info (plan, ids, intermediate results). Short-term = current window, long-term = persistent store se laaye curated facts, preferences aur summaries.

WHEN

Har turn par history/state chahiye hi chahiye. Long-term tab jab user alag sessions mein laute ya purani baat kaam aaye — "pichhli baar wahi error aaya tha".

WHERE

History messages list mein, state app ke objects/DB mein, long-term ek store mein (SQLite, vector index) jisse relevant memories retrieve hoti hain.

layer        | kya rakhta hai                        | kab tootta hai
-------------+---------------------------------------+--------------------
history      | current conversation messages         | session turn
state        | task ki working info — plan, ids, temp | task khatam
short-term   | recent turns + thoda working context   | window cap hit
long-term    | curated facts, prefs, summaries, past  | kabhi nahi (forget)

Confusion door karo: history record hai, memory decision hai. History mein sab messages hain; memory mein sirf wo jo aage kaam aaye. Agent banate waqt in layers ko alag-alag functions do — milti-julti rehti hain par responsibilities alag hain.

Short-term memory — rolling window

class ChatMemory:
    def __init__(self, keep_last=12, max_chars=6000):
        self.messages = []
        self.keep_last = keep_last
        self.max_chars = max_chars

    def add(self, role, text):
        self.messages.append({"role": role, "content": text})

    def window(self):
        msgs = self.messages[-self.keep_last:]      # recent turns hamesha
        text = "\n".join(m["content"] for m in msgs)
        if len(text) > self.max_chars:              # char budget bhi
            msgs = msgs[-6:]                        # aur kaat do
        return msgs

Short-term ka kaam hai chhoti rakho, recent rakho — recency limit (last N messages) aur size limit (chars/tokens) dono. Sirf recency kaafi nahi: ek lamba tool output poori window kha sakta hai.

Yaad rakho: Short-term memory ka default hota hai messages list hi — par usey ek class mein baandho, warna trimming ka decision kabhi bana hi nahi. Class = jagah jahan trim/summarize rules rehte hain.

Long-term memory — store + retrieve

class MemoryStore:
    def __init__(self):
        self.rows = []   # production mein SQLite ya vector store

    def write(self, kind, text):
        self.rows.append({"kind": kind, "text": text})  # fact | pref | summary

    def retrieve(self, query, k=3):
        return top_k(self.rows, query, k)  # keyword ya embedding similarity

    def update(self, idx, text):
        self.rows[idx]["text"] = text       # galat/purana fact sudhaaro

    def forget(self, idx):
        self.rows.pop(idx)                  # purana/galat hata do

Kya yaad rakhein aur kya bhool jaayein

Type hint: Memory entries mein kind laga do (fact / preference / summary / outcome) — retrieval par priority milti hai, aur update/forget aasaan ho jaata hai.

Growth — trim ya summarize

def maybe_summarize(memory):
    if count_tokens(memory.window()) > 5000:   # threshold tumhara
        summary = llm_summarize(memory.messages)
        memory.messages = [
            {"role": "system", "content": f"Pichhli baatchit ka summary: {summary}"},
            *memory.messages[-4:]               # thode recent bhi rakh do
        ]
# trim = purane messages hata do (sasta, fast)
# summarize = content ko short kar do (thoda mehnga, zyada rich)
# dono ka trigger hona chahiye — kabhi kabhi nahi, hamesha jab cap hit ho
Production rule: Memory growth unbounded hai — bina threshold ke do ghante mein window bhar jaayegi. Cap + trigger dono pehle se likho, error aane baad nahi.

Exercise

Question: Current task ki working information (plan, ids, intermediate results) kis layer mein rakhte hain? (ek shabd)

Question: Long-term store se relevance ke basis par memories dhoondhna kya kehlata hai? (ek shabd, English)

Question: Purane messages ko hata kar recent rakhne wala step ka naam? (ek shabd, English)

Question: Memory ke chaaro operations — write, retrieve, update aur ...? (ek shabd, English)

Common mistakes

Desi example: Class notes vs cheat-sheet

Roz ke class notes sab likhte hain (history/short-term) — par exam se pehle banaya cheat-sheet curated hai (long-term). Har page yaad rakhne ki zarurat nahi, sirf asli cheezon ki:

text
short-term: aaj ki class ke notes — session khatam toh file band
long-term:  final wala cheat-sheet — facts, formulas, apni galtiyan
retrieve:   paper mein zaroorat padi toh wahi page kholo, poora copy nahi
Interview angle — yahan se sawaal aate hain
  • Q: Conversation history aur state mein farak — ek example ke saath.
  • Q: Memory ke chaaro operations batao, har ek ka ek realistic example do.
  • Q: Retrieved memory vs poora history — context aur reliability dono ka angle samjhao.
  • Q: Trim aur summarize — kab choose karoge, trigger kaise set karoge?
Lesson complete?

Memory ke layers clear. Agla lesson — Multi-Agent Architectures — mein dekhenge kab ek agent kaafi nahi hota aur decomposition kaise karte hain.

Popular courses: Data Science Course in Lucknow · AI Course in Lucknow · Python Course in Lucknow · Power BI Course · Data Analytics Course