Part 18 / Stage 4
Tool use and agents
Goal: Let models take actions, safely: tool definitions, the agent loop, error handling, and when not to build an agent at all. Time: ~3 hours · Needs: Part 14
What you will learn
- Tool use: definitions, JSON schemas, strict mode
- The agent loop
- Parallel tool calls
- When not to build an agent
- Tool design
- Connecting tools with MCP
Topics in this part
Practice
Exercises 1–3 are offline; Exercise 4 uses the local mock (Part 14 setup) or a real key.
Exercise 1: Write the schema
Define the tool schema for list_orders(customer_email: str, limit: int = 5) — strict mode, required vs optional fields, and a description that teaches by example. Print it as JSON.
Show the solution to Exercise 1
# Exercise 1: Write the schema
import json
LIST_ORDERS = {
"name": "list_orders",
"description": (
"List a customer's recent orders, newest first, by their account email "
"(such as [email protected]). Returns order ids and statuses. Use it when "
"the customer has not given an order id; for one known id, use "
"get_order_status instead."
),
"input_schema": {
"type": "object",
"properties": {
"customer_email": {
"type": "string",
"description": "Account email, e.g. [email protected]",
},
"limit": {
"type": "integer",
"description": "How many orders to return (default 5, max 20)",
},
},
"required": ["customer_email"], # limit stays optional
"additionalProperties": False,
},
"strict": True,
}
print(json.dumps(LIST_ORDERS, indent=2))
Exercise 2: Harden the dispatcher
Extend the lesson's dispatcher with a list_orders tool and three new failure cases: bad argument types, a tool that raises an unexpected ValueError, and an empty result. All must come back as readable tool_results (errors flagged), never exceptions.
Show the solution to Exercise 2
# Exercise 2: Harden the dispatcher
import json
ORDERS = {"A1001": "shipped", "A1002": "delivered"}
CUSTOMERS = {"[email protected]": ["A1001", "A1002"], "[email protected]": []}
def get_order_status(order_id: str) -> dict:
if order_id not in ORDERS:
raise KeyError(f"No order with id {order_id}")
return {"order_id": order_id, "status": ORDERS[order_id]}
def list_orders(customer_email: str, limit: int = 5) -> dict:
if not isinstance(limit, int):
raise TypeError(f"limit must be an integer, got {type(limit).__name__}")
if "@" not in customer_email:
raise ValueError(f"{customer_email!r} is not an email address")
orders = CUSTOMERS.get(customer_email, [])[:limit]
return {"customer": customer_email, "orders": orders,
"note": "no orders on file" if not orders else ""}
TOOLS = {"get_order_status": get_order_status, "list_orders": list_orders}
def run_tool_call(tool_use_id, name, args):
"""Always returns a tool_result; every failure becomes readable is_error data."""
if name not in TOOLS:
return {"type": "tool_result", "tool_use_id": tool_use_id,
"content": f"Unknown tool {name!r}", "is_error": True}
try:
return {"type": "tool_result", "tool_use_id": tool_use_id,
"content": json.dumps(TOOLS[name](**args))}
except (KeyError, ValueError, TypeError) as e:
msg = str(e).strip("'\"")
except Exception as e: # last-resort net: never crash the loop
msg = f"Tool failed unexpectedly: {type(e).__name__}: {e}"
return {"type": "tool_result", "tool_use_id": tool_use_id,
"content": msg, "is_error": True}
calls = [
("toolu_1", "get_order_status", {"order_id": "A1001"}), # ok
("toolu_2", "list_orders", {"customer_email": "[email protected]", "limit": "five"}), # bad type
("toolu_3", "list_orders", {"customer_email": "not-an-email"}), # ValueError
("toolu_4", "list_orders", {"customer_email": "[email protected]"}), # empty result (ok)
("toolu_5", "cancel_order", {"order_id": "A1002"}), # unknown tool
]
for c in calls:
print(run_tool_call(*c))
Exercise 3: Call, workflow or agent?
For six task descriptions (translate a paragraph; nightly summary of new tickets; "find why revenue dipped last week" over a SQL database; extract invoice fields; re-order a customer's usual items on request; answer from a fixed FAQ), print your verdict and a one-line reason each.
Show the solution to Exercise 3
# Exercise 3: Call, workflow or agent?
VERDICTS = [
("Translate a paragraph",
"CALL — one well-defined transformation, no decisions to make."),
("Nightly summary of new tickets",
"WORKFLOW — fixed steps (fetch, summarise each, aggregate); your code owns the order."),
("Find why revenue dipped last week (SQL database)",
"AGENT — the model must explore: query, read, form a hypothesis, query again."),
("Extract invoice fields",
"CALL — structured output with a Pydantic schema; done."),
("Re-order a customer's usual items on request",
"WORKFLOW — look up usuals, confirm, place order: known steps, plus an approval gate."),
("Answer from a fixed FAQ",
"CALL — RAG retrieve + one grounded call; no loop needed."),
]
for task, verdict in VERDICTS:
print(f"{task:50s} {verdict}")
Exercise 4: Two-tool agent
Run the lesson's agent loop with BOTH get_order_status and list_orders registered, a step limit of 5, and a printed log line per tool call (step, name, arguments). Use the mock or a real key; label the final answer honestly if mocked.
Show the solution to Exercise 4
# Exercise 4: Two-tool agent (run with the local mock or a real key — Part 14 setup)
import json
import os
import anthropic
ORDERS = {"A1001": "shipped", "A1002": "delivered"}
CUSTOMERS = {"[email protected]": ["A1001", "A1002"]}
def get_order_status(order_id):
return json.dumps({"order_id": order_id, "status": ORDERS.get(order_id, "not found")})
def list_orders(customer_email, limit=5):
return json.dumps({"customer": customer_email,
"orders": CUSTOMERS.get(customer_email, [])[:limit]})
TOOLS = {"get_order_status": get_order_status, "list_orders": list_orders}
tools = [
{"name": "get_order_status",
"description": "Look up one order's shipping status by id, such as A1001.",
"input_schema": {"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"], "additionalProperties": False},
"strict": True},
{"name": "list_orders",
"description": "List a customer's recent orders by email, newest first.",
"input_schema": {"type": "object",
"properties": {"customer_email": {"type": "string"},
"limit": {"type": "integer"}},
"required": ["customer_email"], "additionalProperties": False},
"strict": True},
]
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "What are [email protected]'s recent orders?"}]
for step in range(5):
response = client.messages.create(model="claude-opus-5-5", max_tokens=16000,
tools=tools, messages=messages)
if response.stop_reason != "tool_use":
break
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
print(f"step {step}: {block.name}({block.input})")
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": TOOLS[block.name](**block.input)})
messages.append({"role": "user", "content": results})
text = "".join(b.text for b in response.content if b.type == "text")
mocked = "ANTHROPIC_BASE_URL" in os.environ
print(f"final{' (placeholder from local mock, not Claude)' if mocked else ''}:", text)
Mini-project: Order assistant
An agent with get_order_status and list_orders, a step limit, an error-safe dispatcher, and a log of every tool call. Run three scripted conversations (valid order, unknown order, list request) and print each transcript.
A complete version is in solutions/mini_order_assistant.py.
Stretch: add a refund_order tool that requires human approval (Track D's guard), plus an eval of 20 scripted conversations.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| No step limit | Runaway loops burn money | Hard cap + budget + timeout |
| Tool exceptions crash the loop | One bad id kills the chat | is_error tool_results |
| Results split across messages | Discourages parallel calls, confuses pairing | One user message, all results |
| Vague tool descriptions | Wrong tool, wrong arguments | Write them as documentation |
| Agent-first design | Cost and failure modes for nothing | Single call, then workflow, then agent |
| Write tools without gates | The model can take irreversible actions | Allowlist + approval (Track D) |
Quick recap
- A tool is a schema plus a description; the model requests the call, and your code executes it.
- The loop takes a tool_use, runs it, returns a tool_result matched by id, and repeats — under a hard step limit.
- Parallel calls return together; errors return as readable
is_errordata. - Escalate from a single call to a workflow to an agent only when the steps are unknown in advance.
- Design tools like APIs for a new teammate; gate the writes.
- MCP standardises the tool plumbing across apps.
Checklist
- I wrote a tool schema with strict mode and an example-bearing description.
- I can trace one loop iteration: stop_reason, history, tool_result ids.
- My dispatcher returns errors the model can act on.
- I can argue call vs workflow vs agent for three sample tasks.
- I can say what MCP standardises in one sentence.
Read more: Tool use · Building effective agents · MCP