Skip to main content

Lab 1 — Testing pyramid ด้วย pytest

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 ที่คุณรันเองจึงอาจต่างจากหน้านี้

คลิปทฤษฎีบอกว่าการทดสอบ agent ต้องมีหลายชั้น (Figure 25.4): ชั้นล่าง unit test เยอะ เร็ว แยกเดี่ยว ชั้นบน integration และ end-to-end น้อยกว่า ช้ากว่า แต่มั่นใจกว่า (§25.5) Lab นี้เราจะสร้างพีระมิดนั้นกับ research agent ของเรา ไล่จากล่างขึ้นบน

สิ่งที่จะได้ทำ

  1. tool สามตัว (search_web · read_document · write_report) บนข้อมูลค้นหาจำลอง
  2. unit test ของ search_web ด้วย mock และ patch (Listing 25.13)
  3. component test ของตัวเรียก tool ใน agent
  4. integration test: model จริง tool ปลอม รันซ้ำ 5 รอบ (Listing 25.14) → test ไหน flaky
  5. แก้ bug ที่ integration test เจอ แล้วรันซ้ำ
  6. end-to-end หนึ่งตัวที่ยอดพีระมิด

ข้อมูลค้นหาเป็นข้อมูลจำลองเพื่อการสอน ส่วน output ของ model มาจากการรันจริง

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §25.5, Figure 25.4, Listings 25.13–25.14 — CC BY-SA 4.0

0. เตรียมเครื่องก่อนเริ่ม

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ราวหนึ่งเซ็นต์ดอลลาร์)
Packages pytest, ipytest, 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 pytest ipytest "openai>=1.50" python-dotenv
import json, os, time
from dataclasses import dataclass
from types import SimpleNamespace
from unittest.mock import patch
import pytest, ipytest
from openai import OpenAI

ipytest.autoconfig(addopts=["-q", "--color=no", "-p", "no:cacheprovider", "-p", "no:warnings"])
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}

Model: google/gemma-4-26b-a4b-it — model เดียวกับทุก EP ล็อก provider เป็น Makora · lab นี้ต้องการ tool calling: agent เรียก tool ผ่าน API ของ model · ราคา 0.09 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.27 ต่อล้าน token ขาออก — รันทั้ง lab ราวหนึ่งเซ็นต์ เพราะ integration test รัน agent ซ้ำหลายสิบรอบ · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-12-03: 3 ใน 3 ครั้งได้ 429)

MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False},
         "provider": {"order": ["makora"], "allow_fallbacks": False}}

def chat(messages, tools):
    r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA,
                                       messages=messages, tools=tools)
    COST["chat"] += r.usage.cost
    return r

1. Tool สามตัวบนข้อมูลค้นหาจำลอง

tool ทำอะไร
search_web(query) ค้น แล้วคืนชื่อเรื่อง + URL · query ว่าง → ValueError · API ล่ม → ข้อความ error · โดน rate limit → ลองใหม่หนึ่งครั้ง
read_document(url) คืนเนื้อหาของ URL
write_report(title, content) เก็บรายงาน

search_api คือ “บริการค้นหาข้างนอก” ที่ tool เรียก ในงานจริงเป็น HTTP API ใน lab นี้ค้นจากเอกสารห้าชิ้นในเครื่อง

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}

2. Unit test — ชั้นล่างสุด (Listing 25.13)

ทดสอบ search_web แยกเดี่ยว ไม่เรียก search API จริง และไม่มี model เกี่ยว: ใช้ patch สลับ search_api เป็น mock เฉพาะใน test

  • happy path: mock คืนผลหนึ่งรายการ → ผลอยู่ในคำตอบ และ API ถูกเรียกครั้งเดียวด้วย num_results=5
  • edge case: query ว่าง → ValueError
  • error case: API ล่ม (ConnectionError) → tool ไม่พัง แต่คืนข้อความ error
  • retry: ครั้งแรก RateLimitError ครั้งที่สองผ่าน → API ถูกเรียกสองครั้ง

ใน notebook ฟังก์ชันของเราอยู่ใน module ชื่อ __main__ จึง patch ที่ "__main__.search_api" (ตำรา patch ที่ "myagent.tools.search_api")

%%ipytest

