Lab 4 — Arize Phoenix: trace ชุดเดิมในเครื่องมือจริง และ evaluator ของ framework
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 3 เราใส่ span เอง แล้วเขียน Python อ่านเองทุกบรรทัด Lab นี้ส่ง trace ของ agent ตัวเดิมเข้า Arize Phoenix — เครื่องมือ observability แบบ open source ที่ตำรายกตัวอย่างไว้ใน §25.6 รันบนเครื่องเรา ไม่ต้องสมัครบัญชี
สิ่งที่จะได้ทำ
- เปิด Phoenix บนเครื่อง
- ต่อ agent เข้า Phoenix: span ของ model มาเอง (auto-instrumentation) เราใส่แค่ span ของ agent กับ tool
- จำลอง production ชุดเดิมของ Lab 3 แล้วดู trace ใน UI ของ Phoenix
- ดึง span กลับมาเป็นตาราง แล้วคำนวณ metrics ด้วย pandas
- ใช้ evaluator สำเร็จรูป ของ Phoenix ตัดสิน hallucination และ refusal แล้วเทียบกับผู้ตัดสินของ Lab 3
- ส่งผลตัดสินกลับไปแปะบน trace ใน Phoenix
ข้อมูลค้นหาและการล่มของ search API เป็นของจำลองเพื่อการสอน ส่วน output ของ model และผลตัดสินมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §25.6 — CC BY-SA 4.0 · Arize Phoenix — Elastic License 2.0 · OpenInference — Apache 2.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ราวหนึ่งเซ็นต์ดอลลาร์) |
| Packages | arize-phoenix, arize-phoenix-otel, arize-phoenix-evals, openinference-instrumentation-openai, opentelemetry-sdk, openai, python-dotenv (ติดตั้งใน cell ถัดไป — Phoenix ใหญ่ ใช้เวลาสักครู่) |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env
%pip install -q "arize-phoenix==22.1.0" "arize-phoenix-otel==0.17.3" "arize-phoenix-evals==3.10.0" "openinference-instrumentation-openai==0.1.78" "opentelemetry-sdk==1.45.2" "openai>=1.50" python-dotenv httpximport json, os, random, time, warnings
import httpx
import pandas as pd
from dataclasses import dataclass
from IPython.display import IFrame
from openai import OpenAI
from opentelemetry.trace import Status, StatusCode
import phoenix as px
from phoenix.otel import register
from phoenix.client import Client
from phoenix.evals import LLM, evaluate_dataframe
from phoenix.evals.metrics import HallucinationEvaluator, RefusalEvaluator
from phoenix.evals.utils import to_annotation_dataframe
from openinference.instrumentation import suppress_tracing
warnings.filterwarnings("ignore")
os.environ["GRPC_VERBOSITY"] = "ERROR"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"]
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5, timeout=60)
COST = {"chat": 0.0, "judge": 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–3
tool สามตัวบนข้อมูลค้นหาจำลอง · run_tool · system prompt · ส่วนประกอบของ ResearchAgentV2 (circuit breaker) — เหมือน Lab 3 ส่วนที่ต่างคือ loop ของ agent ซึ่งเราจะเขียนใหม่ในข้อ 2 โดยใส่ span ของ Phoenix เข้าไป
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. เปิด Phoenix บนเครื่อง
px.launch_app() เปิดเซิร์ฟเวอร์ Phoenix ใน notebook นี้เอง ที่ http://localhost:6006 (บน Colab จะได้ลิงก์ของ Colab แทน)
| Lab 3 | Lab 4 | |
|---|---|---|
| span ไปที่ | InMemorySpanExporter ในหน่วยความจำ |
เซิร์ฟเวอร์ Phoenix — เก็บลงฐานข้อมูลชั่วคราว |
| ดู trace ด้วย | show_trace ที่เขียนเอง |
หน้าจอของ Phoenix |
ถ้าขึ้น server took too long to start (เปิดครั้งแรกหลังติดตั้ง) ให้รัน cell นี้อีกครั้ง
session = px.launch_app()
PROJECT = "ep18-lab4"boto3 is installed but aioboto3 is not. To use AWS Bedrock models in Playground, install aioboto3: pip install aioboto3
🌍 To view the Phoenix app in your browser, visit http://localhost:6006/
📖 For more information on how to use Phoenix, check out https://arize.com/docs/phoenix
2. ต่อ agent เข้า Phoenix
register(..., auto_instrument=True) ทำสองอย่าง:
- ตั้ง tracer provider ที่ส่ง span ไป Phoenix — แทน exporter ห้าบรรทัดของ Lab 3
- เปิด auto-instrumentation: ทุกครั้งที่เรียก
client.chat.completions.createจะได้ span ชนิด LLM เอง พร้อม messages, token และ tool call — แทน spanllm.callที่เราเขียนเอง
span ที่เหลือเราใส่เอง แต่ใช้ OpenInference — ชุดชื่อ attribute มาตรฐานสำหรับงาน LLM ที่ Phoenix อ่านเป็น:
| span | ชนิด (openinference_span_kind) |
ใส่อะไร |
|---|---|---|
research_agent |
agent |
set_input(task) · set_output(คำตอบ) |
search_web, read_document, write_report |
tool |
set_tool(...) · set_input(args) · set_output(ผล) · ERROR ถ้าพัง |
tracer_provider = register(project_name=PROJECT, auto_instrument=True, verbose=False)
tracer = tracer_provider.get_tracer("agent.tracer")# ✏️ TODO 1 (▶ วิดีโอ 3:36): เปิด span ชนิด agent (openinference_span_kind="agent")
class PhoenixAgent(ResearchAgentV2):
def run(self, task):
self.failures, self.down = {}, set()
with tracer.start_as_current_span("research_agent", ___) as span:
span.set_input(task)
result = self.loop(task)
span.set_output(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):
r = chat(messages, self.schemas()) # LLM span: added by auto-instrumentation
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 (▶ วิดีโอ 4:04): เปิด span ชนิด tool ชื่อเดียวกับ tool
for call in msg.tool_calls:
name = call.function.name
with ___ as span:
span.set_tool(name=name, parameters=call.function.arguments or "{}")
span.set_input(call.function.arguments or "{}", mime_type="application/json")
out = run_tool(self.tools, call)
span.set_output(out)
if out.startswith("Error"):
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)class PhoenixAgent(ResearchAgentV2):
def run(self, task):
self.failures, self.down = {}, set()
with tracer.start_as_current_span("research_agent", openinference_span_kind="agent") as span:
span.set_input(task)
result = self.loop(task)
span.set_output(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):
r = chat(messages, self.schemas()) # LLM span: added by auto-instrumentation
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(name, openinference_span_kind="tool") as span:
span.set_tool(name=name, parameters=call.function.arguments or "{}")
span.set_input(call.function.arguments or "{}", mime_type="application/json")
out = run_tool(self.tools, call)
span.set_output(out)
if out.startswith("Error"):
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)3. production ชุดเดิม ใน UI ของ Phoenix
สี่งานของ Lab 3 · 12 รอบ · search API ล่ม 30% (ลูกเต๋า seed เดิม)
เครื่องมือ (เขียนไว้ให้แล้ว):
phoenix_spans()— ดึง span ทั้งหมดของ project กลับมาเป็น DataFrameshow(path)— ฝังหน้าหนึ่งของ Phoenix ไว้ใน notebook
px_client = Client()
def phoenix_spans():
tracer_provider.force_flush()
time.sleep(2) # let the server store the last spans
return px_client.spans.get_spans_dataframe(project_name=PROJECT)
def show(path=""):
return IFrame(session.url + path, width="100%", height=640)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 = ["Research transformers for time-series forecasting",
"Research the history of reinforcement learning",
"What year was PPO published?",
"Compare Informer and PatchTST for long forecasting horizons"]
for i in range(12):
PhoenixAgent().run(TASKS[i % len(TASKS)])
spans = phoenix_spans()
print(spans.span_kind.value_counts().to_string())span_kind
LLM 55
TOOL 43
AGENT 12
project_id = px_client.projects.get(project_name=PROJECT)["id"]
show(f"projects/{project_id}/traces")[12]:
tools = spans[spans.span_kind == "TOOL"]
failed = set(tools[tools.status_code == "ERROR"]["context.trace_id"])
saved = set(tools[tools.name == "write_report"]["context.trace_id"])
cascade = sorted(failed & saved)[0]
show(f"projects/{project_id}/traces/{cascade}")[13]:
4. metrics จากตาราง span
phoenix_spans() คืน DataFrame หนึ่งแถวต่อหนึ่ง span — คอลัมน์ที่ใช้: span_kind · name · status_code · start_time / end_time · context.trace_id · attributes.llm.token_count.prompt
metrics ชุดเดียวกับ Lab 3 ข้อ 4 ด้วย pandas ไม่กี่บรรทัด
# ✏️ TODO 3 (▶ วิดีโอ 6:20): อัตราสำเร็จ: สัดส่วนของ agent span ที่ trace_id อยู่ใน saved
agents = spans[spans.span_kind == "AGENT"]
llms = spans[spans.span_kind == "LLM"]
success = ___
secs = (agents.end_time - agents.start_time).dt.total_seconds()
print(f"success rate {success:.0%} · p50 {secs.median():.1f} s · p95 {secs.quantile(0.95):.1f} s")
print(f"largest prompt {llms['attributes.llm.token_count.prompt'].max():.0f} tokens · cost USD {COST['chat']:.4f}")
print((tools.status_code == "ERROR").groupby(tools.name).agg(["count", "mean"]).round(2))agents = spans[spans.span_kind == "AGENT"]
llms = spans[spans.span_kind == "LLM"]
success = agents["context.trace_id"].isin(saved).mean()
secs = (agents.end_time - agents.start_time).dt.total_seconds()
print(f"success rate {success:.0%} · p50 {secs.median():.1f} s · p95 {secs.quantile(0.95):.1f} s")
print(f"largest prompt {llms['attributes.llm.token_count.prompt'].max():.0f} tokens · cost USD {COST['chat']:.4f}")
print((tools.status_code == "ERROR").groupby(tools.name).agg(["count", "mean"]).round(2))success rate 67% · p50 4.2 s · p95 5.9 s
largest prompt 1589 tokens · cost USD 0.0043
count mean
name
read_document 12 0.00
search_web 23 0.39
write_report 8 0.00
5. evaluator สำเร็จรูปของ Phoenix
phoenix.evals.metrics มี evaluator ที่เขียน prompt ผู้ตัดสินไว้แล้ว เช่น:
| evaluator | ตัดสินว่า | ต้องให้ |
|---|---|---|
HallucinationEvaluator |
grounded / hallucinated — คำตอบมีอะไรที่บทสนทนาไม่รองรับไหม |
input = บทสนทนา (รวมผล tool) · output = คำตอบ |
RefusalEvaluator |
answered / refused |
input · output |
model ผู้ตัดสินคือ Gemma ตัวเดิมผ่าน OpenRouter — ห่อด้วย LLM(...) ของ Phoenix
eval_rows(spans) (เขียนไว้ให้แล้ว) สร้างหนึ่งแถวต่อหนึ่งรอบจาก span: input = งาน + ทุก tool call กับผล · output = รายงาน (หรือคำตอบสุดท้ายถ้าไม่มีรายงาน) · docs = เอกสารที่อ่านสำเร็จ (ไว้ให้ผู้ตัดสินของ Lab 3)
def eval_rows(spans):
rows = []
for trace_id, t in spans.sort_values("start_time").groupby("context.trace_id", sort=False):
agent = t[t.span_kind == "AGENT"].iloc[0]
conversation, report, docs = ["User: " + agent["attributes.input.value"]], None, []
for _, s in t[t.span_kind == "TOOL"].iterrows():
args, out = s["attributes.input.value"], s["attributes.output.value"]
if s["name"] == "write_report":
report = json.loads(args).get("content", "")
continue
conversation.append(f"Tool {s['name']}({args}) → {out}")
if s["name"] == "read_document" and s.status_code != "ERROR":
docs.append(json.loads(args)["url"] + "\n" + out)
rows.append({"span_id": agent["context.span_id"], "trace_id": trace_id,
"task": agent["attributes.input.value"], "input": "\n".join(conversation),
"output": report if report is not None else (agent["attributes.output.value"] or ""),
"docs": "\n\n".join(docs)})
return pd.DataFrame(rows).set_index("span_id")
def add_judge_cost(response):
response.read()
COST["judge"] += response.json().get("usage", {}).get("cost", 0) or 0
judge_llm = LLM(provider="openai", model=MODEL, api_key=load_key(), base_url="https://openrouter.ai/api/v1",
initial_per_second_request_rate=1,
sync_client_kwargs={"http_client": httpx.Client(timeout=60, event_hooks={"response": [add_judge_cost]})})# ✏️ TODO 4 (▶ วิดีโอ 7:50): สร้าง evaluator สองตัว: HallucinationEvaluator และ RefusalEvaluator
evals = eval_rows(spans)
evaluators = [___,
___]
with suppress_tracing():
results = evaluate_dataframe(dataframe=evals, evaluators=evaluators, hide_tqdm_bar=True)
label = lambda col: results[col].map(lambda s: (json.loads(s) if isinstance(s, str) else s)["label"])
results["phoenix"], results["refusal"] = label("hallucination_score"), label("refusal_score")
print(results[["task", "phoenix", "refusal"]].to_string(index=False))evals = eval_rows(spans)
evaluators = [HallucinationEvaluator(llm=judge_llm, temperature=0, extra_body=EXTRA),
RefusalEvaluator(llm=judge_llm, temperature=0, extra_body=EXTRA)]
with suppress_tracing():
results = evaluate_dataframe(dataframe=evals, evaluators=evaluators, hide_tqdm_bar=True)
label = lambda col: results[col].map(lambda s: (json.loads(s) if isinstance(s, str) else s)["label"])
results["phoenix"], results["refusal"] = label("hallucination_score"), label("refusal_score")
print(results[["task", "phoenix", "refusal"]].to_string(index=False)) task phoenix refusal
Research transformers for time-series forecasting hallucinated answered
Research the history of reinforcement learning hallucinated answered
What year was PPO published? grounded answered
Compare Informer and PatchTST for long forecasting horizons hallucinated answered
Research transformers for time-series forecasting grounded answered
Research the history of reinforcement learning hallucinated answered
What year was PPO published? hallucinated answered
Compare Informer and PatchTST for long forecasting horizons hallucinated answered
Research transformers for time-series forecasting grounded answered
Research the history of reinforcement learning hallucinated answered
What year was PPO published? grounded answered
Compare Informer and PatchTST for long forecasting horizons hallucinated answered
เทียบกับผู้ตัดสินของ Lab 3
lab3_hallucination(row) (เขียนไว้ให้แล้ว) = กฎ hallucination ของ Lab 3: output อ้างแหล่งที่ไม่ได้อ่าน หรือตอบทั้งที่ไม่ได้อ่านอะไรเลย (และไม่ได้ปฏิเสธ)
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 lab3_hallucination(row):
r = chat([{"role": "user", "content": JUDGE.format(docs=row.docs or "(none)", task=row.task, output=row.output)}],
response_format={"type": "json_object"})
v = json.loads(r.choices[0].message.content)
return bool(v.get("unsupported") or (not row.docs and not v.get("declined")))with suppress_tracing():
results["lab3"] = [lab3_hallucination(row) for row in results.itertuples()]
results["phoenix_h"] = results.phoenix == "hallucinated"
print(f"hallucinated: Phoenix {results.phoenix_h.sum()}/{len(results)} · Lab 3 {results.lab3.sum()}/{len(results)} · "
f"agree on {(results.phoenix_h == results.lab3).sum()}")hallucinated: Phoenix 8/12 · Lab 3 8/12 · agree on 6
explain = lambda s: (json.loads(s) if isinstance(s, str) else s)["explanation"]
for row in results[results.phoenix_h != results.lab3].itertuples():
print(f"■ {row.task} — Phoenix: {row.phoenix} · Lab 3: {'hallucinated' if row.lab3 else 'ok'}")
print(" output: ", row.output[:150].replace("\n", " "))
print(" Phoenix:", explain(row.hallucination_score)[:260].replace("\n", " "), "\n")■ What year was PPO published? — Phoenix: grounded · Lab 3: hallucinated
output: Proximal Policy Optimization (PPO) was published in 2017.
Phoenix: The response states that Proximal Policy Optimization (PPO) was published in 2017. This claim is directly supported by the tool result provided in the input: 'Proximal Policy Optimization Algorithms (2017) — https://arxiv.org/abs/1707.06347'.
■ Compare Informer and PatchTST for long forecasting horizons — Phoenix: hallucinated · Lab 3: ok
output: # Comparison: Informer vs. PatchTST for Long-Term Forecasting ## Overview Both Informer and PatchTST are Transformer-based architectures designed to
Phoenix: The response is HALLUCINATED. While the assistant correctly identifies the core mechanisms mentioned in the input (ProbSparse self-attention for Informer and patching/channel independence for PatchTST), it introduces several specific technical details and perf
■ Research transformers for time-series forecasting — Phoenix: grounded · Lab 3: hallucinated
output: Since I cannot access live web search results at this moment due to a technical error, I will provide a comprehensive research summary based on my int
Phoenix: The assistant's response is GROUNDED. 1. The assistant correctly identifies that it cannot access live web search results due to a technical error, which is supported by the input showing two failed tool calls (`Error: search failed (search API down)`). 2. T
■ Compare Informer and PatchTST for long forecasting horizons — Phoenix: hallucinated · Lab 3: ok
output: # Comparison: Informer vs. PatchTST for Long-Term Forecasting ## Overview Both Informer and PatchTST are Transformer-based architectures designed to
Phoenix: The response is HALLUCINATED. While the input provides the titles and URLs for the Informer and PatchTST papers, and a brief summary of PatchTST, it does not contain any information regarding the specific technical mechanisms of the Informer model (such as 'Pr
■ What year was PPO published? — Phoenix: grounded · Lab 3: hallucinated
output: Proximal Policy Optimization (PPO) was published in 2017.
Phoenix: The claim that Proximal Policy Optimization (PPO) was published in 2017 is directly supported by the tool result provided in the input: 'Proximal Policy Optimization Algorithms (2017) — https://arxiv.org/abs/1707.06347'.
■ Compare Informer and PatchTST for long forecasting horizons — Phoenix: hallucinated · Lab 3: ok
output: # Comparison: Informer vs. PatchTST for Long-Term Forecasting ## Overview Both Informer and PatchTST are Transformer-based architectures designed to
Phoenix: The response is HALLUCINATED. While the assistant correctly identifies the core concepts mentioned in the input (ProbSparse attention for Informer and patching/channel independence for PatchTST), it introduces several specific technical details and performance
6. แปะผลตัดสินกลับบน trace
to_annotation_dataframe(...) แปลงผลของ evaluator เป็นตาราง annotation (label · score · explanation) ตาม span_id แล้ว log_span_annotations_dataframe(...) ส่งเข้า Phoenix — ผลตัดสินไปอยู่บน span ของ agent ในแต่ละ trace
# ✏️ TODO 5 (▶ วิดีโอ 10:15): ส่ง annotations เข้า Phoenix ด้วย log_span_annotations_dataframe
annotations = to_annotation_dataframe(dataframe=results, score_names=["hallucination", "refusal"])
___
first = results[results.phoenix_h != results.lab3].iloc[0]
show(f"projects/{project_id}/traces/{first.trace_id}")annotations = to_annotation_dataframe(dataframe=results, score_names=["hallucination", "refusal"])
px_client.spans.log_span_annotations_dataframe(dataframe=annotations, sync=True)
first = results[results.phoenix_h != results.lab3].iloc[0]
show(f"projects/{project_id}/traces/{first.trace_id}")[20]:
print(f"Cost of this lab: agent USD {COST['chat']:.4f} · Phoenix judge USD {COST['judge']:.4f} · "
f"total USD {COST['chat'] + COST['judge']:.4f}")Cost of this lab: agent USD 0.0051 · Phoenix judge USD 0.0037 · total USD 0.0089
สรุป
| Lab 3 (เขียนเอง) | Lab 4 (Phoenix) | |
|---|---|---|
| span ของ model | llm.call เขียนเอง |
auto-instrumentation |
| span ของ agent / tool | ชื่อ attribute ตามตำรา | OpenInference: agent · tool · set_input / set_output |
| ดู trace | show_trace |
หน้าจอของ Phoenix — ต้นไม้ span · สีแดงเมื่อพัง |
| metrics | Python ทีละตัว | DataFrame + pandas · กราฟในหน้าจอ (แต่ต้นทุนเป็น $0 เพราะไม่รู้ราคา model) |
| hallucination | ผู้ตัดสินของเรา: แหล่งที่อ้างเทียบกับเอกสารที่อ่าน | HallucinationEvaluator: ทุกประโยคเทียบกับทั้งบทสนทนา |
- evaluator สำเร็จรูปมีนิยามของมันเอง — อ่านนิยาม ดูรอบที่ไม่ตรงกับเรา แล้วเลือกนิยามที่ตรงกับที่ระบบสัญญาไว้
- ผลตัดสินกลับไปอยู่บน trace — เห็นสิ่งที่ agent ทำกับผลตัดสินในที่เดียว และกรองรอบที่พังได้
แบบฝึกหัด
- ใช้
FaithfulnessEvaluatorแทน โดยให้context=docs(เอกสารที่อ่านจริง) — ผลใกล้ผู้ตัดสินของ Lab 3 ขึ้นไหม - ใน Phoenix เปิด span ของ LLM ที่เขียนรายงานในรอบที่ hallucinated แล้วกด Playground — แก้ system prompt เป็น
FIXEDของ Lab 3 แล้วรันใหม่ นี่คือ replay ผ่านหน้าจอ - ตั้ง
OUTAGE = 0.6รันข้อ 3–5 ใหม่ — รอบที่ไม่ตรงกันแบบที่สอง (ไม่ได้อ่าน แต่บอกที่มา) เพิ่มขึ้นไหม