devHọc Dev

Week 2 - Day 6: Building Agents: Tool Loop, Tool Design, Evals, Observability and Debugging

Week 2 – Day 6

This lesson combines 4 topics: When you need an agent and four ways to build the loop, Designing tools for agents, Evals: measuring output quality, Observing and debugging agents.

Learning Objectives

  • Decide when you need an agent and when a single call or a fixed workflow is enough
  • Compare 4 ways to build an agent: hand-written loop, Tool Runner, Agent SDK, Managed Agents
  • Write a small agent with the Agent SDK (TypeScript or Python) using least privilege
  • Design good tools: name, description, schema, compact output, actionable errors, idempotency
  • Know the tool design mistakes that make agents call the wrong tool, loop forever or waste context
  • Build an eval suite: dataset, grading method (code, LLM-as-judge, human), metrics
  • Write an eval script that compares two configurations (model, effort, prompt) on quality and cost
  • Know the eval pitfalls: data that is too easy, a biased judge, overfitting to the test set
  • Log and trace enough to debug a failed agent run
  • Recognize and handle common agent failure modes

Part 1: When you need an agent and four ways to build the loop

1. Three levels: single call, workflow, agent

LevelWho decides the next stepExampleProsCons
Single callThere is no next stepClassify a ticket, summarize, extractCheap, fast, easy to testCannot handle multi-step work
WorkflowYour code, following a fixed flowExtract → validate → translate → savePredictable, easy to debugRigid with unusual situations
AgentThe model, inside a tool loop"Find why the test fails and fix it"Flexible for open-ended workMore expensive, slower, less predictable, harder to test

Start simple: most features only need a single call or a workflow. Move up to an agent only when the task genuinely requires the model to explore on its own.

Four questions before building an agent:

  1. Complexity: does the task have many steps that are hard to specify up front? ("turn a design doc into a PR" does; "get the title from a PDF" does not)
  2. Value: is the result worth the higher cost and latency?
  3. Feasibility: is Claude good at this kind of task? (try it by hand first with Claude Code)
  4. Cost of errors: can mistakes be detected and recovered from? (tests, review, rollback)

A single "no" is a signal to stay at a simpler level.

2. The agent loop

┌───────────────────────────────────────────┐│messages=[system,usertask]│└─────────────────────┬─────────────────────┘▼┌───────────────────────────────────────────┐┌───▶│callmodelwithtools││└─────────────────────┬─────────────────────┘│▼│stop_reason==tool_use?│├──no──▶returnfinalanswer│▼yes│┌───────────────────────────────────────────┐││checkpermission/approval│││runtools(inparallelifindependent)│││appendtool_resultblocks(onemessage)││└─────────────────────┬─────────────────────┘│▼│turnlimit/budgetreached?└────────no──────────────┤└──yes──▶stop,reportpartialresult

Every agent, however it is built, needs three things beyond the loop: a stop condition (number of turns, token or money budget), permission control (which tools need approval), and logging of every turn.

3. Four ways to build

ApproachWhat you writeWho runs the loopBuilt-in toolsFits when
Hand-written loop (Messages API)A while stop_reason == "tool_use" loopYouOnly the tools you defineYou need full control, a specialized flow
Tool Runner (beta, in the API SDK)Only the tool functionsThe SDKOnly the tools you defineAgent with custom tools, without writing the loop yourself
Agent SDKPrompt + optionsA library running the Claude Code engineRead, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch, MCP, subagentsAgents working with files and commands on your infrastructure
Managed Agents (beta)Agent configuration via the APIAnthropic runs the loop and the sandboxAnthropic-hosted sandbox (bash, files, code) + MCP + your toolsYou want Anthropic to host both the loop and the runtime environment

A note on naming: Tool Runner belongs to the API SDK (@anthropic-ai/sdk, anthropic); the Agent SDK is a separate package (@anthropic-ai/claude-agent-sdk, claude-agent-sdk), essentially Claude Code packaged as a library. They are two different things.

Day 5 already had a hand-written loop example. Below is the Agent SDK.

4. Agent SDK: example

Installation (per the Agent SDK quickstart, as of 11/2026; requires Node.js 18.14+ or Python 3.10+):

# TypeScript
npm install @anthropic-ai/claude-agent-sdk

# Python
pip install claude-agent-sdk

The Agent SDK uses an API key (ANTHROPIC_API_KEY), or Bedrock, Google Cloud, Foundry via environment variables. Notes from the docs: the SDK does not read .env files automatically; and unless approved by Anthropic, third-party products may not let users sign in with a claude.ai account.