class TestSearchWebTool:
    def test_basic_search_returns_results(self):
        with patch("__main__.search_api") as mock_api:
            mock_api.return_value = {"results": [{"title": "Test", "url": "http://example.com"}]}
            result = search_web("test query")
            assert "Test" in result
            mock_api.assert_called_once_with(query="test query", num_results=5)

    def test_empty_query_raises_value_error(self):
        with pytest.raises(ValueError, match="Query cannot be empty"):
            search_web("")

    # ✏️ TODO 1 (▶ วิดีโอ 4:26): ให้ search_api ปลอมโยน ConnectionError("API down") แทนการคืนผล

    def test_api_failure_returns_error_message(self):
        with patch("__main__.search_api", side_effect=___):
            result = search_web("test query")
            assert "error" in result.lower()
            assert "API down" in result

    # ✏️ TODO 2 (▶ วิดีโอ 4:41): ตรวจว่า search_api ถูกเรียกสองครั้ง (ลองใหม่หนึ่งครั้ง)

    def test_rate_limit_triggers_retry(self):
        with patch("__main__.search_api") as mock_api:
            mock_api.side_effect = [RateLimitError(), {"results": []}]
            search_web("test query")
            assert ___  # retried once
%%ipytest

class TestSearchWebTool:
    def test_basic_search_returns_results(self):
        with patch("__main__.search_api") as mock_api:
            mock_api.return_value = {"results": [{"title": "Test", "url": "http://example.com"}]}
            result = search_web("test query")
            assert "Test" in result
            mock_api.assert_called_once_with(query="test query", num_results=5)

    def test_empty_query_raises_value_error(self):
        with pytest.raises(ValueError, match="Query cannot be empty"):
            search_web("")

    def test_api_failure_returns_error_message(self):
        with patch("__main__.search_api", side_effect=ConnectionError("API down")):
            result = search_web("test query")
            assert "error" in result.lower()
            assert "API down" in result

    def test_rate_limit_triggers_retry(self):
        with patch("__main__.search_api") as mock_api:
            mock_api.side_effect = [RateLimitError(), {"results": []}]
            search_web("test query")
            assert mock_api.call_count == 2  # retried once
....                                                                                         [100%]
4 passed in 0.51s

3. Component test — ตัวเรียก tool ของ agent

ชั้นถัดขึ้นมา (Figure 25.4: component tests) ทดสอบส่วนประกอบของ agent ที่ใหญ่กว่า tool หนึ่งตัว แต่ยังไม่ต้องใช้ model: run_tool รับ tool call ที่ model ส่งมา → หา tool ตามชื่อ → แปลง arguments จาก JSON → เรียก tool ถ้าพังตรงไหน ต้องคืน ข้อความ error ให้ model อ่าน ไม่ใช่โยน exception จน agent ล่มทั้งตัว

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"
    # ✏️ TODO 3 (▶ วิดีโอ 5:48): เรียก tool ถ้า tool โยน error ให้คืนเป็นข้อความ Error: <ชนิด>: <ข้อความ>
    try:
        return ___
    except Exception as e:
        return ___
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}"
%%ipytest

def fake_call(name, arguments):
    return SimpleNamespace(function=SimpleNamespace(name=name, arguments=arguments))

def test_unknown_tool_returns_error():
    assert run_tool(TOOLS, fake_call("send_email", "{}")).startswith("Error: unknown tool")

def test_broken_json_returns_error():
    assert "not valid JSON" in run_tool(TOOLS, fake_call("search_web", '{"query": '))

def test_tool_exception_becomes_text():
    out = run_tool(TOOLS, fake_call("search_web", '{"query": ""}'))
    assert out == "Error: ValueError: Query cannot be empty"
...                                                                                          [100%]
3 passed in 0.00s

4. Research agent

agent loop แบบเดียวกับ EP ก่อนๆ แต่เก็บ trajectory: ทุก tool call พร้อม input และผล run(task) คืน Result(status, final_answer, trajectory, tokens) แบบที่ test ในตำราอ่าน มีสองจุดที่ตั้งใจเปิดไว้ให้ต่อยอด: schemas() (tool ที่ส่งให้ model) และ observe() (ผลของ tool ก่อนส่งกลับ) — จะได้ใช้ในข้อ 6

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 Step:
    tool: str
    tool_input: dict
    output: str

