Lab 4 — harness ตัวเดิมด้วย LangChain
Lab walkthrough · EP09 Building a Production Harness
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP09 Building a Production Harness
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
ตำรา §18.9 เทียบ framework กับการเขียนเอง และให้ LangChain ว่า “a rich ecosystem of integrations but … abstractions that can obscure what is actually happening”
แล็บนี้สร้าง research assistant ตัวเดิมจาก Lab 1 ด้วย LangChain create_agent แล้วจับคู่ทีละชิ้น:
| harness ของเรา (Lab 1) | LangChain |
|---|---|
ToolDefinition |
@tool (schema จาก type hint + docstring) |
approval ใน ToolExecutor |
HumanInTheLoopMiddleware + checkpointer |
| retry + backoff | ToolRetryMiddleware |
ContextManager |
ContextEditingMiddleware |
MAX_ITERATIONS |
ModelCallLimitMiddleware |
LoopDetector |
ไม่มีแบบเดียวกัน — เขียนเองเป็น middleware |
log + run_id |
astream(..., stream_mode="updates") + thread_id |
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §18.9–18.10 — CC BY-SA 4.0 tool ในแล็บนี้ใช้คลัง paper จำลอง แต่คำตอบของ model ทุกคำตอบมาจากการรันจริง
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | key เดิมจาก Lab 1 (แล็บนี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์) |
| Packages | langchain, langchain-openai, langgraph, tokenizers — ล็อกเวอร์ชันไว้ เพราะ API ของ LangChain เปลี่ยนบ่อย |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
%pip install -q "langchain==1.4.7" "langchain-openai==1.7.2" "langgraph==1.2.16" python-dotenv "tokenizers==0.23.3"1. Model
ChatOpenAI แทน AsyncOpenAI + client.chat.completions.create(...) — model, provider และ timeout เหมือน Lab 3 ทุกค่า
import asyncio, hashlib, json, os, time, uuid
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"
model = ChatOpenAI(model=MODEL, base_url="https://openrouter.ai/api/v1", api_key=load_key(),
temperature=0, max_retries=5, timeout=60,
extra_body={"reasoning": {"enabled": False},
"provider": {"order": ["makora"], "allow_fallbacks": False}})2. tool ด้วย @tool
ใน Lab 1 เราเขียน ToolDefinition พร้อม JSON schema เอง — @tool สร้าง schema จาก type hint และ docstring ให้ ส่วน requires_approval ย้ายไปอยู่ที่ middleware (ส่วนที่ 3)
LIBRARY = {
"P1": ("Informer (2021)", "ProbSparse self-attention makes long-sequence time-series forecasting faster."),
"P2": ("PatchTST (2023)", "Splits each series into patches of 16 steps; each channel is handled on its own."),
"P3": ("TimesFM (2024)", "A decoder-only foundation model that forecasts new series zero-shot."),
"P4": ("Autoformer (2021)", "Replaces attention with auto-correlation and decomposes trend and season."),
"P5": ("DLinear (2023)", "A single linear layer that beats many transformers on long-term forecasting."),
"P6": ("BERT (2019)", "Pre-trains a bidirectional transformer on text with masked language modelling."),
}
SAVED = {} # the simulated diskfrom langchain.tools import tool
@tool
async def search_papers(query: str, max_results: int = 3) -> str:
"""Search the paper library. Returns ids and titles."""
await asyncio.sleep(0.5)
words = [w.rstrip("s") for w in query.lower().replace("-", " ").split() if len(w) > 3]
hits = [(pid, t) for pid, (t, a) in LIBRARY.items() if any(w in (t + " " + a).lower() for w in words)]
return json.dumps([{"id": pid, "title": t} for pid, t in hits[:max_results]])
@tool
async def read_paper(paper_id: str) -> str:
"""Read one paper's abstract by its id (P1, P2, ...)."""
await asyncio.sleep(1.5)
title, abstract = LIBRARY[paper_id]
return json.dumps({"id": paper_id, "title": title, "abstract": abstract})
@tool
def save_report(filename: str, text: str) -> str:
"""Save a finished report to a file."""
SAVED[filename] = text
return f"saved {len(text)} characters to {filename}"
TOOLS = [search_papers, read_paper, save_report]
print(search_papers.args){'query': {'title': 'Query', 'type': 'string'}, 'max_results': {'default': 3, 'title': 'Max Results', 'type': 'integer'}}
3. Middleware — ชิ้นส่วนของ harness
middleware = โค้ดที่ LangChain เรียกรอบๆ การเรียก model หรือการเรียก tool ทุกครั้ง — แต่ละตัวทำงานหนึ่งอย่าง เหมือน class หนึ่งตัวใน harness ของเรา
# ✏️ TODO 1 (▶ วิดีโอ 2:12): ให้ save_report ต้องอนุมัติ โดยตอบได้แค่ approve หรือ reject
from langchain.agents.middleware import (HumanInTheLoopMiddleware, ToolRetryMiddleware,
ModelCallLimitMiddleware, ContextEditingMiddleware, ClearToolUsesEdit, wrap_tool_call)
approval = HumanInTheLoopMiddleware(interrupt_on=___)
retry = ToolRetryMiddleware(max_retries=2, initial_delay=1.0, backoff_factor=2.0)
limit = ModelCallLimitMiddleware(run_limit=50)
# ✏️ TODO 2 (▶ วิดีโอ 2:56): นับ token ของทุกข้อความด้วย tokenizer ของ Gemma บวกข้อความละ 4
from langchain_core.messages.utils import count_tokens_approximately
from tokenizers import Tokenizer
tok = Tokenizer.from_pretrained(MODEL)
def gemma_tokens(messages) -> int:
return ___
context = ContextEditingMiddleware(token_counter=gemma_tokens,
edits=[ClearToolUsesEdit(trigger=128_000, keep=3)])from langchain.agents.middleware import (HumanInTheLoopMiddleware, ToolRetryMiddleware,
ModelCallLimitMiddleware, ContextEditingMiddleware, ClearToolUsesEdit, wrap_tool_call)
approval = HumanInTheLoopMiddleware(
interrupt_on={"save_report": {"allowed_decisions": ["approve", "reject"]}})
retry = ToolRetryMiddleware(max_retries=2, initial_delay=1.0, backoff_factor=2.0)
limit = ModelCallLimitMiddleware(run_limit=50)
from langchain_core.messages.utils import count_tokens_approximately
from tokenizers import Tokenizer
tok = Tokenizer.from_pretrained(MODEL)
def gemma_tokens(messages) -> int:
return sum(len(tok.encode(str(m.content)).ids) + 4 for m in messages)
context = ContextEditingMiddleware(token_counter=gemma_tokens,
edits=[ClearToolUsesEdit(trigger=128_000, keep=3)])Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
from langchain_core.messages import HumanMessage
for text in ["You are a research assistant for a university course.",
"สวัสดีครับ วันนี้เราจะสร้าง harness ด้วย LangChain",
'{"id": "P2", "title": "PatchTST (2023)"}']:
msg = [HumanMessage(text)]
print(f"approx {count_tokens_approximately(msg):3} gemma {gemma_tokens(msg):3} {text}")approx 18 gemma 14 You are a research assistant for a university course.
approx 17 gemma 15 สวัสดีครับ วันนี้เราจะสร้าง harness ด้วย LangChain
approx 14 gemma 24 {"id": "P2", "title": "PatchTST (2023)"}
# ✏️ TODO 3 (▶ วิดีโอ 3:59): ถ้าลายนิ้วมือ h อยู่ใน 5 ตัวล่าสุดตั้งแต่ 2 ครั้ง ให้คืน ToolMessage แจ้งว่าวน
from langchain_core.messages import ToolMessage
fingerprints = []
@wrap_tool_call
async def loop_detector(request, handler):
call = request.tool_call
h = hashlib.md5(f"{call['name']}:{json.dumps(call['args'], sort_keys=True)}".encode()).hexdigest()
fingerprints.append(h)
if ___:
return ToolMessage(f"Loop detected: {call['name']} was called again with the same arguments.",
tool_call_id=call["id"], name=call["name"], status="error")
return await handler(request)from langchain_core.messages import ToolMessage
fingerprints = []
@wrap_tool_call
async def loop_detector(request, handler):
call = request.tool_call
h = hashlib.md5(f"{call['name']}:{json.dumps(call['args'], sort_keys=True)}".encode()).hexdigest()
fingerprints.append(h)
if fingerprints[-5:].count(h) >= 2:
return ToolMessage(f"Loop detected: {call['name']} was called again with the same arguments.",
tool_call_id=call["id"], name=call["name"], status="error")
return await handler(request)4. ประกอบ agent แล้วรัน (อนุมัติ ✅)
create_agent = ลูป ReAct ของ AgentHarness.run · checkpointer เก็บสถานะของงานไว้ ให้หยุดรอคนอนุมัติแล้วทำต่อได้ · thread_id ระบุงาน เหมือน run_id
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
SYSTEM = ("You are a research assistant for a university course. Use the tools to find and read papers "
"before answering. When you need several papers, request them all in the same turn. "
"Always cite paper ids like [P2].")
TASK = ("Find papers on transformers for time-series forecasting, read the three most relevant ones, "
"and save a short report to report.md.")
agent = create_agent(model, TOOLS, system_prompt=SYSTEM,
middleware=[approval, loop_detector, retry, limit, context],
checkpointer=InMemorySaver())
async def run(inp, config):
async for step in agent.astream(inp, config, stream_mode="updates"):
for node, update in step.items():
if node == "__interrupt__":
for req in update[0].value["action_requests"]:
print(f"🔒 approval needed: {req['name']}(filename={req['args'].get('filename')!r})")
continue
for m in (update or {}).get("messages", []):
if getattr(m, "tool_calls", None) and node == "model":
print("model asks:", ", ".join(f"{c['name']}({c['args'].get('paper_id') or c['args'].get('query') or c['args'].get('filename')})" for c in m.tool_calls))
elif m.type == "tool":
print(f" {m.name} → {str(m.content)[:70]}")
elif node == "model":
print("ANSWER:", m.content)
def usage(config) -> str:
msgs = agent.get_state(config).values["messages"]
u = [m.usage_metadata for m in msgs if getattr(m, "usage_metadata", None)]
return f"{len(u)} model calls · {sum(x['input_tokens'] for x in u):,} in + {sum(x['output_tokens'] for x in u):,} out"config = {"configurable": {"thread_id": str(uuid.uuid4())}}
t0 = time.monotonic()
await run({"messages": [{"role": "user", "content": TASK}]}, config)
print(f"\n⏸ paused · saved so far: {list(SAVED)}")model asks: search_papers(transformers for time-series forecasting)
search_papers → [{"id": "P1", "title": "Informer (2021)"}, {"id": "P2", "title": "Patc
model asks: read_paper(P1), read_paper(P2), read_paper(P3)
read_paper → {"id": "P1", "title": "Informer (2021)", "abstract": "ProbSparse self-
read_paper → {"id": "P3", "title": "TimesFM (2024)", "abstract": "A decoder-only fo
read_paper → {"id": "P2", "title": "PatchTST (2023)", "abstract": "Splits each seri
model asks: save_report(report.md)
🔒 approval needed: save_report(filename='report.md')
⏸ paused · saved so far: []
# ✏️ TODO 4 (▶ วิดีโอ 5:56): สั่งงานที่หยุดอยู่ให้ทำต่อ ด้วยคำตอบ approve
await run(___, config)
print(f"\nsaved: {list(SAVED)} · {usage(config)} · {time.monotonic() - t0:.1f}s")await run(Command(resume={"decisions": [{"type": "approve"}]}), config)
print(f"\nsaved: {list(SAVED)} · {usage(config)} · {time.monotonic() - t0:.1f}s") save_report → saved 1384 characters to report.md
ANSWER: I have completed the research task. I searched for papers on transformers for time-series forecasting, selected the three most relevant ones (Informer, PatchTST, and TimesFM), read their abstracts, and compiled a summary report.
The report has been saved to `report.md`.
### Summary of Findings:
* **Informer [P1]**: Introduced ProbSparse self-attention to handle long-sequence forecasting more efficiently.
* **PatchTST [P2]**: Utilizes a patching mechanism to capture local semantic information and improve channel-independent processing.
* **TimesFM [P3]**: A recent decoder-only foundation model designed for zero-shot forecasting on new time-series data.
saved: ['report.md'] · 4 model calls · 2,102 in + 533 out · 16.5s
5. ไม่อนุมัติ ❌ — model พูดว่าอะไร กับ ระบบเกิดอะไรขึ้นจริง
SAVED.clear(); fingerprints.clear()
config = {"configurable": {"thread_id": str(uuid.uuid4())}}
await run({"messages": [{"role": "user", "content": TASK}]}, config)
await run(Command(resume={"decisions": [{"type": "reject"}]}), config)
print(f"\nsaved: {list(SAVED)} · {usage(config)}")model asks: search_papers(transformers for time-series forecasting)
search_papers → [{"id": "P1", "title": "Informer (2021)"}, {"id": "P2", "title": "Patc
model asks: read_paper(P1), read_paper(P2), read_paper(P3)
read_paper → {"id": "P1", "title": "Informer (2021)", "abstract": "ProbSparse self-
read_paper → {"id": "P2", "title": "PatchTST (2023)", "abstract": "Splits each seri
read_paper → {"id": "P3", "title": "TimesFM (2024)", "abstract": "A decoder-only fo
model asks: save_report(report.md)
🔒 approval needed: save_report(filename='report.md')
save_report → User rejected the tool call for `save_report` with id call-3892cc90-88
ANSWER: I have searched for papers on transformers for time-series forecasting and identified three highly relevant works: **Informer (2021)**, **PatchTST (2023)**, and **TimesFM (2024)**.
I have compiled a summary of these papers and attempted to save it to `report.md`.
### Summary of Findings:
* **Informer (2021) [P1]:** Focuses on efficiency for long-sequence forecasting by introducing the **ProbSparse self-attention** mechanism to reduce computational complexity.
* **PatchTST (2023) [P2]:** Utilizes a **patching mechanism** where time series are split into sub-segments (patches). This allows the model to capture local semantic patterns and improves performance over point-wise transformers.
* **TimesFM (2024) [P3]:** A modern **foundation model** approach. It uses a decoder-only architecture to enable **zero-shot forecasting**, allowing it to predict new time series without specific training on that data.
saved: [] · 4 model calls · 2,095 in + 546 out
6. ลำดับของ middleware
ตำรา: “Build custom when … the framework’s abstractions leak in ways that cause bugs” — ลองดูของจริง ขอให้อ่าน paper P9 ซึ่งไม่มีในคลัง → read_paper โยน KeyError → ToolRetryMiddleware ลองใหม่
async def ask(middleware, question):
global agent
agent = create_agent(model, TOOLS, system_prompt=SYSTEM, middleware=middleware,
checkpointer=InMemorySaver())
fingerprints.clear()
t0 = time.monotonic()
await run({"messages": [{"role": "user", "content": question}]},
{"configurable": {"thread_id": str(uuid.uuid4())}})
print(f"({time.monotonic() - t0:.1f}s)")
await ask([approval, retry, loop_detector, limit, context], "Read paper P9 and tell me what it is about.")model asks: read_paper(P9)
read_paper → Loop detected: read_paper was called again with the same arguments.
ANSWER: I am sorry, but I encountered an error when trying to read paper P9. It appears there was a technical issue with the request. Could you please try asking me to read it again?
(3.7s)
await ask([approval, loop_detector, retry, limit, context], "Read paper P9 and tell me what it is about.")model asks: read_paper(P9)
read_paper → Tool 'read_paper' failed after 3 attempts with KeyError: 'P9'. Please
ANSWER: I am sorry, but I cannot access paper **P9** because it does not exist in the current library. Please check the paper ID and try again, or provide the title of the paper you are looking for so I can search for it.
(10.2s)
สรุป — ชิ้นต่อชิ้น
| harness ของเรา | LangChain | ที่เราเห็นในแล็บ |
|---|---|---|
ToolDefinition |
@tool |
schema สร้างจาก type hint ให้ |
| approval | HumanInTheLoopMiddleware |
หยุดทั้งงาน เก็บสถานะ แล้วทำต่อด้วย Command(resume=...) |
| retry + backoff | ToolRetryMiddleware |
ลองสามครั้งเหมือนกัน — แต่ลำดับ middleware เปลี่ยนผล |
ContextManager |
ContextEditingMiddleware |
ล้างผลของ tool เก่าแทนการทิ้งข้อความ · นับแบบประมาณ ถ้าไม่ส่ง tokenizer เอง |
LoopDetector |
— | เขียนเองเป็น @wrap_tool_call |
MAX_ITERATIONS |
ModelCallLimitMiddleware |
|
log + run_id |
astream + thread_id |
ต้องรู้ว่าแต่ละ node ส่งอะไรมา |
| การตัด output 2,000 token | — | ไม่มีให้ — แบบฝึกหัดข้อ 1 |
ทั้งสองแบบ: หลังถูกปฏิเสธ model บางครั้งบอกว่าบันทึกแล้ว ทั้งที่ไม่ได้บันทึก — เชื่อสถานะของระบบ (SAVED) ไม่ใช่คำพูดของ model
แบบฝึกหัด
- เขียน middleware
@wrap_tool_callที่ตัดผลของ tool เกิน 2,000 token ด้วยtokแบบ_truncateใน Lab 1 - ให้
ToolRetryMiddlewareไม่ลองใหม่เมื่อเจอKeyError(ดู argumentretry_on) — ใช้เวลาเหลือเท่าไร - ใช้
recordกับcompareของ Lab 3 กับ agent ตัวนี้ — trace ของ LangChain เทียบกับของเราได้ไหม ต้องดึงข้อมูลจากตรงไหน