A read-only dependency review agent for acme-shop:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt:
    "Read package.json and pnpm-lock.yaml. List direct dependencies that are not used " +
    "in src/ (search with Grep). Do not modify any file. Return the list with evidence.",
  options: {
    allowedTools: ["Read", "Glob", "Grep"], // auto-approve the read tools
    permissionMode: "dontAsk", // tools not in the list are denied, not prompted
    systemPrompt: "You are a dependency reviewer. Only report what has evidence in the repo.",
  },
})) {
  if (message.type === "assistant" && message.message?.content) {
    for (const block of message.message.content) {
      if ("text" in block) console.log(block.text);
      else if ("name" in block) console.log(`Tool: ${block.name}`);
    }
  } else if (message.type === "result") {
    console.log(`Done: ${message.subtype}`);
  }
}

The Python equivalent:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage


async def main():
    async for message in query(
        prompt=(
            "Read package.json and pnpm-lock.yaml. List direct dependencies that are not used "
            "in src/ (search with Grep). Do not modify any file."
        ),
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Glob", "Grep"],
            permission_mode="dontAsk",
        ),
    ):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if hasattr(block, "text"):
                    print(block.text)
        elif isinstance(message, ResultMessage):
            print(f"Done: {message.subtype}")


asyncio.run(main())

Points to note:

  • allowedTools is only the list of auto-approved tools, not the only tools that may be used: a tool not on the list falls through to the permission mode (and runs if the mode is bypassPermissions). For a read-only agent, combine it with permissionMode: "dontAsk" (deny everything not approved) or list disallowedTools: ["Edit", "Write", "Bash"]. This is the real fence, more important than any instruction in the prompt.
  • permissionMode (for example "acceptEdits") allows editing files without asking; only enable it when the agent runs in an environment where you can accept changes (a separate branch, a container).
  • The Agent SDK automatically loads skills, commands and CLAUDE.md from the project's .claude/ and ~/.claude/ like Claude Code does (depending on the settings source configuration). When running on an untrusted repo, control the configuration sources as covered on Day 3.
  • The last message has type: "result"; with the headless CLI, the JSON output has total_cost_usd, a client-side cost estimate that may differ from the actual bill.

Part 2: Designing tools for agents

1. A tool is an interface for the model

The model only knows a tool through its name, description, schema and output. Poorly designed tools are the leading cause of agents calling the wrong tool, passing wrong parameters, or looping uselessly. Design tools the way you would design an API for a new developer: clear and hard to misuse.

2. Name, description, schema

A poor description:

{
  "name": "search",
  "description": "Search",
  "input_schema": {
    "type": "object",
    "properties": { "q": { "type": "string" }, "t": { "type": "string" } }
  }
}

A good description:

{
  "name": "search_orders",
  "description": "Search acme-shop orders by customer email or order ID. Use it when you need to identify an order before checking its status or issuing a refund. Returns at most the 20 most recent orders, each with order_id, status, total_vnd, created_at. Does not return payment information.",
  "strict": true,
  "input_schema": {
    "type": "object",
    "properties": {
      "customer_email": { "type": "string", "description": "Customer email, for example an@example.com" },
      "order_id": { "type": "string", "description": "Order ID in the form A1234; leave empty when searching by email" },
      "status": { "type": "string", "enum": ["pending", "paid", "shipping", "delivered", "cancelled"] }
    },
    "required": ["customer_email"],
    "additionalProperties": false
  }
}

Principles:

PrincipleWhy
Names have a verb and an object (search_orders, refund_order)The model picks the right tool when there are many
The description says: what it does, when to use it, what it returns, what its limits areThe model decides whether to call a tool based on its description
Parameters have meaningful names and format examplesFewer wrongly formatted inputs
Use enum for finite value setsNo more mixing "Shipping", "shipped", "in transit"
strict: true + additionalProperties: false + requiredInput always matches the schema
The description states whether the tool has side effectsThe model is more careful with write tools

3. Tool output

Tool output goes straight into the context. Poor output wastes the agent's tokens and confuses it.

ProblemExampleBetter approach
Returning too muchDumping a whole 5,000-row tablePaginate, limit rows, offer filter parameters
Returning cryptic IDs{"u": "8f3a...", "s": 3}Return meaningful fields: customer_name, status: "shipping"
Vague errorsError: 400Order A12 not found. Order IDs look like A + 4 digits; try search_orders by email.
Silent when empty[]No orders match the email an@example.com in the last 12 months.
Unneeded sensitive dataCard numbers, tokensFilter at the tool layer; the model does not need to see it

