Lab 3 — Tracing ด้วย OpenTelemetry: metrics · logs · หมวดความพัง · replay
Lab walkthrough · EP18 Testing and Observability: Test Suites, Traces and Replay
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP18 Testing and Observability: Test Suites, Traces and Replay
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Lab 1–2 ทดสอบ agent ก่อนปล่อย Lab นี้ดูสิ่งที่ agent ทำ ตอนทำงานจริง ตามสามเสาของ observability ในตำรา (§25.6)
สิ่งที่จะได้ทำ
- ใส่ span ของ OpenTelemetry ให้ agent เอง ตาม Listing 25.18:
agent.run·llm.call·tool.<ชื่อ> - ดู trace ของหนึ่งรอบเป็นแผนภาพเวลา
- จำลอง “production”: 12 รอบ สี่งาน และ search API ล่มบางครั้ง
- metrics จาก span: อัตราสำเร็จ · latency p50/p95 · ค่าใช้จ่าย · อัตรา error ของแต่ละ tool
- logs แบบมีโครงสร้าง ที่พาเรากลับไปหา trace ได้
- จัดหมวดความพังหกแบบของ Table 25.1 จาก trace
- replay ขั้นที่พังด้วย prompt ใหม่ (Listing 25.19) แล้วตรวจว่าแก้ได้จริงไหม
ข้อมูลค้นหาและการล่มของ search API เป็นของจำลองเพื่อการสอน ส่วน output ของ model มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §25.6, Listing 25.18, Table 25.1, Listing 25.19 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ราวหนึ่งเซ็นต์ดอลลาร์) |
| Packages | opentelemetry-sdk, openai, python-dotenv (ติดตั้งใน cell ถัดไป) |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env
%pip install -q "opentelemetry-sdk==1.45.2" "openai>=1.50" python-dotenvimport json, os, random, re, statistics, time
from collections import Counter
from dataclasses import dataclass
from openai import OpenAI
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import Status, StatusCodedef 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"]
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5, timeout=60)
COST = {"chat": 0.0}Model: google/gemma-4-26b-a4b-it ล็อก provider เป็น Makora (tool calling + structured output) — เหตุผลที่เลือก model และราคาอยู่ใน Lab 1
MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False},
"provider": {"order": ["makora"], "allow_fallbacks": False}}
def chat(messages, tools=None, **kw):
if tools:
kw["tools"] = tools
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, messages=messages, **kw)
COST["chat"] += r.usage.cost
return rResearch agent จาก Lab 1–2
tool สามตัวบนข้อมูลค้นหาจำลอง · run_tool · system prompt · ส่วนประกอบของ ResearchAgentV2 (circuit breaker) — เหมือน Lab 2 ส่วนที่ต่างคือ loop ของ agent ซึ่งเราจะเขียนใหม่ในข้อ 1 โดยใส่ span เข้าไป
PAPERS = {
"https://arxiv.org/abs/1312.5602": ("Playing Atari with Deep Reinforcement Learning (2013)",
"DeepMind trains a convolutional network with Q-learning to play seven Atari 2600 games from raw pixels; it beats earlier methods on six of them."),
"https://en.wikipedia.org/wiki/Temporal_difference_learning": ("Temporal difference learning",
"TD learning, introduced by Richard Sutton in 1988, updates value estimates from other learned estimates. TD-Gammon (1992) used it to play backgammon at expert level."),
"https://arxiv.org/abs/1707.06347": ("Proximal Policy Optimization Algorithms (2017)",
"PPO is a policy-gradient method from OpenAI that clips each update so the new policy stays close to the old one; it became a default RL algorithm."),
"https://arxiv.org/abs/2012.07436": ("Informer: Efficient Transformer for Long Sequence Time-Series Forecasting (2020)",
"Informer uses ProbSparse self-attention to cut the cost of attention on long sequences, and forecasts long horizons in one forward pass."),
"https://arxiv.org/abs/2211.14730": ("A Time Series is Worth 64 Words: PatchTST (2022)",
"PatchTST splits each series into patches used as tokens and models each channel independently; it beats earlier transformer forecasters."),
}
class RateLimitError(Exception):
pass
def search_api(query, num_results=5):
words = set(query.lower().split())
hits = [{"title": title, "url": url} for url, (title, body) in PAPERS.items()
if words & set((title + " " + body).lower().replace(",", " ").replace(".", " ").split())]
return {"results": hits[:num_results]}
def search_web(query):
if not query.strip():
raise ValueError("Query cannot be empty")
for attempt in range(2):
try:
data = search_api(query=query, num_results=5)
break
except RateLimitError:
if attempt == 1:
return "Error: rate limited, try again later"
time.sleep(0.5)
except ConnectionError as e:
return f"Error: search failed ({e})"
if not data["results"]:
return "No results."
return "\n".join(f"- {r['title']} — {r['url']}" for r in data["results"])
def read_document(url):
if url not in PAPERS:
return f"Error: no document at {url}"
title, body = PAPERS[url]
return f"{title}\n{body}"
REPORTS = {}
def write_report(title, content):
REPORTS[title] = content
return "Report saved"
TOOLS = {"search_web": search_web, "read_document": read_document, "write_report": write_report}def parse_args(call):
try:
return json.loads(call.function.arguments or "{}")
except json.JSONDecodeError:
return None
def run_tool(tools, call):
name = call.function.name
if name not in tools:
return f"Error: unknown tool {name}"
args = parse_args(call)
if args is None:
return "Error: arguments are not valid JSON"
try:
return str(tools[name](**args))
except Exception as e:
return f"Error: {type(e).__name__}: {e}"
def schema(name, desc, **props):
return {"type": "function", "function": {"name": name, "description": desc,
"parameters": {"type": "object", "required": list(props),
"properties": {k: {"type": "string", "description": v} for k, v in props.items()}}}}
TOOL_SCHEMAS = [
schema("search_web", "Search the web. Returns titles and URLs.", query="search terms"),
schema("read_document", "Read the document at a URL.", url="a URL from the search results"),
schema("write_report", "Save the final research report.", title="report title", content="the report text"),
]
SYSTEM = ("You are a research assistant. Search the web once or twice, read one or two of the documents you found, "
"then save a short report with write_report, citing the URLs you read. "
"After the report is saved, reply with one sentence saying what you found.")
@dataclass
class Result:
status: str
final_answer: str
tool_call_count: int
tokens: int
cost: float
class ResearchAgentV2:
def __init__(self, tools=TOOLS, max_steps=8, system=SYSTEM):
self.tools, self.max_steps, self.system = tools, max_steps, system
def schemas(self): # circuit breaker: tools that failed twice are no longer offered
return [s for s in TOOL_SCHEMAS if s["function"]["name"] not in self.down]
def observe(self, name, out):
if out.startswith("Error"):
self.failures[name] = self.failures.get(name, 0) + 1
if self.failures[name] >= 2:
self.down.add(name)
out += f"\n{name} is down for this task. Continue with what you already have."
return out1. ใส่ span ให้ agent (Listing 25.18)
trace = บันทึกของหนึ่งรอบ ประกอบด้วย span ซ้อนกัน แต่ละ span มีชื่อ เวลาเริ่ม เวลาจบ และ attribute
agent.run ← ทั้งรอบ: งาน, model, สถานะ, token, ค่าใช้จ่าย
├── llm.call ← ทุกครั้งที่เรียก model: messages ที่ส่งไป, token
├── tool.search_web ← ทุกครั้งที่เรียก tool: argument, ผล, สำเร็จไหม
├── llm.call
└── tool.write_report
| ตำรา | แล็บนี้ | |
|---|---|---|
| ส่ง span ไปที่ | collector ที่ localhost:4317 (OTLP) |
InMemorySpanExporter — เก็บไว้ใน notebook |
| ใช้ดู | Jaeger, LangSmith, Phoenix… | อ่านเองด้วย Python (Lab 4 ส่งเข้า Phoenix) |
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("agent.tracer")# ✏️ TODO 1 (▶ วิดีโอ 2:43): ใส่สถานะของรอบ (result.status) เป็น attribute agent.status
class InstrumentedAgent(ResearchAgentV2):
def run(self, task):
self.failures, self.down = {}, set()
with tracer.start_as_current_span("agent.run") as span:
span.set_attribute("agent.task", task)
span.set_attribute("agent.model", MODEL)
result = self.loop(task)
___
span.set_attribute("agent.tool_calls", result.tool_call_count)
span.set_attribute("agent.tokens_used", result.tokens)
span.set_attribute("agent.cost_usd", result.cost)
span.set_attribute("agent.final_answer", result.final_answer)
return result
def loop(self, task):
messages = [{"role": "system", "content": self.system}, {"role": "user", "content": task}]
calls, tokens, start = 0, 0, COST["chat"]
for _ in range(self.max_steps):
with tracer.start_as_current_span("llm.call") as span:
span.set_attribute("llm.model", MODEL)
span.set_attribute("llm.messages", json.dumps(messages))
r = chat(messages, self.schemas())
span.set_attribute("llm.prompt_tokens", r.usage.prompt_tokens)
span.set_attribute("llm.completion_tokens", r.usage.completion_tokens)
tokens += r.usage.total_tokens
msg = r.choices[0].message
if not msg.tool_calls:
return Result("done", msg.content or "", calls, tokens, COST["chat"] - start)
messages.append({"role": "assistant", "content": msg.content or "",
"tool_calls": [tc.model_dump() for tc in msg.tool_calls]})
# ✏️ TODO 2 (▶ วิดีโอ 3:22): ถ้า tool พัง ตั้งสถานะ span เป็น ERROR พร้อมข้อความ error
for call in msg.tool_calls:
name = call.function.name
with tracer.start_as_current_span(f"tool.{name}") as span:
span.set_attribute("tool.name", name)
span.set_attribute("tool.args", call.function.arguments or "{}")
out = run_tool(self.tools, call)
ok = not out.startswith("Error")
span.set_attribute("tool.success", ok)
span.set_attribute("tool.output", out[:500])
if not ok:
___
calls += 1
out = self.observe(name, out)
messages.append({"role": "tool", "tool_call_id": call.id, "content": out})
return Result("max_steps", "", calls, tokens, COST["chat"] - start)class InstrumentedAgent(ResearchAgentV2):
def run(self, task):
self.failures, self.down = {}, set()
with tracer.start_as_current_span("agent.run") as span:
span.set_attribute("agent.task", task)
span.set_attribute("agent.model", MODEL)
result = self.loop(task)
span.set_attribute("agent.status", result.status)
span.set_attribute("agent.tool_calls", result.tool_call_count)
span.set_attribute("agent.tokens_used", result.tokens)
span.set_attribute("agent.cost_usd", result.cost)
span.set_attribute("agent.final_answer", result.final_answer)
return result
def loop(self, task):
messages = [{"role": "system", "content": self.system}, {"role": "user", "content": task}]
calls, tokens, start = 0, 0, COST["chat"]
for _ in range(self.max_steps):
with tracer.start_as_current_span("llm.call") as span:
span.set_attribute("llm.model", MODEL)
span.set_attribute("llm.messages", json.dumps(messages))
r = chat(messages, self.schemas())
span.set_attribute("llm.prompt_tokens", r.usage.prompt_tokens)
span.set_attribute("llm.completion_tokens", r.usage.completion_tokens)
tokens += r.usage.total_tokens
msg = r.choices[0].message
if not msg.tool_calls:
return Result("done", msg.content or "", calls, tokens, COST["chat"] - start)
messages.append({"role": "assistant", "content": msg.content or "",
"tool_calls": [tc.model_dump() for tc in msg.tool_calls]})
for call in msg.tool_calls:
name = call.function.name
with tracer.start_as_current_span(f"tool.{name}") as span:
span.set_attribute("tool.name", name)
span.set_attribute("tool.args", call.function.arguments or "{}")
out = run_tool(self.tools, call)
ok = not out.startswith("Error")
span.set_attribute("tool.success", ok)
span.set_attribute("tool.output", out[:500])
if not ok:
span.set_status(Status(StatusCode.ERROR, out))
calls += 1
out = self.observe(name, out)
messages.append({"role": "tool", "tool_call_id": call.id, "content": out})
return Result("max_steps", "", calls, tokens, COST["chat"] - start)2. trace ของหนึ่งรอบ
เครื่องมืออ่าน trace (เขียนไว้ให้แล้ว):
traces_of(spans)— จัดกลุ่ม span ตามtrace_idได้หนึ่งรายการต่อหนึ่งรอบshow_trace(t)— แผนภาพเวลา: เริ่มที่วินาทีไหน · ใช้กี่วินาที · ซ้อนอยู่ใต้ span ไหน · ✗ = พัง
def traces_of(spans):
by_id = {}
for s in spans:
by_id.setdefault(s.context.trace_id, []).append(s)
return [sorted(t, key=lambda s: s.start_time) for t in by_id.values()]
def root(t): return t[0]
def llm_spans(t): return [s for s in t if s.name == "llm.call"]
def tool_spans(t): return [s for s in t if s.name.startswith("tool.")]
def seconds(s): return (s.end_time - s.start_time) / 1e9
def args_of(s):
try:
return json.loads(s.attributes["tool.args"])
except json.JSONDecodeError:
return {}
def show_trace(t):
t0, depth = root(t).start_time, {}
for s in t:
d = depth[s.parent.span_id] + 1 if s.parent and s.parent.span_id in depth else 0
depth[s.context.span_id] = d
a = s.attributes
if s.name == "agent.run":
info = f"{a['agent.task']} [{a['agent.status']}]"
elif s.name == "llm.call":
info = f"prompt {a['llm.prompt_tokens']} tokens"
else:
info = a["tool.args"][:60] + ("" if a["tool.success"] else " ✗ " + a["tool.output"][:45])
print(f"{(s.start_time - t0) / 1e9:5.1f}s {seconds(s):5.1f}s {' ' * d}{s.name:<19} {info}")GOLDEN_TASK = "Research transformers for time-series forecasting"
exporter.clear()
result = InstrumentedAgent().run(GOLDEN_TASK)
t = traces_of(exporter.get_finished_spans())[0]
show_trace(t) 0.0s 5.1s agent.run Research transformers for time-series forecasting [done]
0.0s 1.4s llm.call prompt 258 tokens
1.4s 0.0s tool.search_web {"query":"transformers for time-series forecasting review su
1.4s 0.5s llm.call prompt 334 tokens
1.9s 0.0s tool.search_web {"query":"transformer architectures for time series forecast
1.9s 0.5s llm.call prompt 451 tokens
2.4s 0.0s tool.read_document {"url":"https://arxiv.org/abs/2211.14730"}
2.4s 2.1s llm.call prompt 538 tokens
4.5s 0.0s tool.write_report {"content":"# Research Report: Transformers for Time-Series
4.5s 0.6s llm.call prompt 1234 tokens
for key, value in root(t).attributes.items():
print(f"{key:<18} {str(value)[:90]}")agent.task Research transformers for time-series forecasting
agent.model google/gemma-4-26b-a4b-it
agent.status done
agent.tool_calls 4
agent.tokens_used 3606
agent.cost_usd 0.00040919200000000006
agent.final_answer I have researched the evolution of transformer architectures for time-series forecasting,
3. จำลอง production
- สี่งาน วนกันจนครบ 12 รอบ
- search API ล่ม 30% ของครั้งที่เรียก (จำลองด้วยการสุ่ม) →
search_webคืนError: search failed - ทุกรอบเขียน span ลง exporter ตัวเดิม — เหมือนระบบจริงที่บันทึก trace ของทุกคำขอ
real_search_api = search_api
OUTAGE = 0.3
dice = random.Random(7)
def search_api(query, num_results=5):
if dice.random() < OUTAGE:
raise ConnectionError("search API down")
return real_search_api(query, num_results)
TASKS = [GOLDEN_TASK,
"Research the history of reinforcement learning",
"What year was PPO published?",
"Compare Informer and PatchTST for long forecasting horizons"]
exporter.clear()
for i in range(12):
InstrumentedAgent().run(TASKS[i % len(TASKS)])
traces = traces_of(exporter.get_finished_spans())
for i, t in enumerate(traces):
steps = " → ".join(s.name[5:] + ("✗" if not s.attributes["tool.success"] else "") for s in tool_spans(t))
print(f"{i:>2} {root(t).attributes['agent.task'][:34]:<35} {steps}")
print(len(exporter.get_finished_spans()), "spans") 0 Research transformers for time-ser search_web → search_web✗ → search_web → read_document → write_report
1 Research the history of reinforcem search_web✗ → search_web → search_web → read_document → write_report
2 What year was PPO published? search_web✗ → search_web → read_document → write_report
3 Compare Informer and PatchTST for search_web✗
4 Research transformers for time-ser search_web → search_web✗ → search_web✗ → read_document → write_report
5 Research the history of reinforcem search_web → search_web → read_document → write_report
6 What year was PPO published? search_web✗ → search_web✗
7 Compare Informer and PatchTST for search_web → read_document → read_document → write_report
8 Research transformers for time-ser search_web → search_web → read_document → read_document → write_report
9 Research the history of reinforcem search_web → search_web → read_document → write_report
10 What year was PPO published? search_web✗
11 Compare Informer and PatchTST for search_web → read_document → read_document → write_report
112 spans
4. Metrics จาก span
| metric | คำนวณจาก |
|---|---|
| อัตราสำเร็จ | รอบที่มี tool.write_report สำเร็จ ÷ ทุกรอบ |
| latency p50 / p95 | ความยาวของ span agent.run — p95 = 95% ของรอบเร็วกว่านี้ |
| ค่าใช้จ่าย | agent.cost_usd |
| การใช้ tool และอัตรา error | นับ span tool.* และ span ที่ tool.success เป็น False |
# ✏️ TODO 3 (▶ วิดีโอ 6:19): p95 = จุดตัดสุดท้ายของ quantiles แบ่ง 20 ส่วน
runs = [root(t) for t in traces]
saved = sum(any(s.name == "tool.write_report" and s.attributes["tool.success"] for s in tool_spans(t))
for t in traces)
secs = sorted(seconds(r) for r in runs)
p50 = statistics.median(secs)
p95 = ___
cost = [r.attributes["agent.cost_usd"] for r in runs]
print(f"success rate {saved}/{len(runs)} = {saved / len(runs):.0%} (report saved)")
print(f"latency p50 {p50:.1f} s · p95 {p95:.1f} s")
print(f"cost USD {statistics.mean(cost):.5f} per run · {sum(cost):.4f} in all")
usage = Counter(s.attributes["tool.name"] for t in traces for s in tool_spans(t))
errors = Counter(s.attributes["tool.name"] for t in traces for s in tool_spans(t) if not s.attributes["tool.success"])
for name, n in usage.most_common():
print(f"{name:<15} {n:>3} calls · {errors[name]:>2} errors ({errors[name] / n:.0%})")runs = [root(t) for t in traces]
saved = sum(any(s.name == "tool.write_report" and s.attributes["tool.success"] for s in tool_spans(t))
for t in traces)
secs = sorted(seconds(r) for r in runs)
p50 = statistics.median(secs)
p95 = statistics.quantiles(secs, n=20, method="inclusive")[-1]
cost = [r.attributes["agent.cost_usd"] for r in runs]
print(f"success rate {saved}/{len(runs)} = {saved / len(runs):.0%} (report saved)")
print(f"latency p50 {p50:.1f} s · p95 {p95:.1f} s")
print(f"cost USD {statistics.mean(cost):.5f} per run · {sum(cost):.4f} in all")
usage = Counter(s.attributes["tool.name"] for t in traces for s in tool_spans(t))
errors = Counter(s.attributes["tool.name"] for t in traces for s in tool_spans(t) if not s.attributes["tool.success"])
for name, n in usage.most_common():
print(f"{name:<15} {n:>3} calls · {errors[name]:>2} errors ({errors[name] / n:.0%})")success rate 9/12 = 75% (report saved)
latency p50 4.0 s · p95 5.2 s
cost USD 0.00036 per run · 0.0043 in all
search_web 23 calls · 9 errors (39%)
read_document 12 calls · 0 errors (0%)
write_report 9 calls · 0 errors (0%)
5. Logs แบบมีโครงสร้าง
หนึ่งบรรทัดต่อหนึ่งเหตุการณ์ เป็น JSON มีช่องชื่อชัดเจน และมี trace_id → จาก log หนึ่งบรรทัด กลับไปหา trace ทั้งรอบได้ ในระบบจริง เขียน log ตอนที่เหตุการณ์เกิด ในแล็บนี้เราเขียนจาก span เพื่อให้เห็นว่า log กับ trace เชื่อมกันอย่างไร
def trace_id(s):
return format(s.context.trace_id, "032x")
for t in traces:
for s in tool_spans(t):
if not s.attributes["tool.success"]:
print(json.dumps({"event": "tool_error", "tool": s.attributes["tool.name"],
"error": s.attributes["tool.output"][:40], "trace_id": trace_id(s)[:12]}))
def find_trace(prefix):
return next(t for t in traces if trace_id(root(t)).startswith(prefix))
last_error = [s for t in traces for s in tool_spans(t) if not s.attributes["tool.success"]][-1]
show_trace(find_trace(trace_id(last_error)[:12])){"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "1db653d28236"}
{"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "cac13515ff63"}
{"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "e82a3b809999"}
{"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "f434759e15a3"}
{"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "4fffade429e7"}
{"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "4fffade429e7"}
{"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "3d803c45719f"}
{"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "3d803c45719f"}
{"event": "tool_error", "tool": "search_web", "error": "Error: search failed (search API down)", "trace_id": "89e6c6e0367a"}
0.0s 1.1s agent.run What year was PPO published? [done]
0.0s 0.4s llm.call prompt 258 tokens
0.4s 0.0s tool.search_web {"query":"when was PPO (Proximal Policy Optimization) publis ✗ Error: search failed (search API down)
0.4s 0.7s llm.call prompt 308 tokens
6. จัดหมวดความพังจาก trace (Table 25.1)
| หมวด | ตรวจจับ (ตำรา) | กฎของเราบน trace |
|---|---|---|
| tool error | เฝ้าอัตรา error | มี span tool.* ที่ tool.success เป็น False |
| reasoning error | วิเคราะห์ trajectory | อ่าน URL ที่ไม่เคยอยู่ในผลค้นหา (แต่ง argument) |
| hallucination | fact-checking, grounding check | ผู้ตัดสิน (LLM): output อ้างแหล่งที่ไม่ได้อ่าน · หรือตอบโดยไม่ได้อ่านอะไรเลย |
| infinite loop | loop detection, max iterations | เรียก tool + argument เดิม ≥ 3 ครั้ง หรือหมด max_steps |
| context overflow | นับ token | llm.prompt_tokens เกินงบ 4,000 |
| refusal | output classification | ผู้ตัดสิน (LLM): ปฏิเสธ หรือไม่ทำงานที่ขอ |
ผู้ตัดสินแบบ LLM-as-judge ใช้แนวเดียวกับ EP17 — ส่ง เอกสารที่ agent อ่านจริง (จาก span) + output ไปให้ model ตัดสิน
JUDGE = """Documents the agent read:
{docs}
Task: {task}
The agent's output:
{output}
1. List every source the output cites that is not one of the documents above.
2. Did the agent decline or fail to do the task?
Answer JSON only: {{"unsupported": ["..."], "declined": true or false}}"""
def judge(docs, task, output):
r = chat([{"role": "user", "content": JUDGE.format(docs=docs or "(none)", task=task, output=output)}],
response_format={"type": "json_object"})
return json.loads(r.choices[0].message.content)
def docs_read(t):
return "\n\n".join(args_of(s).get("url", "") + "\n" + s.attributes["tool.output"]
for s in tool_spans(t) if s.name == "tool.read_document" and s.attributes["tool.success"])
def output_of(t):
reports = [s for s in tool_spans(t) if s.name == "tool.write_report"]
return args_of(reports[-1]).get("content", "") if reports else root(t).attributes["agent.final_answer"]
VERDICTS = {}
def verdict(t):
key = trace_id(root(t))
if key not in VERDICTS:
VERDICTS[key] = judge(docs_read(t), root(t).attributes["agent.task"], output_of(t))
return VERDICTS[key]
CONTEXT_BUDGET = 4000
def classify(t):
tools, labels = tool_spans(t), []
if any(not s.attributes["tool.success"] for s in tools):
labels.append("tool_error")
seen = set()
for s in tools:
if s.name == "tool.search_web":
seen |= set(re.findall(r"https?://\S+", s.attributes["tool.output"]))
if s.name == "tool.read_document" and args_of(s).get("url") not in seen:
labels.append("reasoning_error")
break
# ✏️ TODO 4 (▶ วิดีโอ 9:06): infinite loop: status เป็น max_steps หรือ (tool, args) เดิมซ้ำ ≥ 3 ครั้ง
steps = [(s.name, s.attributes["tool.args"]) for s in tools]
if ___:
labels.append("infinite_loop")
if max(s.attributes["llm.prompt_tokens"] for s in llm_spans(t)) > CONTEXT_BUDGET:
labels.append("context_overflow")
v = verdict(t)
if v.get("unsupported") or (not docs_read(t) and not v.get("declined")):
labels.append("hallucination")
if v.get("declined"):
labels.append("refusal")
return labelsJUDGE = """Documents the agent read:
{docs}
Task: {task}
The agent's output:
{output}
1. List every source the output cites that is not one of the documents above.
2. Did the agent decline or fail to do the task?
Answer JSON only: {{"unsupported": ["..."], "declined": true or false}}"""
def judge(docs, task, output):
r = chat([{"role": "user", "content": JUDGE.format(docs=docs or "(none)", task=task, output=output)}],
response_format={"type": "json_object"})
return json.loads(r.choices[0].message.content)
def docs_read(t):
return "\n\n".join(args_of(s).get("url", "") + "\n" + s.attributes["tool.output"]
for s in tool_spans(t) if s.name == "tool.read_document" and s.attributes["tool.success"])
def output_of(t):
reports = [s for s in tool_spans(t) if s.name == "tool.write_report"]
return args_of(reports[-1]).get("content", "") if reports else root(t).attributes["agent.final_answer"]
VERDICTS = {}
def verdict(t):
key = trace_id(root(t))
if key not in VERDICTS:
VERDICTS[key] = judge(docs_read(t), root(t).attributes["agent.task"], output_of(t))
return VERDICTS[key]
CONTEXT_BUDGET = 4000
def classify(t):
tools, labels = tool_spans(t), []
if any(not s.attributes["tool.success"] for s in tools):
labels.append("tool_error")
seen = set()
for s in tools:
if s.name == "tool.search_web":
seen |= set(re.findall(r"https?://\S+", s.attributes["tool.output"]))
if s.name == "tool.read_document" and args_of(s).get("url") not in seen:
labels.append("reasoning_error")
break
steps = [(s.name, s.attributes["tool.args"]) for s in tools]
if root(t).attributes["agent.status"] == "max_steps" or any(steps.count(x) >= 3 for x in steps):
labels.append("infinite_loop")
if max(s.attributes["llm.prompt_tokens"] for s in llm_spans(t)) > CONTEXT_BUDGET:
labels.append("context_overflow")
v = verdict(t)
if v.get("unsupported") or (not docs_read(t) and not v.get("declined")):
labels.append("hallucination")
if v.get("declined"):
labels.append("refusal")
return labelslabels = [classify(t) for t in traces]
for i, (t, ls) in enumerate(zip(traces, labels)):
print(f"{i:>2} {root(t).attributes['agent.task'][:34]:<35} {' → '.join(ls) or 'ok'}")
print()
print(Counter(l for ls in labels for l in ls))
print("largest prompt:", max(s.attributes["llm.prompt_tokens"] for t in traces for s in llm_spans(t)), "tokens") 0 Research transformers for time-ser tool_error → hallucination
1 Research the history of reinforcem tool_error → hallucination
2 What year was PPO published? tool_error
3 Compare Informer and PatchTST for tool_error → hallucination
4 Research transformers for time-ser tool_error → hallucination
5 Research the history of reinforcem hallucination
6 What year was PPO published? tool_error → hallucination
7 Compare Informer and PatchTST for ok
8 Research transformers for time-ser hallucination
9 Research the history of reinforcem hallucination
10 What year was PPO published? tool_error → hallucination
11 Compare Informer and PatchTST for ok
Counter({'hallucination': 9, 'tool_error': 7})
largest prompt: 1504 tokens
cascade = next((t for t, ls in zip(traces, labels) if ls[:1] == ["tool_error"] and len(ls) > 1), None)
if cascade:
show_trace(cascade)
print("\noutput:", output_of(cascade)[:300]) 0.0s 5.1s agent.run Research transformers for time-series forecasting [done]
0.0s 0.6s llm.call prompt 258 tokens
0.6s 0.0s tool.search_web {"query":"transformers for time-series forecasting research
0.6s 0.5s llm.call prompt 334 tokens
1.1s 0.0s tool.search_web {"query":"state of the art transformers for time-series fore ✗ Error: search failed (search API down)
1.1s 0.5s llm.call prompt 390 tokens
1.6s 0.0s tool.search_web {"query":"transformer architectures for time series forecast
1.6s 0.5s llm.call prompt 508 tokens
2.1s 0.0s tool.read_document {"url":"https://arxiv.org/abs/2211.14730"}
2.1s 2.4s llm.call prompt 595 tokens
4.5s 0.0s tool.write_report {"content":"# Research Report: Transformers for Time-Series
4.5s 0.7s llm.call prompt 1271 tokens
output: # Research Report: Transformers for Time-Series Forecasting
## Overview
The application of Transformer architectures to time-series forecasting has evolved from direct adaptations of the original NLP Transformer to specialized architectures designed to handle the unique properties of temporal data
7. Replay ขั้นที่พัง (Listing 25.19)
ตำราใช้ LangSmith โหลด trace ตาม run id แล้วส่ง input ของขั้นที่พังเข้า model อีกครั้ง ด้วย model ที่เก่งกว่า หรือ prompt ใหม่ เราทำแบบเดียวกันกับ span ของเราเอง:
- เลือกรอบที่เป็น hallucination (รายงานอ้างแหล่งที่ไม่ได้อ่าน)
- หา span
llm.callที่ตัดสินใจเรียกwrite_report→ ดึงllm.messagesออกมา - เปลี่ยน system prompt แล้วส่ง messages ชุดเดิมให้ model ใหม่ (temperature 0) → model ตัดสินใจต่างไปไหม
# ✏️ TODO 5 (▶ วิดีโอ 11:18): เปลี่ยนข้อความแรก (system) เป็น system prompt ที่ส่งเข้ามา
FIXED = SYSTEM + (" Write the report only from the documents you read: cite only their URLs, "
"and add no facts or sources from memory.")
def replay(t, system):
report = [s for s in tool_spans(t) if s.name == "tool.write_report"][-1]
step = max((s for s in llm_spans(t) if s.end_time <= report.start_time), key=lambda s: s.end_time)
messages = json.loads(step.attributes["llm.messages"])
___
msg = chat(messages, TOOL_SCHEMAS).choices[0].message
return msg.tool_calls or [], msg.content
bad = next(t for t, ls in zip(traces, labels)
if "hallucination" in ls and any(s.name == "tool.write_report" for s in tool_spans(t)))
print("task:", root(bad).attributes["agent.task"])
print("unsupported:", verdict(bad)["unsupported"])
for name, system in [("current", SYSTEM), ("current", SYSTEM), ("fixed", FIXED), ("fixed", FIXED)]:
calls, text = replay(bad, system)
for c in calls:
if c.function.name == "write_report":
v = judge(docs_read(bad), root(bad).attributes["agent.task"], parse_args(c)["content"])
print(f"{name:<8} write_report → unsupported: {v['unsupported']}")
else:
print(f"{name:<8} {c.function.name}({c.function.arguments})")
if not calls:
print(f"{name:<8} answer: {(text or '')[:80]}")FIXED = SYSTEM + (" Write the report only from the documents you read: cite only their URLs, "
"and add no facts or sources from memory.")
def replay(t, system):
report = [s for s in tool_spans(t) if s.name == "tool.write_report"][-1]
step = max((s for s in llm_spans(t) if s.end_time <= report.start_time), key=lambda s: s.end_time)
messages = json.loads(step.attributes["llm.messages"])
messages[0] = {"role": "system", "content": system}
msg = chat(messages, TOOL_SCHEMAS).choices[0].message
return msg.tool_calls or [], msg.content
bad = next(t for t, ls in zip(traces, labels)
if "hallucination" in ls and any(s.name == "tool.write_report" for s in tool_spans(t)))
print("task:", root(bad).attributes["agent.task"])
print("unsupported:", verdict(bad)["unsupported"])
for name, system in [("current", SYSTEM), ("current", SYSTEM), ("fixed", FIXED), ("fixed", FIXED)]:
calls, text = replay(bad, system)
for c in calls:
if c.function.name == "write_report":
v = judge(docs_read(bad), root(bad).attributes["agent.task"], parse_args(c)["content"])
print(f"{name:<8} write_report → unsupported: {v['unsupported']}")
else:
print(f"{name:<8} {c.function.name}({c.function.arguments})")
if not calls:
print(f"{name:<8} answer: {(text or '')[:80]}")task: Research transformers for time-series forecasting
unsupported: ['Informer: Efficient Transformer for Long Sequence Time-Series Forecasting (https://arxiv.org/abs/2012.07436)', 'Autoformer', 'FEDformer (Frequency Enhanced Decomposed Transformer)']
current write_report → unsupported: ['Informer: Efficient Transformer for Long Sequence Time-Series Forecasting (https://arxiv.org/abs/2012.07436)', 'Autoformer', 'FEDformer (Frequency Enhanced Decomposition Transformer)']
current write_report → unsupported: ['Informer: Efficient Transformer for Long Sequence Time-Series Forecasting (https://arxiv.org/abs/2012.07436)', 'Autoformer', 'FEDformer (Frequency Enhanced Decomposed Transformer)']
fixed read_document({"url":"https://arxiv.org/abs/2012.07436"})
fixed read_document({"url":"https://arxiv.org/abs/2012.07436"})
ตรวจวิธีแก้กับทั้งรอบ
รันสี่งานของข้อ 3 งานละสองรอบ = 8 รอบ ด้วย prompt เดิม และ 8 รอบ ด้วย prompt ใหม่ (search ไม่ล่ม) แล้วจัดหมวดด้วย classify ตัวเดิม วิธีแก้ต้องใช้ได้กับทุกงาน ไม่ใช่แค่งานของรอบที่เรา replay
OUTAGE = 0.0
def check(system):
exporter.clear()
for task in TASKS * 2:
InstrumentedAgent(system=system).run(task)
found = traces_of(exporter.get_finished_spans())
for t in found:
print(f" {root(t).attributes['agent.task'][:34]:<35} {' → '.join(classify(t)) or 'ok'}")
return sum("hallucination" in classify(t) for t in found), len(found)
print("current prompt:"); before, n = check(SYSTEM)
print("fixed prompt:"); after, n = check(FIXED)
print(f"\nhallucination: current {before}/{n} · fixed {after}/{n}")current prompt:
Research transformers for time-ser ok
Research the history of reinforcem hallucination
What year was PPO published? hallucination
Compare Informer and PatchTST for ok
Research transformers for time-ser hallucination
Research the history of reinforcem tool_error → reasoning_error → hallucination
What year was PPO published? ok
Compare Informer and PatchTST for ok
fixed prompt:
Research transformers for time-ser ok
Research the history of reinforcem infinite_loop → refusal
What year was PPO published? ok
Compare Informer and PatchTST for ok
Research transformers for time-ser ok
Research the history of reinforcem infinite_loop
What year was PPO published? ok
Compare Informer and PatchTST for ok
hallucination: current 4/8 · fixed 0/8
print(f"Cost of this lab: USD {COST['chat']:.4f}")Cost of this lab: USD 0.0123
สรุป
| เสา | ในแล็บนี้ | ตอบคำถาม |
|---|---|---|
| Traces | span agent.run · llm.call · tool.* + attribute ตาม Listing 25.18 |
รอบนี้เกิดอะไรขึ้น ทีละขั้น |
| Metrics | อัตราสำเร็จ · p50/p95 · ค่าใช้จ่าย · อัตรา error ต่อ tool — คำนวณจาก span | ภาพรวมเป็นอย่างไร |
| Logs | JSON หนึ่งบรรทัดต่อเหตุการณ์ พร้อม trace_id |
เกิดที่ไหน แล้วพาไปหา trace |
- Table 25.1: หกหมวดเป็นกฎบน trace — สี่หมวดอ่านจาก attribute ตรงๆ · hallucination / refusal ใช้ LLM-as-judge กับเอกสารที่ agent อ่านจริง
- อัตราสำเร็จหลอกได้: รอบที่บันทึกรายงานได้ ยังอ้างแหล่งที่ไม่ได้อ่านได้
- ลูกโซ่: tool error → คำตอบที่ไม่ได้มาจากแหล่งข้อมูล — แก้ต้นเหตุ ไม่ใช่แค่อาการ
- Replay (Listing 25.19): ส่ง
llm.messagesของขั้นที่พังให้ model อีกครั้งด้วย prompt ใหม่ — ไม่ใช่การทำซ้ำแบบเป๊ะ และขั้นเดียวไม่พอ ต้องวัดทั้งรอบ
แบบฝึกหัด
- ตั้ง
OUTAGE = 0.6แล้วรันข้อ 3–6 ใหม่ หมวดไหนเพิ่มขึ้น ลูกโซ่หน้าตาเหมือนเดิมไหม - ใช้
ResearchAgentV2ที่ไม่มี circuit breaker (ให้schemasคืนTOOL_SCHEMASทุกครั้ง) — กฎ infinite loop จับได้กี่รอบ - ลด
CONTEXT_BUDGETให้ต่ำกว่า prompt ที่ใหญ่ที่สุด — มีกี่รอบถูกจัดเป็น context overflow แล้วงบเท่าไรถึงเหมาะกับ agent นี้
ถัดไป — Lab 4: ส่ง span ชุดเดียวกันเข้า Arize Phoenix — ดู trace ใน UI จริง และใช้ evaluator ของ framework