Lab 4 — สรุปของเก่าด้วย LangChain
Lab walkthrough · EP07 Context Window Management
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP07 Context Window Management
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Lab 2 เราเขียน summarize_old เอง: เกินงบเมื่อไร → สรุปข้อความเก่า เก็บข้อความล่าสุดไว้ครบ (สมการ 18.4) lab นี้ใช้ SummarizationMiddleware ของ LangChain ทำเรื่องเดียวกัน — middleware ที่เราเจอใน EP06 Lab 4
| ที่เราเขียนเองใน Lab 2 | ใน SummarizationMiddleware |
|---|---|
BUDGET + เช็กว่าเกินไหม |
trigger=("tokens", 600) |
keep_last=6 |
keep=("messages", 6) |
SUMMARY_PROMPT |
summary_prompt= |
message_tokens (Lab 1) |
token_counter= |
list HISTORY |
state ของ agent ใน checkpointer (thread) |
สิ่งที่ framework เพิ่มให้: ตรวจงบเอง ก่อนเรียก model ทุกครั้ง ใน agent loop — เราไม่ต้องเรียกสรุปเอง
บทสนทนาเป็นชุดเดียวกับ Lab 2 (ข้อมูลจำลอง) ส่วนคำตอบและบทสรุปของ model มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §18.2.3 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์) |
| Packages | langchain, langgraph, langchain-openai, langchain-core (ล็อกเวอร์ชันชุดเดียวกับ EP06 Lab 4), tokenizers, python-dotenv |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1
%pip install -q "langchain==1.4.7" "langgraph==1.2.16" "langchain-openai==1.7.2" "langchain-core==1.7.0" "tokenizers==0.23.3" python-dotenv1. Model, ตัวนับ token และบทสนทนา (จาก Lab 1–2)
ChatOpenAI ชี้ไป OpenRouter (Gemma 4 26B ล็อกที่ DeepInfra) แบบเดียวกับ EP06 Lab 4 USER_TURNS คือข้อความของผู้ใช้จาก Lab 2 ทั้ง 15 ข้อความ — คราวนี้ agent ตอบเองทุกข้อความ
import os, re
os.environ["HF_HUB_VERBOSITY"] = "error"
from tokenizers import Tokenizer
from langchain_openai import ChatOpenAI
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"
llm = ChatOpenAI(model=MODEL, base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_tokens=400,
extra_body={"reasoning": {"enabled": False},
"provider": {"order": ["deepinfra/fp8"], "allow_fallbacks": False}})
tok = Tokenizer.from_pretrained(MODEL)
PAPERS = {"P01": 2021, "P02": 2021, "P03": 2022, "P04": 2023, "P05": 2023,
"P06": 2024, "P07": 2024, "P08": 2024, "P09": 2019, "P10": 2024}
USER_TURNS = [
"Task for this whole chat: I'm writing a literature review on transformers for time series. I'll paste paper notes. Always answer in Thai.",
"Correction to the task: my review only covers papers published in 2023 or later. Leave older ones out.",
"Paper note P04: Are Transformers Effective for Time Series Forecasting? (2023). A one-layer linear model beats several transformers.",
"Paper note P05: PatchTST (2023). Cuts each series into patches of 16 points and treats channels independently.",
"Paper note P06: iTransformer (2024). Inverts the axes: each variable becomes a token, attention runs across variables.",
"Thanks!",
"Paper note P01: Informer (2021). ProbSparse self-attention cuts the cost of long inputs; tested on electricity and weather data.",
"Paper note P07: TimesFM (2024). A decoder-only foundation model pretrained on 100 billion time points; good zero-shot forecasts.",
"Paper note P09: Temporal Fusion Transformer (2019). LSTM encoders with attention and variable selection for interpretable forecasts.",
"Nice, coffee break, back in five minutes.",
"Paper note P08: Chronos (2024). Scales and quantizes values into tokens and trains a T5 language model on them.",
"Paper note P02: Autoformer (2021). Replaces attention with auto-correlation and splits each series into trend and seasonal parts.",
"Paper note P10: Moirai (2024). A universal forecasting transformer trained on 27 billion observations across nine domains.",
"Haha, my cat just walked on the keyboard.",
"Paper note P03: FEDformer (2022). Works in the frequency domain with Fourier and wavelet blocks; linear cost in sequence length.",
]
ASK = "List every paper that belongs in my review, one line each: id, title, year."ROLE = {"human": "user", "ai": "model", "system": "system", "tool": "tool"}
def gemma_counter(messages):
return sum(len(tok.encode(f"<|turn>{ROLE[m.type]}\n{str(m.content).strip()}<turn|>\n", add_special_tokens=False).ids)
for m in messages)2. Agent + SummarizationMiddleware
trigger=("tokens", 600)— สรุปเมื่อ history เกิน 600 tokenkeep=("messages", 6)— เก็บ 6 ข้อความล่าสุดไว้ครบcheckpointer=InMemorySaver()— จำบทสนทนาของแต่ละthread_idข้ามการเรียกแต่ละครั้ง (EP05 Lab 5)
รอบแรกใช้ summary prompt ค่าเริ่มต้น ของ LangChain ดูก่อน
from langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware
from langgraph.checkpoint.memory import InMemorySaver
def make_agent(**prompt):
summarize = SummarizationMiddleware(model=llm, trigger=("tokens", 600), keep=("messages", 6),
token_counter=gemma_counter, **prompt)
return create_agent(llm, tools=[], middleware=[summarize], checkpointer=InMemorySaver(),
system_prompt="You are the Cogito Learn research assistant. When the user pastes a paper note, reply with one short sentence.")
# ✏️ TODO 1 (▶ วิดีโอ 2:35): ส่งข้อความของผู้ใช้หนึ่งข้อความเข้า thread เดียวกัน แล้วเอา messages ของ state ออกมา
def chat_all(agent, thread):
cfg = {"configurable": {"thread_id": thread}}
last, summaries = None, 0
for text in USER_TURNS:
msgs = ___
summary = next((m.content for m in msgs if m.additional_kwargs.get("lc_source") == "summarization"), None)
new = summary is not None and summary != last
if new:
summaries, last = summaries + 1, summary
print(f"{text[:32]:32} → {len(msgs):2} messages, {gemma_counter(msgs):3} tokens {'📝 summarized' if new else ''}")
answer = agent.invoke({"messages": [{"role": "user", "content": ASK}]}, cfg)["messages"][-1].content
ids = sorted(set(re.findall(r"^\W*(P\d\d)", answer, re.M)))
print(f"\nsummaries written: {summaries} · last summary: {len(tok.encode(last, add_special_tokens=False).ids)} tokens")
print(answer, "\n→ older than 2023:", [p for p in ids if PAPERS[p] < 2023], "· right papers:", f"{sum(PAPERS[p] >= 2023 for p in ids)}/6")
return lastfrom langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware
from langgraph.checkpoint.memory import InMemorySaver
def make_agent(**prompt):
summarize = SummarizationMiddleware(model=llm, trigger=("tokens", 600), keep=("messages", 6),
token_counter=gemma_counter, **prompt)
return create_agent(llm, tools=[], middleware=[summarize], checkpointer=InMemorySaver(),
system_prompt="You are the Cogito Learn research assistant. When the user pastes a paper note, reply with one short sentence.")
def chat_all(agent, thread):
cfg = {"configurable": {"thread_id": thread}}
last, summaries = None, 0
for text in USER_TURNS:
msgs = agent.invoke({"messages": [{"role": "user", "content": text}]}, cfg)["messages"]
summary = next((m.content for m in msgs if m.additional_kwargs.get("lc_source") == "summarization"), None)
new = summary is not None and summary != last
if new:
summaries, last = summaries + 1, summary
print(f"{text[:32]:32} → {len(msgs):2} messages, {gemma_counter(msgs):3} tokens {'📝 summarized' if new else ''}")
answer = agent.invoke({"messages": [{"role": "user", "content": ASK}]}, cfg)["messages"][-1].content
ids = sorted(set(re.findall(r"^\W*(P\d\d)", answer, re.M)))
print(f"\nsummaries written: {summaries} · last summary: {len(tok.encode(last, add_special_tokens=False).ids)} tokens")
print(answer, "\n→ older than 2023:", [p for p in ids if PAPERS[p] < 2023], "· right papers:", f"{sum(PAPERS[p] >= 2023 for p in ids)}/6")
return lastdefault_summary = chat_all(make_agent(), "default-prompt")Task for this whole chat: I'm wr → 2 messages, 52 tokens
Correction to the task: my revie → 4 messages, 114 tokens
Paper note P04: Are Transformers → 6 messages, 181 tokens
Paper note P05: PatchTST (2023). → 8 messages, 249 tokens
Paper note P06: iTransformer (20 → 10 messages, 320 tokens
Thanks! → 12 messages, 347 tokens
Paper note P01: Informer (2021). → 14 messages, 419 tokens
Paper note P07: TimesFM (2024). → 16 messages, 498 tokens
Paper note P09: Temporal Fusion → 18 messages, 564 tokens
Nice, coffee break, back in five → 20 messages, 601 tokens
Paper note P08: Chronos (2024). → 8 messages, 611 tokens 📝 summarized
Paper note P02: Autoformer (2021 → 8 messages, 621 tokens 📝 summarized
Paper note P10: Moirai (2024). A → 8 messages, 652 tokens 📝 summarized
Haha, my cat just walked on the → 8 messages, 638 tokens 📝 summarized
Paper note P03: FEDformer (2022) → 8 messages, 644 tokens 📝 summarized
summaries written: 5 · last summary: 411 tokens
P04: Are Transformers Effective for Time Series Forecasting?, 2023
P05: PatchTST, 2023
P06: iTransformer, 2024
P07: TimesFM, 2024
P08: Chronos, 2024
P10: Moirai, 2024
→ older than 2023: [] · right papers: 6/6
print(default_summary[-500:]) - P07 (2024): "TimesFM" - เป็น decoder-only foundation model ที่ผ่านการ pretrain ด้วยข้อมูล 100 billion time points มีจุดเด่นด้าน zero-shot forecasting
- P08 (2024): "Chronos" - ประยุกต์ใช้ T5 language model โดยการแปลงค่าอนุกรมเวลาให้เป็น tokens (Scale และ Quantize)
- การคัดออก:
- P09 (Temporal Fusion Transformer, 2019) ถูกคัดออกเนื่องจากไม่ตรงตามเงื่อนไขปีที่ตีพิมพ์
- P02 (Autoformer, 2021) ถูกคัดออกเนื่องจากไม่ตรงตามเงื่อนไขปีที่ตีพิมพ์
## ARTIFACTS
None
## NEXT STEPS
- รอ
3. ใช้ prompt ของเราจาก Lab 2
summary_prompt ต้องมี {messages} — middleware จะแทนที่ด้วยข้อความเก่าที่ต้องสรุป
# ✏️ TODO 2 (▶ วิดีโอ 4:21): ส่ง prompt ของเราเข้า make_agent ผ่าน summary_prompt
SUMMARY_PROMPT = ("Summarize this conversation for the assistant's own memory, in English, in at most 120 words. "
"Keep every instruction and correction the user gave, and every paper id with its title and year. "
"Copy numbers exactly; add nothing.\n\n{messages}")
our_summary = chat_all(make_agent(___), "our-prompt")SUMMARY_PROMPT = ("Summarize this conversation for the assistant's own memory, in English, in at most 120 words. "
"Keep every instruction and correction the user gave, and every paper id with its title and year. "
"Copy numbers exactly; add nothing.\n\n{messages}")
our_summary = chat_all(make_agent(summary_prompt=SUMMARY_PROMPT), "our-prompt")Task for this whole chat: I'm wr → 2 messages, 63 tokens
Correction to the task: my revie → 4 messages, 124 tokens
Paper note P04: Are Transformers → 6 messages, 197 tokens
Paper note P05: PatchTST (2023). → 8 messages, 269 tokens
Paper note P06: iTransformer (20 → 10 messages, 341 tokens
Thanks! → 12 messages, 358 tokens
Paper note P01: Informer (2021). → 14 messages, 419 tokens
Paper note P07: TimesFM (2024). → 16 messages, 493 tokens
Paper note P09: Temporal Fusion → 18 messages, 548 tokens
Nice, coffee break, back in five → 20 messages, 584 tokens
Paper note P08: Chronos (2024). → 8 messages, 320 tokens 📝 summarized
Paper note P02: Autoformer (2021 → 10 messages, 379 tokens
Paper note P10: Moirai (2024). A → 12 messages, 455 tokens
Haha, my cat just walked on the → 14 messages, 494 tokens
Paper note P03: FEDformer (2022) → 16 messages, 553 tokens
summaries written: 1 · last summary: 120 tokens
P04: Are Transformers Effective for Time Series Forecasting? (2023)
P05: PatchTST (2023)
P06: iTransformer (2024)
P07: TimesFM (2024)
P08: Chronos (2024)
P10: Moirai (2024)
→ older than 2023: [] · right papers: 6/6
print(our_summary)Here is a summary of the conversation to date:
Task: Writing a literature review on transformers for time series. Always answer in Thai. Only include papers published in 2023 or later; leave older ones out.
Papers:
P04: Are Transformers Effective for Time Series Forecasting? (2023).
P05: PatchTST (2023).
P06: iTransformer (2024).
P01: Informer (2021).
P07: TimesFM (2024).
สรุป
| prompt ค่าเริ่มต้น | prompt ของเรา (Lab 2) | |
|---|---|---|
| บทสรุป | เป็นหัวข้อ ยาวจนชนเพดาน 400 token (ถูกตัดกลางประโยค) | ไม่ถึง 200 token |
| สรุปกี่ครั้ง ใน 15 turn | แทบทุก turn หลังเกินงบครั้งแรก | 1–2 ครั้ง |
| คำตอบสุดท้าย | 6/6 เหมือนกัน — แต่เรียก model เพิ่มเพื่อสรุปหลายครั้ง | 6/6 ไม่มี paper เก่า |
- framework ทำงานซ้ำๆ ให้: ตรวจงบก่อนเรียก model ทุกครั้ง แบ่งข้อความเก่า/ใหม่ แทนที่ด้วยบทสรุปใน state
- แต่ ค่าเริ่มต้นไม่ได้ออกแบบมาสำหรับงานของเรา — ต้องรู้ว่าข้างในทำอะไร (สมการ 18.4) ถึงจะตั้งค่าได้ถูก
- อ่านต่อ:
summarizer=ใช้ model อีกตัว (เล็กและถูกกว่า) เขียนบทสรุป ตามที่ตำราแนะนำ
แบบฝึกหัด
- ลบ
token_counter=gemma_counterออก (ใช้ตัวนับแบบประมาณ) แล้วรันอีกครั้ง — สรุปครั้งแรกที่ turn ไหน ต่างจากเดิมไหม - ตั้ง
keep=("tokens", 250)แทนจำนวนข้อความ — เก็บกี่ข้อความ
ถัดไป — Recap: สรุป EP07 ทั้งตอนในคลิปเดียว