Actionable errors are a powerful trick: when a tool returns an error with a hint on how to fix it, the model usually corrects itself on the next turn instead of repeating the same wrong call. Return errors as a tool_result with is_error: true.

4. Tools with side effects

MeasureDescription
Separate reads and writesget_order and refund_order are two tools, not merged into manage_order(action)
Confirmation outside the modelImportant write tools (refunds, deletion, sending email) need approval by a human or by business rules in code, not just the model's judgment
Idempotency keyThe agent may call the same tool again after a network error; refund_order takes an idempotency_key so it never refunds twice
Limits inside the toolThe refund tool itself rejects amounts above a threshold, no matter what the model asks
Least privilegeThe tool's credentials are only enough for that tool's job

Principle: business and security rules must live in the tool's code, not only in the prompt. A prompt can be misunderstood or hit by prompt injection; code cannot.

5. Number and granularity of tools

  • Too many tools (a few dozen or more): tool definitions take up context on every request, and the model picks the wrong one more often. Merge duplicate tools, or use the tool search mechanism to load tools on demand (see the tool use docs).
  • Tools that are too fine-grained: get_user, get_user_address, get_user_phone... force the agent into many turns. Merge them into one tool that returns enough information.
  • Tools that are too broad: run_sql(query) gives the agent full database access. Replace it with narrow business tools, or at least a read-only account limited to specific tables.

Part 3: Evals: measuring output quality

1. Why you need evals

Without evals, every change to the prompt, model or effort is a guess: "tried it 3 times, seems better". LLMs are non-deterministic, so a few tries tell you nothing. An eval is a test suite for model behavior: a fixed set of inputs, a grading method, and a number to compare.

┌──────────────┐┌──────────────┐┌──────────────┐┌──────────────┐│Dataset│───▶│RunconfigA│───▶│Grade│───▶│Report││inputs+││andconfigB││code/judge││score,cost,││expectations││(model,││/human││latency,││││effort,││││failures││││prompt)│││││└──────────────┘└──────────────┘└──────────────┘└──────────────┘

2. Building the dataset

SourceProsNotes
Real data (tickets, logs, user questions)Reflects the true distributionAnonymize PII before adding it to the eval set
Hand-written edge casesCatches rare but serious bugsDo not use only edge cases, or the distribution will be skewed
Bugs seen in productionPrevents regressionsEvery important bug becomes an eval case
Synthetic data generated by a modelFast, plentifulTends to be too uniform and too easy; must be reviewed

Start small: 30–100 well-labeled cases are worth more than 5,000 sloppily labeled ones. Set aside part of it as a final test set that is not used while tuning the prompt, to avoid overfitting.

3. Grading methods

Grading methodFitsExampleCons
Code (matching, regex, running tests)Output with a clear answerClassification labels, schema-valid JSON, code that passes testsCannot grade the quality of prose
LLM-as-judgeOpen-ended output with a rubricDoes a support answer follow the policy, is it polite enoughThe judge can be biased; needs validation against humans
HumanDefining "good" the first time, validating the judgeReviewing 50 cases to calibrate the rubricSlow, expensive

Prefer code-based grading whenever possible; use LLM-as-judge for the rest; use humans to calibrate and periodically check the judge.

4. Eval script: ticket classification

Continuing the Day 5 exercise. Each line of the file eval/tickets.jsonl is: {"text": "...", "expected": "billing"}.

import json
import time
import anthropic

client = anthropic.Anthropic()

SCHEMA = {
    "type": "object",
    "properties": {
        "category": {"type": "string", "enum": ["billing", "shipping", "account", "product", "other"]}
    },
    "required": ["category"],
    "additionalProperties": False,
}

# Prices in USD/MTok (as of 11/2026, source: the Pricing page). Update when prices change.
PRICES = {
    "claude-opus-5-5": (4.00, 20.00),
    "claude-haiku-5-5": (0.10, 0.50),  # prompt <= 100K tokens
}


def classify(text: str, model: str, effort: str) -> tuple[str | None, anthropic.types.Usage]:
    response = client.messages.create(
        model=model,
        max_tokens=2000,
        system="Classify an acme-shop support ticket into exactly one category.",
        messages=[{"role": "user", "content": f"<ticket>\n{text}\n</ticket>"}],
        output_config={"effort": effort, "format": {"type": "json_schema", "schema": SCHEMA}},
    )
    if response.stop_reason != "end_turn":
        return None, response.usage
    text_block = next(b for b in response.content if b.type == "text")
    return json.loads(text_block.text)["category"], response.usage


