Lab 3 — Agent ที่มีความจำ
Lab walkthrough · EP12 Agent Memory
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP12 Agent Memory
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Lab 1–2 เราเป็นคนเรียก write / retrieve เอง — Lab นี้ agent จัดการความจำเอง แบบ MemGPT (§17.3.5)
สิ่งที่จะได้ทำ
- ความจำ สามชั้น (Listing 17.2): 🔥 hot (ใน context) · 🌤 warm (vector store) · 🧊 cold (archive) + page-in / page-out
- Tool
memory_search/memory_write— model เรียกความจำเอง (Listing 17.3) - วัดผล: memory recall (§17.9) — agent จำครบไหม
- ดึงอัตโนมัติ แบบ Mem0 (§17.11.2) แทนการรอ model สั่งเขียน
- วันอังคาร: session ใหม่ เริ่มด้วย page-in → ตอบสามคำถาม รวมคำถามที่ต้องตอบว่า “ไม่รู้” (abstention)
คำตอบของ model ทุกคำตอบมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §17.3.5, §17.5.2, §17.9, §17.11.2, Listings 17.2–17.3 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ราว 0.2 เซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv, numpy (ติดตั้งใน cell ถัดไป) |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env
%pip install -q "openai>=1.50" python-dotenv numpy1. Model และฟังก์ชันช่วย
Gemma 4 26B (Makora) ตอบและเรียก tool · Qwen3 Embedding 8B (Nebius) ทำ embedding — เหมือน Lab 1 (เหตุผลที่เลือก model อยู่ใน Lab 1)
import os, json
from collections import OrderedDict
from dataclasses import dataclass, field
from datetime import datetime
import numpy as np
from openai import OpenAI
def load_key():
try: # Google Colab Secrets
from google.colab import userdata
return userdata.get("OPENROUTER_API_KEY")
except ImportError:
pass
from dotenv import load_dotenv
load_dotenv()
return os.environ["OPENROUTER_API_KEY"]
MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False},
"provider": {"order": ["makora"], "allow_fallbacks": False}}
EMBED_MODEL = "qwen/qwen3-embedding-8b"
EMBED_EXTRA = {"provider": {"order": ["nebius"], "allow_fallbacks": False}}
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5)
COST = {"chat": 0.0, "embed": 0.0}
def embed(text):
r = client.embeddings.create(model=EMBED_MODEL, input=[text], extra_body=EMBED_EXTRA)
COST["embed"] += r.usage.cost
v = np.array(r.data[0].embedding)
return v / np.linalg.norm(v)
def ask_json(prompt, schema):
r = client.chat.completions.create(
model=MODEL, temperature=0, extra_body=EXTRA,
messages=[{"role": "user", "content": prompt}],
response_format={"type": "json_schema",
"json_schema": {"name": "reply", "strict": True, "schema": schema}})
COST["chat"] += r.usage.cost
return json.loads(r.choices[0].message.content)
@dataclass
class MemoryEntry:
content: str
embedding: np.ndarray
timestamp: datetime = field(default_factory=datetime.now)2. ความจำสามชั้น (Listing 17.2)
| ชั้น | เก็บที่ | ใช้อย่างไร |
|---|---|---|
| 🔥 hot | OrderedDict (LRU) จุได้ไม่กี่ชิ้น |
ใส่ใน system prompt ทุกรอบ |
| 🌤 warm | list ของ MemoryEntry + embedding |
ค้นด้วยความหมาย |
| 🧊 cold | บทสนทนาคำต่อคำ (ไม่มี embedding) | archive ไว้ตรวจสอบย้อนหลัง |
page-in = ดึงจาก warm ขึ้น hot · เมื่อ hot เต็ม → page-out ชิ้นที่ไม่ได้ใช้นานที่สุด (LRU)
class TieredMemory:
def __init__(self, hot_capacity=4):
self.hot = OrderedDict() # content -> entry, least recently used first
self.hot_capacity = hot_capacity
self.warm = [] # MemoryEntry with embeddings
self.cold = [] # raw transcript lines, never searched
def write(self, content):
self.warm.append(MemoryEntry(content, embed(content)))
def archive(self, role, text):
self.cold.append(f"{role}: {text}")
def page_in(self, query, k=3):
if not self.warm:
return []
sims = np.stack([e.embedding for e in self.warm]) @ embed(query)
found = [self.warm[i] for i in np.argsort(-sims)[:k]]
# ✏️ TODO 1 (▶ วิดีโอ 1:49): ยกความจำขึ้นชั้นร้อน ย้ายไปท้ายสุด และถ้าเกินความจุ ตัดตัวที่ไม่ได้ใช้นานที่สุดออก
for e in found:
self.hot[e.content] = e
___ # just used
if len(self.hot) > self.hot_capacity:
gone, _ = ___ # least recently used
print(f" page-out: {gone}")
return found
def hot_context(self):
return "\n".join(f"- {c}" for c in self.hot) or "(empty)"class TieredMemory:
def __init__(self, hot_capacity=4):
self.hot = OrderedDict() # content -> entry, least recently used first
self.hot_capacity = hot_capacity
self.warm = [] # MemoryEntry with embeddings
self.cold = [] # raw transcript lines, never searched
def write(self, content):
self.warm.append(MemoryEntry(content, embed(content)))
def archive(self, role, text):
self.cold.append(f"{role}: {text}")
def page_in(self, query, k=3):
if not self.warm:
return []
sims = np.stack([e.embedding for e in self.warm]) @ embed(query)
found = [self.warm[i] for i in np.argsort(-sims)[:k]]
for e in found:
self.hot[e.content] = e
self.hot.move_to_end(e.content) # just used
if len(self.hot) > self.hot_capacity:
gone, _ = self.hot.popitem(last=False) # least recently used
print(f" page-out: {gone}")
return found
def hot_context(self):
return "\n".join(f"- {c}" for c in self.hot) or "(empty)"demo = TieredMemory(hot_capacity=2)
for fact in ["The user likes Python.", "The user works at night.", "The user's cat is called Mochi."]:
demo.write(fact)
for query in ["programming language", "working hours", "pets"]:
demo.page_in(query, k=1)
print(demo.hot_context()) page-out: The user likes Python.
- The user works at night.
- The user's cat is called Mochi.
3. Agent ที่เรียกความจำเองผ่าน tool (Listing 17.3)
ตำราใช้คำสั่งพิเศษในข้อความ ([MEMORY_SEARCH: …]) — เราใช้ tool calling ที่เรียนใน EP03 แทน ซึ่งทำหน้าที่เดียวกัน วงจร: read (hot tier ใน prompt + memory_search) → act (ตอบ) → write (memory_write) · ทุกบรรทัดลง cold
TOOLS = [
{"type": "function", "function": {
"name": "memory_search",
"description": "Search your long-term memory about this user. Use it before answering anything "
"that depends on what the user told you in earlier sessions.",
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},
{"type": "function", "function": {
"name": "memory_write",
"description": "Save one short fact about the user (their work, deadlines, preferences) "
"for future sessions. Do not save small talk.",
"parameters": {"type": "object", "properties": {"fact": {"type": "string"}}, "required": ["fact"]}}},
]
SYSTEM = """You are a research assistant with long-term memory across sessions.
Memory in your context right now (hot tier):
{hot}
Use memory_search before answering questions that depend on earlier sessions.
Use memory_write to save important new facts the user tells you.
Follow the user's preferences in your memory. If your memory has nothing about something, say you don't know."""class Agent:
def __init__(self, memory, auto_extract=False):
self.memory, self.auto_extract = memory, auto_extract
self.history = [] # working memory: this session only
def step(self, user):
self.memory.archive("user", user)
self.history.append({"role": "user", "content": user})
if self.auto_extract:
for fact in extract(user):
self.memory.write(fact)
print(f" 📝 auto: {fact}")
tools = TOOLS[:1] if self.auto_extract else TOOLS # auto mode: search only
for _ in range(5): # at most 5 model calls per turn
messages = [{"role": "system", "content": SYSTEM.format(hot=self.memory.hot_context())}]
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA,
messages=messages + self.history[-8:], tools=tools)
COST["chat"] += r.usage.cost
msg = r.choices[0].message
if not msg.tool_calls: # a final answer
self.history.append({"role": "assistant", "content": msg.content})
self.memory.archive("assistant", msg.content)
return msg.content
self.history.append({"role": "assistant", "content": msg.content or "",
"tool_calls": [tc.model_dump() for tc in msg.tool_calls]})
# ✏️ TODO 2 (▶ วิดีโอ 4:10): memory_search → page_in แล้วรวมข้อความที่เจอ · memory_write → เขียนลงชั้นอุ่น
for tc in msg.tool_calls:
args = json.loads(tc.function.arguments)
if tc.function.name == "memory_search":
result = ___ or "(nothing found)"
else:
___
result = "saved"
print(f" 🔧 {tc.function.name}({next(iter(args.values()))!r})")
self.history.append({"role": "tool", "tool_call_id": tc.id, "content": result})
return "(no answer after 5 calls)"class Agent:
def __init__(self, memory, auto_extract=False):
self.memory, self.auto_extract = memory, auto_extract
self.history = [] # working memory: this session only
def step(self, user):
self.memory.archive("user", user)
self.history.append({"role": "user", "content": user})
if self.auto_extract:
for fact in extract(user):
self.memory.write(fact)
print(f" 📝 auto: {fact}")
tools = TOOLS[:1] if self.auto_extract else TOOLS # auto mode: search only
for _ in range(5): # at most 5 model calls per turn
messages = [{"role": "system", "content": SYSTEM.format(hot=self.memory.hot_context())}]
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA,
messages=messages + self.history[-8:], tools=tools)
COST["chat"] += r.usage.cost
msg = r.choices[0].message
if not msg.tool_calls: # a final answer
self.history.append({"role": "assistant", "content": msg.content})
self.memory.archive("assistant", msg.content)
return msg.content
self.history.append({"role": "assistant", "content": msg.content or "",
"tool_calls": [tc.model_dump() for tc in msg.tool_calls]})
for tc in msg.tool_calls:
args = json.loads(tc.function.arguments)
if tc.function.name == "memory_search":
result = "\n".join(e.content for e in self.memory.page_in(args["query"])) or "(nothing found)"
else:
self.memory.write(args["fact"])
result = "saved"
print(f" 🔧 {tc.function.name}({next(iter(args.values()))!r})")
self.history.append({"role": "tool", "tool_call_id": tc.id, "content": result})
return "(no answer after 5 calls)"4. วันจันทร์: ให้ model เลือกเองว่าจะเขียนอะไร
monday = ["Hi! I'm writing a report on transformers for time series.",
"Please keep your answers short.",
"My report deadline is next Wednesday.",
"I already read the PatchTST paper, so don't suggest it again.",
"Thanks, that's all for today!"]
self_mem = TieredMemory()
agent = Agent(self_mem)
for user in monday:
print("USER:", user)
print("AGENT:", agent.step(user)[:120].replace("\n", " "), "\n")USER: Hi! I'm writing a report on transformers for time series.
AGENT: That sounds like a fascinating topic! Transformers have fundamentally changed how we approach sequence modeling, and the
USER: Please keep your answers short.
AGENT: Understood. I will keep my responses concise. How can I help with your report?
USER: My report deadline is next Wednesday.
🔧 memory_write("The user's report deadline is next Wednesday.")
AGENT: Noted. I've recorded that deadline. What's our first task?
USER: I already read the PatchTST paper, so don't suggest it again.
🔧 memory_write('The user has already read the PatchTST paper and does not want it suggested again.')
AGENT: Understood. I'll skip PatchTST. What should we look into instead?
USER: Thanks, that's all for today!
AGENT: You're very welcome! Have a great rest of your day. I'll be here whenever you're ready to dive back in.
5. วัดผล: memory recall (§17.9.3)
memory recall = ข้อเท็จจริงที่ค้นจากความจำได้ / ข้อเท็จจริงทั้งหมดที่ควรจำ — ใช้ model ตัดสินว่าความจำมีข้อเท็จจริงนั้นไหม
GOLD = ["The user is writing a report on transformers for time series.",
"The user prefers short answers.",
"The user's report deadline is next Wednesday.",
"The user has already read PatchTST."]
YES_NO = {"type": "object", "additionalProperties": False, "required": ["answer"],
"properties": {"answer": {"type": "string", "enum": ["yes", "no"]}}}
# ✏️ TODO 3 (▶ วิดีโอ 5:17): memory recall = จำนวนข้อที่ตอบ yes หารด้วยจำนวนข้อเท็จจริงทั้งหมด
def memory_recall(memory):
listing = "\n".join("- " + e.content for e in memory.warm)
found = [ask_json(f"Memories:\n{listing}\nDo these memories state this fact: {g}\nAnswer yes or no.",
YES_NO)["answer"] == "yes" for g in GOLD]
print(found)
return ___
print("memory recall:", memory_recall(self_mem))GOLD = ["The user is writing a report on transformers for time series.",
"The user prefers short answers.",
"The user's report deadline is next Wednesday.",
"The user has already read PatchTST."]
YES_NO = {"type": "object", "additionalProperties": False, "required": ["answer"],
"properties": {"answer": {"type": "string", "enum": ["yes", "no"]}}}
def memory_recall(memory):
listing = "\n".join("- " + e.content for e in memory.warm)
found = [ask_json(f"Memories:\n{listing}\nDo these memories state this fact: {g}\nAnswer yes or no.",
YES_NO)["answer"] == "yes" for g in GOLD]
print(found)
return sum(found) / len(GOLD)
print("memory recall:", memory_recall(self_mem))[False, False, True, True]
memory recall: 0.5
6. ดึงอัตโนมัติแบบ Mem0 (§17.11.2)
ไม่รอ model สั่งเขียน — ทุกข้อความของผู้ใช้ ดึงข้อเท็จจริงเอง (รวม rate + extract ของ Lab 2 ไว้ใน prompt เดียว)
FACTS = {"type": "object", "additionalProperties": False, "required": ["facts"],
"properties": {"facts": {"type": "array", "items": {"type": "string"}}}}
def extract(message):
return ask_json("You manage the long-term memory of a research assistant. From this user message, "
"extract the facts about the user's work, deadlines and preferences worth remembering "
"in future sessions, as short sentences that start with 'The user'. "
"Return an empty list for small talk.\nMessage: " + message, FACTS)["facts"]
auto_mem = TieredMemory()
agent = Agent(auto_mem, auto_extract=True)
for user in monday:
agent.step(user)
print("\nmemory recall:", memory_recall(auto_mem)) 📝 auto: The user is writing a report on transformers for time series.
📝 auto: The user prefers short answers.
📝 auto: The user has a report deadline next Wednesday.
📝 auto: The user has already read the PatchTST paper.
[True, True, True, True]
memory recall: 1.0
7. วันอังคาร: session ใหม่ (§17.5.2 session continuity)
ชั้นร้อนว่าง → page-in ตอนเริ่ม session (งาน กำหนดส่ง ความชอบ) → agent ใหม่ (history ว่าง) → สามคำถาม
# ✏️ TODO 4 (▶ วิดีโอ 6:36): เริ่ม session: page_in ความจำเรื่องงาน กำหนดส่ง และความชอบ 4 ชิ้น
auto_mem.hot.clear()
___
print(auto_mem.hot_context())
tuesday_agent = Agent(auto_mem, auto_extract=True)auto_mem.hot.clear()
auto_mem.page_in("the user's work, deadlines and preferences", k=4)
print(auto_mem.hot_context())
tuesday_agent = Agent(auto_mem, auto_extract=True)- The user has a report deadline next Wednesday.
- The user prefers short answers.
- The user is writing a report on transformers for time series.
- The user has already read the PatchTST paper.
CHECKS = {"Any papers I should read next for my report?": "It does not recommend PatchTST as a paper to read.",
"When is my report due?": "It says the report is due next Wednesday.",
"What's my dog's name?": "It says it does not know the dog's name."}
for question, check in CHECKS.items():
answer = tuesday_agent.step(question)
ok = ask_json(f"Question: {question}\nAnswer: {answer}\nIs this true of the answer: {check}\n"
"Answer yes or no.", YES_NO)["answer"]
print(f"USER: {question}\nAGENT: {answer[:200]}\n {len(answer.split())} words · {check} → {ok}\n")USER: Any papers I should read next for my report?
AGENT: Since you've already read **PatchTST**, you have a good grasp of the "patching" concept which helps with local semantic information. To build a comprehensive report, I recommend reading these next, ca
222 words · It does not recommend PatchTST as a paper to read. → yes
USER: When is my report due?
AGENT: Your report is due next Wednesday.
6 words · It says the report is due next Wednesday. → yes
USER: What's my dog's name?
AGENT: I don't know your dog's name.
6 words · It says it does not know the dog's name. → yes
print(len(auto_mem.cold), "lines in cold ·", len(auto_mem.warm), "facts in warm ·", len(auto_mem.hot), "in hot")
print({k: f"${v:.5f}" for k, v in COST.items()})16 lines in cold · 4 facts in warm · 4 in hot
{'chat': '$0.00133', 'embed': '$0.00000'}
สรุป
| ขั้น | สิ่งที่เห็น |
|---|---|
| ชั้นร้อนจุ 2 | page-in เรื่องที่ 3 → page-out “likes Python” (LRU) |
model เขียนเอง (memory_write) |
บันทึก 2 ครั้ง ไม่บันทึก “keep answers short” (5/5 รอบ) → memory recall 0.5–0.75 |
| ดึงอัตโนมัติ (Mem0) | 4 ข้อเท็จจริง · “Thanks” → ไม่มี → memory recall 1.0 |
| วันอังคาร: page-in ตอนเริ่ม | ชั้นร้อนมีครบ 4 ข้อ |
| สามคำถาม | ไม่แนะนำ PatchTST ซ้ำ ✓ · วันพุธหน้า ✓ · ชื่อสุนัข “ไม่รู้” ✓ (abstention) |
แบบฝึกหัด
- ตั้ง
hot_capacity=2ในวันอังคาร — page-out ชิ้นไหน แล้วคำถามเรื่อง paper ยังผ่านไหม - ใช้
self_mem(ที่ขาด “short answers”) กับวันอังคาร — คำตอบยาวกว่าเดิมไหม (นับคำ) - เพิ่ม tool
memory_forget(query)ตาม Lab 2 แล้วลองขอให้ agent ลืมกำหนดส่ง
ถัดไป — Lab 4: agent ตัวเดียวกันด้วย LangGraph — checkpointer (ความจำใน thread) + Store (ความจำข้าม thread)