@dataclass
class Result:
    status: str
    final_answer: str
    trajectory: list
    tokens: int
class ResearchAgent:
    def __init__(self, tools=TOOLS, max_steps=8):
        self.tools, self.max_steps = tools, max_steps

    def schemas(self):
        return TOOL_SCHEMAS

    def observe(self, name, out):
        return out

    def run(self, task):
        messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": task}]
        trajectory, tokens = [], 0
        for _ in range(self.max_steps):
            r = chat(messages, self.schemas())
            tokens += r.usage.total_tokens
            msg = r.choices[0].message
            if not msg.tool_calls:
                return Result("done", msg.content or "", trajectory, tokens)
            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:
                out = self.observe(call.function.name, run_tool(self.tools, call))
                trajectory.append(Step(call.function.name, parse_args(call) or {}, out))
                messages.append({"role": "tool", "tool_call_id": call.id, "content": out})
        return Result("max_steps", "", trajectory, tokens)

5. Integration test — model จริง tool ปลอม (Listing 25.14)

MockToolSet แทน tool ทั้งสามด้วยฟังก์ชันที่คืนข้อความตายตัว (ตามตำรา) นับจำนวนครั้งที่ถูกเรียก และ set_failure(name, after_calls) ทำให้ tool พังหลังเรียกไป after_calls ครั้ง

test สามตัวของตำรา: งานจบ · ค้นก่อนเขียน · รอดเมื่อ tool พัง model เป็นของจริง ผลจึงไม่เหมือนกันทุกรอบ → รันแต่ละ test 5 รอบ ด้วย parametrize แล้วนับว่าผ่านกี่รอบ

สองจุดที่ต่างจากตำรา: (1) ตำราใช้งาน "Research a topic" ซึ่ง agent ของเราตอบกลับมาถามว่าหัวข้ออะไร แล้วไม่ค้นเลย → test ผ่านทั้งที่ tool ไม่เคยพัง เราจึงใช้งานจริงหนึ่งงาน และเพิ่ม assert ว่าความพังเกิดขึ้นจริง (2) ตำราตั้ง after_calls=2 แต่ agent ของเราค้นแค่หนึ่งถึงสองครั้ง จึงใช้ after_calls=1

class MockToolSet(dict):
    def __init__(self, fns):
        super().__init__()
        self.calls = {name: 0 for name in fns}
        self.fail_after = {}
        for name, fn in fns.items():
            self[name] = self._wrap(name, fn)

    def _wrap(self, name, fn):
        def tool(**kwargs):
            self.calls[name] += 1
            if name in self.fail_after and self.calls[name] > self.fail_after[name]:
                raise ConnectionError(f"{name} is down")
            return fn(**kwargs)
        return tool

    def set_failure(self, name, after_calls):
        self.fail_after[name] = after_calls

def make_tools():
    return MockToolSet({
        "search_web": lambda query: f"Results for: {query}\n- An overview — https://example.org/overview",
        "read_document": lambda url: f"Document content here (from {url}).",
        "write_report": lambda title, content: "Report saved",
    })
%%ipytest --tb=no

RUNS = range(5)
TASK = "Research the history of reinforcement learning"

@pytest.mark.parametrize("run", RUNS)
def test_completes_research_task(run):
    result = ResearchAgent(tools=make_tools()).run(TASK)
    assert result.status == "done"
    assert result.final_answer
    assert len(result.trajectory) > 0

# ✏️ TODO 4 (▶ วิดีโอ 9:25): ตรวจว่าตำแหน่งที่ค้นมาก่อนตำแหน่งที่เขียน

@pytest.mark.parametrize("run", RUNS)
def test_uses_search_before_writing(run):
    result = ResearchAgent(tools=make_tools()).run(TASK)
    tool_calls = [step.tool for step in result.trajectory]
    search_idx = next(i for i, t in enumerate(tool_calls) if "search" in t)
    write_idx = next(i for i, t in enumerate(tool_calls) if "write" in t)
    assert ___, "Agent should search before writing"

# ✏️ TODO 5 (▶ วิดีโอ 9:40): ตั้งให้ search_web พังหลังเรียกไปหนึ่งครั้ง