def run(model: str, effort: str, cases: list[dict]) -> None:
    correct, cost, failures = 0, 0.0, []
    started = time.time()
    in_price, out_price = PRICES[model]
    for case in cases:
        predicted, usage = classify(case["text"], model, effort)
        cost += usage.input_tokens / 1e6 * in_price + usage.output_tokens / 1e6 * out_price
        if predicted == case["expected"]:
            correct += 1
        else:
            failures.append({"text": case["text"][:80], "expected": case["expected"], "got": predicted})
    print(f"{model} effort={effort}: accuracy={correct / len(cases):.1%} "
          f"cost=${cost:.4f} time={time.time() - started:.0f}s")
    for f in failures[:10]:
        print("  FAIL", f)


cases = [json.loads(line) for line in open("eval/tickets.jsonl", encoding="utf-8")]
run("claude-haiku-5-5", "low", cases)
run("claude-opus-5-5", "low", cases)

Results like this let you decide with data: "Haiku 5.5 at effort low reaches 94%, Opus 5.5 reaches 96% but costs ~40 times more; the 2 percentage point gap lies in tickets with multiple issues → add examples to the prompt and measure again". The cost calculation here is an estimate (caching not included); see the Console for exact numbers.

5. LLM-as-judge

For open-ended output (answers to customers), write a specific rubric and have the judge return a structured result:

JUDGE_SCHEMA = {
    "type": "object",
    "properties": {
        "follows_policy": {"type": "boolean"},
        "answers_question": {"type": "boolean"},
        "invents_facts": {"type": "boolean"},
        "reason": {"type": "string"},
    },
    "required": ["follows_policy", "answers_question", "invents_facts", "reason"],
    "additionalProperties": False,
}

def judge(question: str, answer: str, policy: str) -> dict:
    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=4000,
        system=(
            "You grade customer support answers against a rubric. Rely only on the provided policy. "
            "invents_facts = true if the answer states information that is not in the policy or the question."
        ),
        messages=[{
            "role": "user",
            "content": f"<policy>\n{policy}\n</policy>\n<question>\n{question}\n</question>\n<answer>\n{answer}\n</answer>",
        }],
        output_config={"format": {"type": "json_schema", "schema": JUDGE_SCHEMA}},
    )
    return json.loads(next(b.text for b in response.content if b.type == "text"))

Good practices for LLM-as-judge:

  • Binary, specific criteria ("does it invent information?") are more reliable than a vague 1–10 scale.
  • Require a reason so you can check the judge.
  • Calibrate against humans: grade 30–50 cases by hand and measure the agreement rate between judge and human before trusting the judge.
  • Separate the judge from the system being graded: a different prompt, and consider a different model, to reduce self-preference bias.
  • Do not show the judge "configuration A/B answer" labels; shuffle the order when comparing two outputs.

6. Eval pitfalls

PitfallSymptomHow to avoid
Eval set too easyEvery configuration scores 99%Add hard cases, edge cases, production bugs
OverfittingScore rises on the tuning set but drops on new dataKeep a separate final test set
Running once and concludingA 1–2% gap between two configurationsRun repeatedly and look at the variance before concluding
Measuring only qualityPicking the best configuration that costs 10 times moreReport cost and latency too
Unvalidated judgeHigh judge scores, users still complainCalibrate the judge against humans periodically

Part 4: Observing and debugging agents

1. What to log for each agent run

LevelDataUsed for
RunTask, configuration (model, effort, tools, prompt version), result, total tokens, cost, duration, number of turnsComparison, tracking cost per task
Each turnstop_reason, usage, request ID, latencyDetecting truncated output, refusals, unusual token growth
Each tool callName, input, output (trimmed), errors, durationSeeing where the agent calls the wrong tool, loops, or is slow
Full transcriptAll messagesReplay to reproduce

Saving the transcript is the most important part: without a transcript you cannot debug an agent, because its behavior cannot be reproduced by running it again.

For larger systems, the Claude SDKs support OpenTelemetry-based tracing to send each request's spans into your existing observability stack (see the OpenTelemetry docs). With the Agent SDK and claude -p, the final result message includes estimated cost and the session ID.

2. Common failure modes

