Lab 4 — Agent ตัวเดิมด้วย LangGraph
Lab walkthrough · EP12 Agent Memory
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP12 Agent Memory
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Lab 3 เราเขียนความจำเองทุกชั้น — Lab นี้สร้าง agent แบบ Mem0 ตัวเดิมด้วย LangGraph
| Lab 3 (เขียนเอง) | LangGraph |
|---|---|
history ของ session (working memory) |
checkpointer + thread_id |
ชั้นอุ่น + page_in(query) |
Store + store.search(namespace, query=…) |
extract() ทุกข้อความ |
node remember |
| ชั้นเย็น (บทสนทนาทั้งหมด) | checkpointer เก็บทุกข้อความของทุก thread |
| — | namespace ต่อผู้ใช้: ("memories", user_id) |
คำตอบของ model ทุกคำตอบมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §17.5, §17.10.3 — CC BY-SA 4.0 · LangGraph (MIT)
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึง 0.1 เซ็นต์ดอลลาร์) |
| Packages | langgraph==1.2.16 (เวอร์ชันเดียวกับ EP11), openai, python-dotenv, numpy |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env
%pip install -q "langgraph==1.2.16" "openai>=1.50" python-dotenv numpy1. Model และฟังก์ชันช่วยจาก Lab 3
Gemma 4 26B (Makora) · Qwen3 Embedding 8B (Nebius) — เหตุผลที่เลือก model อยู่ใน Lab 1 extract() คือฟังก์ชันดึงข้อเท็จจริงแบบ Mem0 จาก Lab 3 ทุกตัวอักษร
import os, json, operator, uuid
from typing import Annotated, TypedDict
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 chat(messages):
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA,
messages=messages)
COST["chat"] += r.usage.cost
return r.choices[0].message.content
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)
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"]def embed_texts(texts):
r = client.embeddings.create(model=EMBED_MODEL, input=list(texts), extra_body=EMBED_EXTRA)
COST["embed"] += r.usage.cost
return [d.embedding for d in r.data]2. Store: ความจำข้าม thread
InMemoryStore(index=…) — เก็บ value (dict) ไว้ใต้ namespace และ key · index ทำ embedding ของ field text ให้ค้นด้วยความหมายได้ (ระบบจริงใช้ PostgresStore แทน — API เดียวกัน)
from langgraph.store.memory import InMemoryStore
store = InMemoryStore(index={"embed": embed_texts, "dims": 4096, "fields": ["text"]})3. Graph สอง node: remember → respond
node ใน LangGraph ขอ config (มี thread_id, user_id) และ store ได้ — framework ส่งให้เอง
class State(TypedDict):
messages: Annotated[list[dict], operator.add]
# ✏️ TODO 1 (▶ วิดีโอ 1:55): เก็บข้อเท็จจริงลง Store ใต้ namespace ของผู้ใช้ ด้วย key ไม่ซ้ำ และ value {'text': fact}
def remember(state, config, *, store):
namespace = ("memories", config["configurable"]["user_id"])
for fact in extract(state["messages"][-1]["content"]):
___
print(" 📝", fact)
return {}
SYSTEM = """You are a research assistant with long-term memory across sessions.
What you remember about this user:
{memories}
Follow the user's preferences in your memory. If your memory has nothing about something, say you don't know."""
# ✏️ TODO 2 (▶ วิดีโอ 2:19): ค้น Store ใต้ namespace ของผู้ใช้ ด้วยข้อความล่าสุด เอา 4 ชิ้น
def respond(state, config, *, store):
namespace = ("memories", config["configurable"]["user_id"])
hits = ___
memories = "\n".join(f"- {h.value['text']}" for h in hits) or "(nothing)"
answer = chat([{"role": "system", "content": SYSTEM.format(memories=memories)}] + state["messages"][-8:])
return {"messages": [{"role": "assistant", "content": answer}]}class State(TypedDict):
messages: Annotated[list[dict], operator.add]
def remember(state, config, *, store):
namespace = ("memories", config["configurable"]["user_id"])
for fact in extract(state["messages"][-1]["content"]):
store.put(namespace, str(uuid.uuid4()), {"text": fact})
print(" 📝", fact)
return {}
SYSTEM = """You are a research assistant with long-term memory across sessions.
What you remember about this user:
{memories}
Follow the user's preferences in your memory. If your memory has nothing about something, say you don't know."""
def respond(state, config, *, store):
namespace = ("memories", config["configurable"]["user_id"])
hits = store.search(namespace, query=state["messages"][-1]["content"], limit=4)
memories = "\n".join(f"- {h.value['text']}" for h in hits) or "(nothing)"
answer = chat([{"role": "system", "content": SYSTEM.format(memories=memories)}] + state["messages"][-8:])
return {"messages": [{"role": "assistant", "content": answer}]}from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
graph = StateGraph(State)
graph.add_node("remember", remember)
graph.add_node("respond", respond)
graph.add_edge(START, "remember")
graph.add_edge("remember", "respond")
graph.add_edge("respond", END)
# ✏️ TODO 3 (▶ วิดีโอ 2:43): compile โดยใส่ checkpointer (InMemorySaver) และ store
app = ___from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
graph = StateGraph(State)
graph.add_node("remember", remember)
graph.add_node("respond", respond)
graph.add_edge(START, "remember")
graph.add_edge("remember", "respond")
graph.add_edge("respond", END)
app = graph.compile(checkpointer=InMemorySaver(), store=store)def say(text, thread, user="alice"):
config = {"configurable": {"thread_id": thread, "user_id": user}}
out = app.invoke({"messages": [{"role": "user", "content": text}]}, config)
return out["messages"][-1]["content"]4. วันจันทร์ — thread "monday"
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!"]
for text in monday:
print("USER:", text)
print("AGENT:", say(text, "monday")[:120].replace("\n", " "), "\n")USER: Hi! I'm writing a report on transformers for time series.
📝 The user is writing a report on transformers for time series.
AGENT: Hello! It's good to see you working on that report again. Since we are picking up on your project regarding **transform
USER: Please keep your answers short.
📝 The user prefers short answers.
AGENT: Understood. I will keep my responses brief. How can I help with your report?
USER: My report deadline is next Wednesday.
📝 The user has a report deadline next Wednesday.
AGENT: Noted. I'll keep that in mind to help you stay on track. What's next on your agenda?
USER: I already read the PatchTST paper, so don't suggest it again.
📝 The user has already read the PatchTST paper.
AGENT: Understood. I will skip PatchTST and focus on other architectures or concepts. What are we looking at next?
USER: Thanks, that's all for today!
AGENT: You're welcome! Good luck with the writing. See you next time.
print(len(app.get_state({"configurable": {"thread_id": "monday"}}).values["messages"]), "messages in 'monday'")
print(app.get_state({"configurable": {"thread_id": "tuesday"}}).values)10 messages in 'monday'
{}
5. วันอังคาร — thread ใหม่ ความจำเดิม
for q in ["Any papers I should read next for my report?", "When is my report due?", "What's my dog's name?"]:
answer = say(q, "tuesday")
print(f"USER: {q}\nAGENT: {answer[:200]}\n ({len(answer.split())} words)\n")USER: Any papers I should read next for my report?
AGENT: Since you've read **PatchTST**, I recommend these to show the evolution of the field:
1. **Informer** (ProbSparse Attention): A foundational paper for long-sequence forecasting.
2. **Autoformer** (
(75 words)
USER: When is my report due?
AGENT: Your report is due next Wednesday.
(6 words)
USER: What's my dog's name?
AGENT: I don't know.
(3 words)
6. สิ่งที่ framework เพิ่มให้: namespace แยกผู้ใช้ (§17.5 Privacy)
ตำรา: ระบบหลายผู้ใช้ต้อง คุมสิทธิ์ — ความจำของคนหนึ่งต้องไม่รั่วไปถึงอีกคน · และผู้ใช้ต้อง ดูและลบ ความจำของตัวเองได้
print(say("When is my report due?", "bob-1", user="bob"))I don't know when your report is due. I don't have access to your personal calendar, emails, or specific project details unless you have shared them with me in this conversation.
items = store.search(("memories", "alice"), limit=10)
for it in items:
print(it.key[:8], it.value["text"])
# ✏️ TODO 4 (▶ วิดีโอ 4:51): ลบความจำเรื่องกำหนดส่งออกจาก Store ด้วย namespace และ key
deadline = next(it for it in items if "deadline" in it.value["text"])
___
print("tuesday: ", say("When is my report due?", "tuesday"))
print("new thread:", say("When is my report due?", "wednesday"))items = store.search(("memories", "alice"), limit=10)
for it in items:
print(it.key[:8], it.value["text"])
deadline = next(it for it in items if "deadline" in it.value["text"])
store.delete(("memories", "alice"), deadline.key)
print("tuesday: ", say("When is my report due?", "tuesday"))
print("new thread:", say("When is my report due?", "wednesday"))c146e5d6 The user is writing a report on transformers for time series.
ff69f770 The user prefers short answers.
147c4d1e The user has a report deadline next Wednesday.
f384dbd5 The user has already read the PatchTST paper.
tuesday: Your report is due next Wednesday.
new thread: I don't know.
print({k: f"${v:.5f}" for k, v in COST.items()}){'chat': '$0.00048', 'embed': '$0.00000'}
สรุป
| Lab 3 (เขียนเอง) | LangGraph | สิ่งที่เห็น |
|---|---|---|
history |
checkpointer + thread_id |
“monday” 10 ข้อความ · “tuesday” ว่าง |
ชั้นอุ่น + page_in |
Store + store.search |
วันอังคารตอบได้ทั้งสามข้อ |
extract() |
node remember |
4 ข้อเท็จจริง |
| — | namespace ต่อผู้ใช้ | บ็อบ “ไม่รู้” — ความจำของอลิซไม่รั่ว |
| — | store.search(ns) / store.delete |
ดูและลบได้ — แต่ history ใน checkpointer ต้องลบแยก |
แบบฝึกหัด
- ใส่ tool
memory_searchแบบ Lab 3 ให้ noderespondแล้วเพิ่ม nodetoolsกับ conditional edge - ใช้
get_state_historyของ thread “monday” (EP05 Lab 5) — checkpointer เก็บไว้กี่ checkpoint - ลองลบ thread ทั้ง thread ด้วย
app.checkpointer.delete_thread("tuesday")แล้วถามกำหนดส่งอีกครั้ง
ถัดไป — EP12 Recap: ความจำของ agent ในคลิปเดียว