@pytest.mark.parametrize("run", RUNS)
def test_handles_tool_failure_gracefully(run):
    tools = make_tools()
    ___
    result = ResearchAgent(tools=tools).run(TASK)
    assert tools.calls["search_web"] > 1, "the failure never happened"
    assert result.status in ("done", "partial")
    assert "error" not in result.final_answer.lower()
%%ipytest --tb=no

RUNS = range(5)
TASK = "Research the history of reinforcement learning"

@pytest.mark.parametrize("run", RUNS)
def test_completes_research_task(run):
    result = ResearchAgent(tools=make_tools()).run(TASK)
    assert result.status == "done"
    assert result.final_answer
    assert len(result.trajectory) > 0

@pytest.mark.parametrize("run", RUNS)
def test_uses_search_before_writing(run):
    result = ResearchAgent(tools=make_tools()).run(TASK)
    tool_calls = [step.tool for step in result.trajectory]
    search_idx = next(i for i, t in enumerate(tool_calls) if "search" in t)
    write_idx = next(i for i, t in enumerate(tool_calls) if "write" in t)
    assert search_idx < write_idx, "Agent should search before writing"

@pytest.mark.parametrize("run", RUNS)
def test_handles_tool_failure_gracefully(run):
    tools = make_tools()
    tools.set_failure("search_web", after_calls=1)
    result = ResearchAgent(tools=tools).run(TASK)
    assert tools.calls["search_web"] > 1, "the failure never happened"
    assert result.status in ("done", "partial")
    assert "error" not in result.final_answer.lower()
..........FFFFF                                                                              [100%]
===================================== short test summary info ======================================
FAILED t_7baeb94abd8a439ca9b84ecb46eaff60.py::test_handles_tool_failure_gracefully[0] - Assertion...
FAILED t_7baeb94abd8a439ca9b84ecb46eaff60.py::test_handles_tool_failure_gracefully[1] - Assertion...
FAILED t_7baeb94abd8a439ca9b84ecb46eaff60.py::test_handles_tool_failure_gracefully[2] - Assertion...
FAILED t_7baeb94abd8a439ca9b84ecb46eaff60.py::test_handles_tool_failure_gracefully[3] - Assertion...
FAILED t_7baeb94abd8a439ca9b84ecb46eaff60.py::test_handles_tool_failure_gracefully[4] - Assertion...
5 failed, 10 passed in 70.38s (0:01:10)
tools = make_tools()
tools.set_failure("search_web", after_calls=1)
result = ResearchAgent(tools=tools).run(TASK)
print(result.status, tools.calls)
for i, step in enumerate(result.trajectory):
    print(i, step.tool, step.tool_input, "→", step.output[:60])
max_steps {'search_web': 8, 'read_document': 0, 'write_report': 0}
0 search_web {'query': 'history of reinforcement learning timeline'} → Results for: history of reinforcement learning timeline
- An
1 search_web {'query': 'history of reinforcement learning key milestones and figures'} → Error: ConnectionError: search_web is down
2 search_web {'query': 'history of reinforcement learning key milestones and figures'} → Error: ConnectionError: search_web is down
3 search_web {'query': 'history of reinforcement learning key milestones and figures'} → Error: ConnectionError: search_web is down
4 search_web {'query': 'history of reinforcement learning key milestones and figures'} → Error: ConnectionError: search_web is down
5 search_web {'query': 'history of reinforcement learning key milestones and figures'} → Error: ConnectionError: search_web is down
6 search_web {'query': 'history of reinforcement learning key milestones and figures'} → Error: ConnectionError: search_web is down
7 search_web {'query': 'history of reinforcement learning key milestones and figures'} → Error: ConnectionError: search_web is down

6. แก้ bug: circuit breaker

Table 25.1 ของตำรา: tool error → แก้ด้วย retry logic, fallback · infinite loop → แก้ด้วย hard limits, loop-breaking prompts ResearchAgentV2 ใช้สองจุดที่เปิดไว้:

  • observe(): tool ตัวไหนพัง สองครั้ง → ปิดมันไว้ แล้วต่อท้ายผลว่า “ใช้ของที่มีอยู่ทำต่อ” (loop-breaking prompt)
  • schemas(): ไม่ส่ง tool ที่ปิดแล้วให้ model อีก (hard limit)