SymptomCommon causeFix
Calls the same tool with the same input many timesTool output gives no new information; errors have no guidanceErrors with hints; detect loops in code and stop
Calls the wrong toolOverlapping tool descriptions, vague namesRewrite descriptions, state clearly when to use each, merge duplicate tools
Wrongly formatted parametersLoose schema, no examplesenum, strict: true, describe the format
Context fills up midwayTools return too much dataPaginate, trim output, delegate heavy reading to a subagent
Stops early, reports "done" when it is notNo verifiable completion criteriaGive it a verification tool (running tests), state completion criteria in the prompt
Goes beyond scopeVague prompt, overly powerful toolsClear constraints, least privilege
Runs forever, high costNo turn or budget limitTurn limit, budget, timeout
stop_reason: refusalThe request hit a safety filterRead stop_details, review the request; treat it as a valid outcome, do not retry blindly

3. Debugging a failed run

  1. Get the transcript of the run (do not rerun right away; the next run may differ).
  2. Find the first turn that went wrong: did the model misunderstand the request? Call the wrong tool? Did the tool return wrong data? The root cause is often a few turns before where it surfaces.
  3. Classify: a prompt bug, a tool design bug, a tool data bug, or a model limitation.
  4. Fix at the right layer: if the tool returns wrong data, fix the tool; do not add an instruction to the prompt to "compensate".
  5. Add this case to the eval set so it does not recur, and rerun the evals to make sure fixing this did not break something else.

A useful trick: give the transcript to Claude (on claude.ai or in Claude Code) and ask "At which turn did the agent start going wrong and why? Suggest changes to the tool descriptions or the prompt." Claude reads long transcripts faster than you, but you still decide what to change.


Review Questions

  1. Distinguish a single call, a workflow and an agent. Give an example of each in an e-commerce shop.

    Show answer

    Single call: one request, one result, for example classifying a ticket. Workflow: code drives a fixed sequence of steps, each of which may call the model, for example extracting product information from a supplier file → validate → translate the description → save to the DB. Agent: the model decides the next step inside a tool loop, for example an operations assistant that looks up logs and orders on its own and proposes the cause of an incident. Start at the simplest level that meets the requirement.

  2. Which four questions should you answer before building an agent?

    Show answer

    Complexity (does the task have many steps that are hard to specify up front), value (is the result worth the cost and latency), feasibility (is Claude good at this kind of task), cost of errors (can mistakes be detected and recovered from). A single "no" is a signal to stay at the workflow or single-call level.

  3. How do Tool Runner and the Agent SDK differ?

    Show answer

    Tool Runner is a helper (beta) in the API SDK (@anthropic-ai/sdk, anthropic): it runs the loop of calling the model → running your tools → sending back the results. It has no built-in tools. The Agent SDK is a separate package (@anthropic-ai/claude-agent-sdk, claude-agent-sdk) that packages the Claude Code engine: built-in tools for reading/editing files, Bash, search, web, plus hooks, subagents, permissions, sessions. You host both; Managed Agents is the option where Anthropic hosts both the loop and the sandbox.

  4. A dependency review agent only needs to read. How do you configure the Agent SDK safely?

    Show answer

    allowedTools contains only Read, Glob, Grep, together with permissionMode: "dontAsk" (or disallowedTools for Edit, Write, Bash) so that tools outside the list are denied instead of falling through to another mode; do not use a mode that allows edits. Run with an API key that has a spend limit, on a checkout that contains no secrets. If running on an untrusted repo, control the configuration sources so hooks or MCP servers are not loaded from the repo. Least privilege is the real fence; the "do not modify files" sentence in the prompt is only an extra layer.

  5. Rewrite the tool description {"name": "search", "description": "Search"} to be better and explain each change.

    Show answer

    Rename it to verb + object (search_orders); the description says what it does, when to use it, which fields it returns, how many results at most, and that it returns nothing sensitive; parameters have clear names, a format description, an enum for status; add required, additionalProperties: false, strict: true. Each change helps the model pick the right tool and pass the right parameters.

  6. Why should tool errors include a hint on how to fix them? Give an example.

    Show answer

    The model reads the error output to decide its next turn. "Error: 400" gives no information, so the model often retries the exact same call or gives up. "Order A12 not found. Order IDs look like A + 4 digits; try search_orders by email" helps the model correct itself on the next turn. Return it via tool_result with is_error: true.

  7. What measures beyond the prompt does a refund_order tool need?

    Show answer

    Separate it from read tools; confirmation outside the model (human approval or business rules in code); an idempotency key so a retry after a network error does not refund twice; an amount limit in the tool's code; credentials only allowed to issue refunds; complete logging. Business rules live in the tool because a prompt can be misunderstood or hit by prompt injection.

  8. An agent has 60 tools from several MCP servers and often picks the wrong one. How do you fix it?

    Show answer

    Tool definitions take up context, and many overlapping tools make the model pick wrongly. Disable servers not needed for this task; merge duplicate tools; rewrite descriptions to make it clear when to use each; use the tool search mechanism to load tools on demand; or split the work across several specialized subagents, each with few tools.

  9. Why is "tried it 3 times, the new prompt seems better" not evidence?

    Show answer

    Output is non-deterministic, 3 runs are far too few to tell a real improvement from random variation, and the 3 test cases are usually ones you thought of, not representative of the real distribution. You need a fixed, large enough eval set, consistent grading, and a comparison of quality, cost and latency together.

  10. When should you grade with code, and when with LLM-as-judge?

