Objectives: LO-8.1, LO-8.2, LO-8.3
Prerequisites: the Module 8 reading
Time: about 2.5 hours
In this lab you validate dispatch records against a JSON Schema, write three tool definitions whose descriptions tell a model when to use each tool, and build the tool-use loop: run each call, return its result or its error, and stop on the right stop reason.
No cell sends anything over the network. Where a cell needs a model, a ScriptedModel from
promptlab answers instead, from a script written in the cell. Its responses have the shape
of real ones, but a person wrote them, so they are illustrative, not model output. The tools
read a small fictional menu, MENU, and change nothing.
Each exercise ends with a check cell that prints passed or fails with a message. Run the
cells in order, from the top. Some cells fail on purpose until you finish the exercise above
them.
Setup¶
import sys
import json
import re
from importlib.metadata import version
from jsonschema import validate, ValidationError
from promptlab import ScriptedModel, make_response
from promptlab.shop_tools import MENU, TOOLS, tool_turn, run_tool, text_of, ask
SCHEMA = {
"type": "object",
"properties": {"queue": {"enum": ["repair", "billing", "account"]},
"summary": {"type": "string", "minLength": 1, "maxLength": 80}},
"required": ["queue", "summary"],
"additionalProperties": False,
}
print("Python", sys.version.split()[0], "| jsonschema", version("jsonschema"))Predict validity¶
Both objects below are valid JSON. Predict which one satisfies SCHEMA, then run the cell.
for example in ({"queue": "repair", "summary": "Flat tire"}, {"queue": "repair"}):
try:
validate(example, SCHEMA)
print("valid", example)
except ValidationError:
print("invalid", example)Exercise L8.1 (LO-8.1, ★★, about 25 minutes)¶
Check the response contract. Write parse_record(text). Parse text as JSON, validate the
value against SCHEMA, and return the record. A summary that is blank or holds only spaces is
invalid too, even though it passes minLength. Turn the errors you expect, a parse error and a
schema error, into ValueError, so the caller has one kind of error to handle.
def parse_record(text):
raise NotImplementedError("L8.1")record = parse_record('{"queue":"account","summary":"Reset email"}')
assert record == {"queue": "account", "summary": "Reset email"}, \
f"A valid record should come back unchanged, not {record!r}."
bad_records = {
"oops": "text that isn't JSON",
'{"queue":"unknown","summary":"A"}': "a queue that isn't in the enum",
'{"queue":"repair","summary":" "}': "a summary of spaces only",
'{"queue":"repair"}': "a record with no summary",
'{"queue":"repair","summary":"A","urgent":true}': "a field the schema doesn't name",
json.dumps({"queue": "repair", "summary": "A" * 81}): "an 81-character summary",
"[]": "JSON that isn't an object",
}
for bad, why in bad_records.items():
try:
parse_record(bad)
except ValueError:
pass
else:
raise AssertionError(f"parse_record accepted {why}: {bad[:50]}")
print("passed")Exercise L8.2 (LO-8.2, ★★, about 25 minutes)¶
Write tool specifications. Write specs(), which returns a list of three tool definitions,
each with a name, a description, and an input_schema. Use the names and input schemas in
the setup’s TOOLS, in the same order, but write your own descriptions. Those in TOOLS are
one sentence long, and Anthropic’s
guide to defining tools
recommends at least three to four sentences for each. Say what each tool returns, when to use
it, and what it doesn’t cover, so the descriptions tell a price from a bench time. The lab’s
run_tool already maps these names to the fictional menu.
def specs():
raise NotImplementedError("L8.2")defs = specs()
assert [x["name"] for x in defs] == [x["name"] for x in TOOLS], "Use the names in TOOLS, in order."
assert [x["input_schema"] for x in defs] == [x["input_schema"] for x in TOOLS], \
"Use the input schemas in TOOLS unchanged."
descriptions = [x["description"] for x in defs]
assert not set(descriptions) & {x["description"] for x in TOOLS}, \
"Write your own descriptions instead of the one-sentence ones in TOOLS."
short = [x["name"] for x in defs if len(re.findall(r"[.!?](?:\s|$)", x["description"])) < 3]
assert not short, f"Give each description at least three sentences; these have fewer: {short}"
assert "price" in descriptions[0].lower() and "minute" in descriptions[1].lower(), \
"Say that find_service returns a price and estimate_minutes returns minutes."
print("passed")Exercise L8.3 (LO-8.3, ★★, about 25 minutes)¶
Handle completed and incomplete turns. Write terminal(response), which returns a pair with
the stop reason first. For "end_turn", the second item is the response’s text, joined from
every text block as Module 2 did. For every other stop reason, it is None.
def terminal(response):
raise NotImplementedError("L8.3")result = terminal(make_response("Ready"))
assert result == ("end_turn", "Ready"), \
f"A finished answer gives ('end_turn', 'Ready'), not {result!r}."
two_blocks = make_response([{"type": "text", "text": "Ready "}, {"type": "text", "text": "now."}])
assert terminal(two_blocks) == ("end_turn", "Ready now."), \
"Join the text of every text block, not only the first."
assert terminal(make_response("Partial", stop_reason="max_tokens")) == ("max_tokens", None), \
"A cut-off answer isn't a final answer: return ('max_tokens', None)."
assert terminal(make_response([], stop_reason="refusal")) == ("refusal", None), \
"A refusal returns ('refusal', None)."
print("passed")Exercise L8.4 (LO-8.3, ★★, about 25 minutes)¶
Complete the loop. Write tool_loop(model, ticket, max_turns=4), which implements the
reading’s tool-use loop with the setup’s TOOLS and run_tool:
Start the history with the ticket as a user message, and send
TOOLSwith every request.On a
"tool_use"stop, forward the response’s wholecontentas an assistant message, text blocks included, then one user message with a result for everytool_useblock. A"tool_use"stop with notool_useblocks raisesValueError.On any other stop reason, return the same pair as
terminal.After
max_turnsrequests without a final answer, return("turn_limit", None).
def tool_loop(model, ticket, max_turns=4):
raise NotImplementedError("L8.4")model = ScriptedModel([tool_turn(("price", "find_service", {"service": "flat"}),
("bad", "shop_hours", {"day": "Sunday"})), "$18."])
result = tool_loop(model, "Price a flat and check hours.")
assert result == ("end_turn", "$18."), \
f"The loop should end with ('end_turn', '$18.'), not {result!r}."
names = [t["name"] for t in TOOLS]
assert all([t["name"] for t in r.get("tools", [])] == names for r in model.requests), \
"Send the tool definitions with every request."
last = model.requests[1]["messages"][-1]
assert last["role"] == "user", "Send the tool results in a user message."
assert [b["tool_use_id"] for b in last["content"]] == ["price", "bad"], \
"Send one result per call, in one message, each with its call's tool_use_id."
assert last["content"][1].get("is_error"), "The Sunday call failed, so its result needs is_error."
mixed = make_response([{"type": "text", "text": "Checking the menu."},
{"type": "tool_use", "id": "m1", "name": "find_service",
"input": {"service": "brakes"}}], stop_reason="tool_use")
model = ScriptedModel([mixed, "$35."])
assert tool_loop(model, "Price brakes.") == ("end_turn", "$35."), "The loop should return '$35.'."
assert model.requests[1]["messages"][1] == {"role": "assistant", "content": mixed["content"]}, \
"Forward the response's content unchanged, text block included, as an assistant message."
try:
tool_loop(ScriptedModel([make_response("Let me check.", stop_reason="tool_use")]), "Price.")
except ValueError:
pass
else:
raise AssertionError("A tool_use stop with no tool_use blocks should raise ValueError.")
assert tool_loop(ScriptedModel([]), "Flat", 0) == ("turn_limit", None), \
"With max_turns=0, return ('turn_limit', None) without calling the model."
looping = ScriptedModel([tool_turn(("again", "find_service", {"service": "flat"}))])
assert tool_loop(looping, "Price a flat.", max_turns=1) == ("turn_limit", None), \
"A loop that is still calling tools after max_turns requests returns ('turn_limit', None)."
assert looping.calls == 1, f"Stop at the turn limit: expected 1 request, got {looping.calls}."
print("passed")Summary¶
json.loadschecks syntax,jsonschemachecks a record against its schema, and your own code checks what a schema can’t, such as a summary of spaces only. OneValueErrorreports every failure to the caller.A tool’s description tells a model what the tool returns and when to use it. The host still validates every input, and answers a bad one with an error result.
The tool-use loop forwards the model’s whole turn, returns one result per call in a single user message, matched by
tool_use_id, and stops on any other stop reason or at its turn limit.The stand-in tested the loop’s plumbing. Whether a real model picks the right tool from your descriptions needs an evaluation against that model.