class ResearchAgentV2(ResearchAgent):
    def run(self, task):
        self.failures, self.down = {}, set()
        return super().run(task)

    def schemas(self):
        return [s for s in TOOL_SCHEMAS if s["function"]["name"] not in self.down]

    # ✏️ TODO 6 (▶ วิดีโอ 11:19): tool ที่พังครบสองครั้ง: เพิ่มชื่อเข้า 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:
                ___
                out += f"\n{name} is down for this task. Continue with what you already have."
        return out
class ResearchAgentV2(ResearchAgent):
    def run(self, task):
        self.failures, self.down = {}, set()
        return super().run(task)

    def schemas(self):
        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 out
%%ipytest --tb=no

@pytest.mark.parametrize("run", RUNS)
def test_v2_handles_tool_failure_gracefully(run):
    tools = make_tools()
    tools.set_failure("search_web", after_calls=1)
    result = ResearchAgentV2(tools=tools).run(TASK)
    assert tools.calls["search_web"] > 1, "the failure never happened"
    assert result.status in ("done", "partial")
    assert "error" not in result.final_answer.lower()
.....                                                                                        [100%]
5 passed in 26.53s

7. End-to-end — ยอดพีระมิด

ไม่มีของปลอม: tool จริงทั้งสาม (บนข้อมูลค้นหาจำลอง) และ model จริง หนึ่งงาน ตรวจผลที่ผู้ใช้สนใจจริง: รายงานถูกบันทึก และ อ้าง URL ที่ agent อ่านมาจริง

%%ipytest -s

def test_end_to_end_report_cites_what_it_read():
    REPORTS.clear()
    result = ResearchAgentV2().run("Research transformers for time-series forecasting")
    print([step.tool for step in result.trajectory])
    read = {step.tool_input.get("url") for step in result.trajectory if step.tool == "read_document"}
    assert result.status == "done" and REPORTS
    report = next(iter(REPORTS.values()))
    assert any(url in report for url in read), "the report cites nothing it read"
['search_web', 'read_document', 'search_web', 'read_document', 'write_report']
.
1 passed in 4.81s
print(f"Cost of this lab: USD {COST['chat']:.4f}")
Cost of this lab: USD 0.0083

สรุป

ชั้น (Figure 25.4) ในแล็บนี้ model เวลา
unit search_web + mock: ผลปกติ · query ว่าง · API ล่ม · rate limit (Listing 25.13) ไม่ใช้ ไม่ถึงวินาที
component run_tool: tool ไม่มีจริง · JSON เสีย · tool โยน error ไม่ใช้ ไม่ถึงวินาที
integration agent จริง + MockToolSet × 5 รอบ: งานจบ · ค้นก่อนเขียน · รอดเมื่อ tool พัง (Listing 25.14) ใช้ เป็นนาที
end-to-end tool จริง + model จริง: รายงานอ้าง URL ที่อ่าน ใช้ หลายวินาทีต่อ test
  • integration test จับ ลูกโซ่ tool error → infinite loop ได้ → แก้ด้วย circuit breaker (ResearchAgentV2)
  • test ที่มี model จริงอยู่ข้างในอาจ flaky → รันซ้ำแล้วนับ ไม่ใช่รันครั้งเดียวแล้วเชื่อ
  • test ที่ผ่านอาจผ่าน เพราะไม่ได้ทดสอบอะไรเลย → ตรวจว่าเงื่อนไขที่ต้องการเกิดขึ้นจริง

แบบฝึกหัด

  1. เพิ่ม unit test ของ read_document: URL ที่ไม่มีต้องได้ข้อความ error
  2. ลอง set_failure("search_web", after_calls=0) (ค้นไม่ได้เลย) กับ ResearchAgentV2 — agent ทำอะไร test ของตำรายังผ่านไหม และควรผ่านไหม
  3. เขียน assert ใหม่แทน "error" not in final_answer ที่ยอมให้ agent บอกผู้ใช้ตรงๆ ว่าค้นไม่ได้

ถัดไป — Lab 2: golden trajectory · behavioral test · ด่านเงินและเวลา