Show answer

Grade with code when the output has a clear answer: classification labels, schema-valid JSON, extracted values, code that passes tests. Use LLM-as-judge when open-ended output must be assessed against a rubric: does the answer follow the policy, does it invent anything, does it actually answer the question. Use humans to define "good" initially and to calibrate the judge.

  1. Name 3 ways to make LLM-as-judge more reliable.
Show answer

Binary, specific criteria instead of a vague scale; require a reason; calibrate against humans (measure the agreement rate on 30–50 cases); separate the judge from the system being graded (a different prompt, consider a different model); shuffle the order and hide the source when comparing two outputs.

  1. An eval set gives every configuration 99%. What does that tell you and what should you do?
Show answer

The eval set is too easy; it cannot distinguish good configurations from bad ones, so it does not help you make decisions. Add hard cases: edge cases, ambiguous tickets, tickets with multiple issues, bugs seen in production. A useful eval set is one with failing cases you can learn something from.

  1. An agent calls search_orders with the same input 12 times in a row. How do you debug it?
Show answer

Get the transcript and look at the tool output for each call: most likely the tool returns empty results or an error with no guidance, so the model has no new information to change direction. Fix the tool to return a message with hints (correct format, alternative tools); add loop detection in the loop code (same tool + same input N times means stop); limit the number of turns; add this case to the evals.

  1. Why should you save the full transcript for every agent run?
Show answer

Agents are non-deterministic: rerunning may not reproduce the bug. The transcript shows exactly what the model saw at each turn, which tool it called and what the tool returned, so you can find the first turn that went wrong and classify the bug (prompt, tool, data, model limitation). Transcripts are also a source of new eval cases. Remember to control PII and secrets in transcripts.

Hands-on Exercises

Exercise 1: Should you build an agent?

List 5 ideas for using Claude in your project. For each idea, answer the 4 questions in Part 1 and choose a level: single call, workflow, agent.

Expected output: a 5-row table; at least 2 ideas concluding "no agent needed" with reasons.

Exercise 2: A read-only agent with the Agent SDK

Write an agent with the Agent SDK that lists TODO/FIXME comments in the repo, groups them by directory and estimates severity. Allow only Read, Glob, Grep.

Expected output: a working script; output grouped by directory; try asking the agent to "fix all the TODOs too" and record how it reacts without Edit permission.

Exercise 3: Redesign tools

Take 3 tools (from an MCP server you use, or write your own for acme-shop). Rewrite their names, descriptions, schemas, output format and error messages following Part 2.

Expected output: a before/after table for each tool; run one agent scenario with the old and new versions, and compare the number of turns and wrong calls.

Exercise 4: Classification eval

Take the 20 tickets from the Day 5 exercise and expand them to at least 50 labeled cases (add hard cases). Run the eval script from Part 3 with 3 configurations (for example Haiku 5.5 low, Sonnet 5.5 low, Opus 5.5 low).

Expected output: a table of accuracy, estimated cost, duration; a list of 5 cases that fail in all three configurations; a recommended configuration with reasons.

Exercise 5: Calibrated LLM-as-judge

Write 10 customer support answers (some following the policy, some inventing information). Grade them by hand against the rubric, then run the judge from Part 3.

Expected output: a table comparing hand grading and the judge; the agreement rate; if it is below 80%, fix the rubric and run again.

Exercise 6: Debugging from a transcript

Deliberately create a tool that returns a vague error (Error) and run the agent until it loops. Save the transcript and give it to Claude to analyze the turn that went wrong. Fix the tool and run again.

Expected output: before/after transcripts; a note on the first turn that went wrong; the reduction in turns after the fix.

References


Next lesson →