About this notebook
Companion to Module 3: Tools and MCP. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
Notebook 1 turned two functions into tools and let one of them fail. This notebook looks at everything between the model’s request for a tool and the observation that goes back, because that is where most of the engineering in a tool-using agent lives:
- the wire format: what a tool definition and a tool call look like as JSON;
- schemas from signatures: generating the definition from a Python function;
- validation: checking the model’s arguments before running anything;
- a registry that never crashes: every failure becomes an observation;
- errors in the loop: why the wording of an error message matters;
- descriptions are the interface: a linter for tool definitions;
- a search tool, and how much its output costs in tokens;
- everything together in
agentlab.Agent.
Which model answers here?
With no
MODELset, the offline policy model answers. It picks a tool by counting words shared between the request and each tool’s name and description, and it has one rule written for this notebook that maps currency words (“euros”) to codes (EUR). It is a stand-in, not a language model: where this notebook shows it choosing a tool, read that as a demonstration of the mechanics, not as evidence of what a real model would choose. Section 5 uses a scripted model, so the failures happen on cue.
from agentlab.nbsetup import setup
nb = setup("03a_function_calling", packs=["tools"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. A tool call on the wire
A tool is a function plus a description the model can read. Here is one with a closed set of currencies, so that the model has something to get wrong later. The exchange rates are made-up round numbers.
from typing import Literal
from agentlab import LlmRequest, Message, tool
RATES_PER_USD = {"USD": 1.0, "EUR": 0.9, "JPY": 150.0, "GBP": 0.8} # made-up round rates
Currency = Literal["USD", "EUR", "JPY", "GBP"]
def convert_currency(amount: float, from_currency: Currency, to_currency: Currency) -> str:
"""Convert an amount of money between currencies (US dollars, euros, yen, pounds).
Uses fixed illustrative rates, not live market rates.
Args:
amount: How much money, in units of from_currency. Must be positive.
from_currency: ISO 4217 code of the currency the amount is in.
to_currency: ISO 4217 code of the currency to convert to.
"""
if amount <= 0:
raise ValueError("amount must be positive")
value = amount / RATES_PER_USD[from_currency] * RATES_PER_USD[to_currency]
return f"{amount:g} {from_currency} = {value:,.2f} {to_currency}"
request = LlmRequest(
instructions=["Answer the user's question. Use a tool when one fits."],
contents=[Message(role="user", content="How many yen is 120 euros?")],
tools=[tool(convert_currency)],
)
response = await llm.generate(request)
for c in response.tool_calls:
print(f"{c.name}({c.arguments})")convert_currency({'amount': 120.0, 'from_currency': 'EUR', 'to_currency': 'JPY'})
The model did not run anything. It returned a request to run convert_currency with
some arguments. Here is the definition it was shown, in the OpenAI-style format that
LiteLLM accepts for every provider:
import json
from agentlab.llm import build_messages
from agentlab.llm.base import tool_definitions
print(json.dumps(tool_definitions(request)[0], indent=2)){
"type": "function",
"function": {
"name": "convert_currency",
"description": "Convert an amount of money between currencies (US dollars, euros, yen, pounds).\n\nUses fixed illustrative rates, not live market rates.",
"parameters": {
"type": "object",
"properties": {
"amount": {
"type": "number",
"description": "How much money, in units of from_currency. Must be positive."
},
"from_currency": {
"enum": [
"USD",
"EUR",
"JPY",
"GBP"
],
"type": "string",
"description": "ISO 4217 code of the currency the amount is in."
},
"to_currency": {
"enum": [
"USD",
"EUR",
"JPY",
"GBP"
],
"type": "string",
"description": "ISO 4217 code of the currency to convert to."
}
},
"required": [
"amount",
"from_currency",
"to_currency"
]
}
}
}
And here is the model’s reply as it travels back. Note that arguments is a JSON
string, not an object. Your code parses it, and a model can produce a string that does
not parse (Notebook 2b showed how easily that happens).
wire = build_messages(LlmRequest(contents=request.contents + response.content))
print(json.dumps(wire[-1], indent=2)){
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_0000",
"type": "function",
"function": {
"name": "convert_currency",
"arguments": "{\"amount\": 120.0, \"from_currency\": \"EUR\", \"to_currency\": \"JPY\"}"
}
}
]
}
Your code then runs the function and sends the result back as a message with role tool,
tied to the call by its id. Doing this by hand once makes the loop’s last step concrete:
tool_call = wire[-1]["tool_calls"][0]
arguments = json.loads(tool_call["function"]["arguments"])
tool_message = {"role": "tool", "tool_call_id": tool_call["id"],
"content": convert_currency(**arguments)}
print(json.dumps(tool_message, indent=2)){
"role": "tool",
"tool_call_id": "call_0000",
"content": "120 EUR = 20,000.00 JPY"
}
Providers agree on the idea and differ in the field names. LiteLLM translates, which is why the rest of the course only ever sees the OpenAI-style shapes above.
| OpenAI-style (chat completions) | Anthropic Messages API | |
|---|---|---|
| tool list | tools[].function with name, description, parameters | tools[] with name, description, input_schema |
| the model asks | tool_calls[].function.arguments, a JSON string | a tool_use content block whose input is a JSON object |
| you answer | a message with role tool and the tool_call_id | a tool_result block in the next user message, with the tool_use_id |
2. From a signature to a schema
Writing JSON Schema by hand for every tool is tedious and drifts out of date. A Python function already says most of it: parameter names, types, which ones have defaults. The docstring supplies the rest. About 35 lines turn one into the other:
import inspect
import re
import types
import typing
from typing import get_args, get_origin, get_type_hints
JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"}
def type_schema(hint) -> dict:
origin = get_origin(hint)
if origin is typing.Literal:
return {"type": "string", "enum": list(get_args(hint))}
if origin is list:
return {"type": "array", "items": type_schema(get_args(hint)[0])}
if origin in (typing.Union, types.UnionType): # Optional[T] is Union[T, None]
(inner,) = [a for a in get_args(hint) if a is not type(None)]
return type_schema(inner)
return {"type": JSON_TYPES.get(hint, "string")}
def arg_descriptions(doc: str | None) -> dict[str, str]:
"""The 'Args:' section of a Google-style docstring, as {name: description}."""
section = inspect.cleandoc(doc or "").partition("Args:")[2]
return {m[1]: m[2].strip() for m in re.finditer(r"^\s*(\w+):\s*(.+)$", section, re.M)}
def schema_for(func) -> dict:
hints = get_type_hints(func)
descriptions = arg_descriptions(func.__doc__)
properties, required = {}, []
for name, param in inspect.signature(func).parameters.items():
prop = type_schema(hints.get(name, str))
if name in descriptions:
prop["description"] = descriptions[name]
if param.default is inspect.Parameter.empty:
required.append(name)
elif param.default is not None: # "None" means "absent", not a value to suggest
prop["default"] = param.default
properties[name] = prop
return {"type": "object", "properties": properties, "required": required}
print(json.dumps(schema_for(convert_currency), indent=2)){
"type": "object",
"properties": {
"amount": {
"type": "number",
"description": "How much money, in units of from_currency. Must be positive."
},
"from_currency": {
"type": "string",
"enum": [
"USD",
"EUR",
"JPY",
"GBP"
],
"description": "ISO 4217 code of the currency the amount is in."
},
"to_currency": {
"type": "string",
"enum": [
"USD",
"EUR",
"JPY",
"GBP"
],
"description": "ISO 4217 code of the currency to convert to."
}
},
"required": [
"amount",
"from_currency",
"to_currency"
]
}
agentlab.tools has the same function with a few more cases (Pydantic models, dict,
unions of several types). On these functions the two agree:
from agentlab.tools import function_to_input_schema
def search_example(query: str, max_results: int = 3, site: str | None = None) -> str:
"""Example with defaults and an optional argument."""
return query
for f in (convert_currency, search_example):
assert schema_for(f) == function_to_input_schema(f), f.__name__
print("schema_for matches agentlab.tools.function_to_input_schema")schema_for matches agentlab.tools.function_to_input_schema
Two things the generator cannot know. “Must be positive” is written in the docstring, so the model reads it, but nothing in the schema enforces it; the function itself has to check. And the summary line of the docstring becomes the tool’s description, which is the model’s main clue for when to use the tool. Write it for the model, not for yourself.
3. Validate before you call
The model’s arguments are untrusted input, the same as a form a user filled in. Checking them against the schema before running anything catches most bad calls, and, as important, it lets you say exactly what was wrong.
TYPE_CHECKS = {
"string": lambda v: isinstance(v, str),
"integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
"number": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool),
"boolean": lambda v: isinstance(v, bool),
"array": lambda v: isinstance(v, list),
"object": lambda v: isinstance(v, dict),
}
def validate_args(schema: dict, args: dict) -> list[str]:
"""Every problem with ``args``, phrased so that a model can fix its call."""
props = schema.get("properties", {})
problems = [f"missing required argument '{k}'" for k in schema.get("required", [])
if k not in args]
for key, value in args.items():
spec = props.get(key)
if spec is None:
problems.append(f"unknown argument '{key}'; expected one of {sorted(props)}")
elif "enum" in spec and value not in spec["enum"]:
problems.append(f"'{key}' must be one of {spec['enum']}, got {value!r}")
elif not TYPE_CHECKS[spec.get("type", "string")](value):
problems.append(f"'{key}' must be a {spec.get('type')}, got {value!r}")
return problems
schema = schema_for(convert_currency)
cases = [
{"amount": 120, "from_currency": "EUR", "to_currency": "JPY"},
{"amount": "120", "from_currency": "EUR", "to_currency": "JPY"},
{"amount": 120, "from_currency": "euro", "to_currency": "JPY"},
{"amount": 120, "to_currency": "JPY"},
{"amount": 120, "from_currency": "EUR", "to_currency": "JPY", "date": "today"},
]
for args in cases:
print(json.dumps(args), "\n ->", validate_args(schema, args) or "ok"){"amount": 120, "from_currency": "EUR", "to_currency": "JPY"}
-> ok
{"amount": "120", "from_currency": "EUR", "to_currency": "JPY"}
-> ["'amount' must be a number, got '120'"]
{"amount": 120, "from_currency": "euro", "to_currency": "JPY"}
-> ["'from_currency' must be one of ['USD', 'EUR', 'JPY', 'GBP'], got 'euro'"]
{"amount": 120, "to_currency": "JPY"}
-> ["missing required argument 'from_currency'"]
{"amount": 120, "from_currency": "EUR", "to_currency": "JPY", "date": "today"}
-> ["unknown argument 'date'; expected one of ['amount', 'from_currency', 'to_currency']"]
Pydantic can do the same job from the type hints alone. By default it is lenient: it
converts the string "120" to the number 120 instead of rejecting it, while still
refusing a currency that is not in the list.
from pydantic import ValidationError, validate_call
checked = validate_call(convert_currency)
for args in cases[1:3]:
try:
print("ok:", checked(**args))
except ValidationError as exc:
print(f"{exc.error_count()} error:", exc.errors()[0]["msg"])ok: 120 EUR = 20,000.00 JPY 1 error: Input should be 'USD', 'EUR', 'JPY' or 'GBP'
Either policy is defensible. Lenient validation saves a round trip for harmless slips; strict validation keeps your tools’ inputs exactly as documented. What matters is that the check happens before the tool runs, and that its message names the expected values.
4. A registry that never crashes
An agent’s tool layer receives whatever the model writes. Each of the following can happen, and none of them should stop the agent:
model's tool call
-> is the tool known? no -> error: list the tools that exist
-> do the arguments parse? no -> error: say it must be a JSON object
-> are they valid? no -> error: say what was expected
-> run the function raises -> error: the exception's type and message
-> cap the output length too long -> cut it, and say how much was cut
-> observation, sent back to the model either wayA second tool reads pages from a small offline “web”: thirteen short pages written for
this course, at addresses on the reserved kb.example domain.
from dataclasses import dataclass
from agentlab.config import fixtures_dir
PAGES = {p["url"]: p for p in
json.loads((fixtures_dir() / "tools" / "web_pages.json").read_text())}
def read_page(url: str) -> str:
"""Return the full text of one page from the offline web.
Args:
url: The page's address, exactly as returned by search_web.
"""
if url not in PAGES:
raise LookupError(f"no page at {url}; use a URL returned by search_web")
return PAGES[url]["title"] + "\n" + PAGES[url]["text"]
@dataclass
class Observation:
status: str # "success" or "error"
content: str
class ToolRegistry:
def __init__(self, max_chars: int = 600):
self.functions, self.schemas, self.max_chars = {}, {}, max_chars
def register(self, func):
self.functions[func.__name__] = func
self.schemas[func.__name__] = schema_for(func)
return func
def definitions(self) -> list[dict]:
return [{"type": "function", "function": {
"name": name, "description": inspect.getdoc(f).split("\n")[0],
"parameters": self.schemas[name]}}
for name, f in self.functions.items()]
def dispatch(self, name: str, arguments: str) -> Observation:
if name not in self.functions:
known = sorted(self.functions)
return Observation("error", f"unknown tool '{name}'; available tools: {known}")
try:
args = json.loads(arguments)
except json.JSONDecodeError as exc:
return Observation("error", f"arguments are not valid JSON ({exc.msg}); "
"send one JSON object")
problems = validate_args(self.schemas[name], args)
if problems:
return Observation("error", f"invalid arguments for {name}: "
+ "; ".join(problems))
try:
output = str(self.functions[name](**args))
except Exception as exc:
return Observation("error", f"{name} failed: {type(exc).__name__}: {exc}")
if len(output) > self.max_chars:
cut = len(output) - self.max_chars
output = output[: self.max_chars] + f" ... [{cut} more characters cut]"
return Observation("success", output)
registry = ToolRegistry(max_chars=300)
registry.register(convert_currency)
registry.register(read_page)
print([d["function"]["name"] for d in registry.definitions()])['convert_currency', 'read_page']
calls = [
("convert_currency", '{"amount": 120, "from_currency": "EUR", "to_currency": "JPY"}'),
("convert_money", '{"amount": 120}'),
("convert_currency", "{'amount': 120}"),
("convert_currency", '{"amount": 120, "from_currency": "euro", "to_currency": "JPY"}'),
("convert_currency", '{"amount": -5, "from_currency": "EUR", "to_currency": "JPY"}'),
("read_page", '{"url": "https://kb.example/formats/json-schema"}'),
]
for name, arguments in calls:
obs = registry.dispatch(name, arguments)
print(f"{name} {arguments}\n -> {obs.status}: {obs.content}\n")convert_currency {"amount": 120, "from_currency": "EUR", "to_currency": "JPY"}
-> success: 120 EUR = 20,000.00 JPY
convert_money {"amount": 120}
-> error: unknown tool 'convert_money'; available tools: ['convert_currency', 'read_page']
convert_currency {'amount': 120}
-> error: arguments are not valid JSON (Expecting property name enclosed in double quotes); send one JSON object
convert_currency {"amount": 120, "from_currency": "euro", "to_currency": "JPY"}
-> error: invalid arguments for convert_currency: 'from_currency' must be one of ['USD', 'EUR', 'JPY', 'GBP'], got 'euro'
convert_currency {"amount": -5, "from_currency": "EUR", "to_currency": "JPY"}
-> error: convert_currency failed: ValueError: amount must be positive
read_page {"url": "https://kb.example/formats/json-schema"}
-> success: JSON Schema in brief
JSON Schema is a vocabulary for describing the shape of JSON data. A schema for an object lists its properties, the type of each one (string, number, integer, boolean, array, object or null), which properties are required, and optional constraints such as enum for a fixed set of ... [239 more characters cut]
Every line above is something the model reads on its next step. “Unknown tool” lists the real names; “invalid arguments” lists the allowed codes; the failed conversion says why; the long page says how much was cut, so the model knows it has not seen everything.
5. Errors in the loop
agentlab.Agent already turns exceptions into observations (Notebook 1). It does not
validate arguments: it calls the function with whatever arrived. A before_tool
callback adds the check without touching the agent. A callback that returns a
ToolResult replaces the call; one that returns None lets it run.
from agentlab import Agent, ToolResult, show_trajectory
from agentlab.llm import ScriptedLLM, ToolCallSpec
def validation_callback(tools):
schemas = {t.name: t.parameters for t in tools}
def before_tool(context, tool_call):
if tool_call.name not in schemas:
return None # the agent already reports unknown tools
problems = validate_args(schemas[tool_call.name], tool_call.arguments)
if not problems:
return None
message = "invalid arguments: " + "; ".join(problems)
return ToolResult(tool_call_id=tool_call.tool_call_id, name=tool_call.name,
status="error", content=[message])
return before_toolTo compare the two observations fairly, a scripted model makes the same mistake in both runs (currency names instead of codes) and the same correction afterwards.
def scripted_model():
return nb.track(ScriptedLLM([
ToolCallSpec("convert_currency",
{"amount": 120, "from_currency": "euros", "to_currency": "yen"}),
ToolCallSpec("convert_currency",
{"amount": 120, "from_currency": "EUR", "to_currency": "JPY"}),
"120 euros is 20,000 yen at this notebook's fixed rates.",
]))
tools = [tool(convert_currency)]
for label, callbacks in [("without validation", []),
("with validation", [validation_callback(tools)])]:
agent = Agent(model=scripted_model(), tools=tools, before_tool_callbacks=callbacks)
print(f"--- {label}")
show_trajectory(await agent.run("How many yen is 120 euros?"))--- without validation
[user] How many yen is 120 euros?
[agent -> convert_currency] {"amount": 120, "from_currency": "euros", "to_currency": "yen"}
[convert_currency ERROR] KeyError: 'euros'
[agent -> convert_currency] {"amount": 120, "from_currency": "EUR", "to_currency": "JPY"}
[convert_currency ok] 120 EUR = 20,000.00 JPY
[agent] 120 euros is 20,000 yen at this notebook's fixed rates.
--- status: complete, steps: 3
--- with validation
[user] How many yen is 120 euros?
[agent -> convert_currency] {"amount": 120, "from_currency": "euros", "to_currency": "yen"}
[convert_currency ERROR] invalid arguments: 'from_currency' must be one of ['USD', 'EUR', 'JPY', 'GBP'], got 'euros'; ...
[agent -> convert_currency] {"amount": 120, "from_currency": "EUR", "to_currency": "JPY"}
[convert_currency ok] 120 EUR = 20,000.00 JPY
[agent] 120 euros is 20,000 yen at this notebook's fixed rates.
--- status: complete, steps: 3
The scripted model corrects itself both times because we wrote it that way. A real model
can only correct what the observation tells it about. KeyError: 'euros' says that
something was missing, but not what would have worked. The validated version names the four
codes. Writing error messages is writing prompts.
6. Descriptions are the interface
The model never sees your code. It sees a name, a description and a schema, and nothing else, so those three have to say what the tool does, when to use it and how to fill each argument. Vendor guides boil this down to a few checks, and they are easy to automate:
CLOSED_SET_HINTS = ("state", "mode", "unit", "status", "format", "currency", "level")
def lint_tool(definition: dict) -> list[str]:
fn = definition["function"]
params = fn.get("parameters", {})
props = params.get("properties", {})
issues = []
if "_" not in fn["name"]:
issues.append(f"name '{fn['name']}' is one word: name the action and the object")
if len(fn.get("description", "")) < 25:
issues.append("description too short to say what the tool does and when to use it")
if props and "required" not in params:
issues.append("no 'required' list: mandatory and optional arguments look the same")
if sum(p.get("type") == "boolean" for p in props.values()) >= 2:
issues.append("several booleans can contradict each other: use one enum")
for name, p in props.items():
if "description" not in p and "enum" not in p:
issues.append(f"argument '{name}' has no description")
if any(h in name for h in CLOSED_SET_HINTS) and "enum" not in p:
issues.append(f"argument '{name}' looks like a closed set: consider an enum")
if len(props) > 6:
issues.append(f"{len(props)} arguments: consider splitting the tool")
return issues
def fn_def(name, description, properties, **extra):
params = {"type": "object", "properties": properties, **extra}
return {"type": "function", "function": {"name": name, "description": description,
"parameters": params}}
candidates = [
fn_def("convert", "Converts.", {"x": {"type": "number"}, "a": {"type": "string"},
"b": {"type": "string"}}),
fn_def("export_report", "Export the report.",
{"csv": {"type": "boolean"}, "pdf": {"type": "boolean"},
"format_version": {"type": "string"}}),
tool(convert_currency).tool_definition,
tool(read_page).tool_definition,
]
for d in candidates:
issues = lint_tool(d)
print(f"{d['function']['name']}: {'clean' if not issues else ''}")
for issue in issues:
print(" -", issue)convert: - name 'convert' is one word: name the action and the object - description too short to say what the tool does and when to use it - no 'required' list: mandatory and optional arguments look the same - argument 'x' has no description - argument 'a' has no description - argument 'b' has no description export_report: - description too short to say what the tool does and when to use it - no 'required' list: mandatory and optional arguments look the same - several booleans can contradict each other: use one enum - argument 'csv' has no description - argument 'pdf' has no description - argument 'format_version' has no description - argument 'format_version' looks like a closed set: consider an enum convert_currency: clean read_page: clean
A vague definition hurts even when the code behind it is fine. The cell below offers the
offline model the same function twice: once as convert(x, a, b) with the description
“Converts.”, once as convert_currency with the definition from section 1.
def convert(x: float, a: str, b: str) -> str:
"""Converts."""
return convert_currency(x, a, b)
question = [Message(role="user", content="How many yen is 120 euros?")]
for offered in ([tool(convert)], [tool(convert_currency)]):
r = await llm.generate(LlmRequest(contents=question, tools=offered))
chosen = [f"{c.name}({c.arguments})" for c in r.tool_calls] or [r.text[:80] + "..."]
print(f"offered {offered[0].name}:\n {chosen[0]}")offered convert:
[offline model] I received 0 system and 1 conversation message(s); the latest as...
offered convert_currency:
convert_currency({'amount': 120.0, 'from_currency': 'EUR', 'to_currency': 'JPY'})
The offline model matches words, so with nothing in “Converts.” that overlaps the question
it calls no tool at all. That is a caricature: a real model would probably guess that
convert is relevant, and then it would have to guess what a and b mean and in what
format. In both cases the model has only the definition to go on.
7. A search tool, and what its output costs
Search is the tool most agents get first, and its output design matters more than its ranking. The function below scores pages by the rare words they share with the query (a crude ranking; Module 5 does retrieval properly) and returns, for each hit, a title, a URL and the single most relevant sentence.
import math
from collections import Counter
STOP = {"the", "a", "an", "of", "to", "is", "in", "and", "or", "for", "on", "what", "which",
"that", "how", "does", "do", "search", "web", "me", "find"}
def terms(text: str) -> list[str]:
return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP]
def page_terms(page: dict) -> set[str]:
return set(terms(page["title"] + " " + page["text"]))
DOC_FREQ = Counter(w for p in PAGES.values() for w in page_terms(p))
def score(query_terms: set[str], page: dict) -> float:
shared = query_terms & page_terms(page)
return sum(math.log(1 + len(PAGES) / DOC_FREQ[w]) for w in shared)
def best_sentence(text: str, query_terms: set[str]) -> str:
sentences = re.split(r"(?<=[.!?])\s+", text)
return max(sentences, key=lambda s: len(set(terms(s)) & query_terms))
def search_web(query: str, max_results: int = 3) -> str:
"""Search the web; return the best pages with title, URL and a one-sentence snippet.
Args:
query: A few keywords describing what to find.
max_results: How many results to return, at most 5.
"""
q = set(terms(query))
ranked = sorted(PAGES.values(), key=lambda p: -score(q, p))
hits = [p for p in ranked if score(q, p) > 0][: min(max_results, 5)]
if not hits:
return f"No results for '{query}'. Try fewer or more general keywords."
return "\n".join(f"{i}. {p['title']} ({p['url']})\n {best_sentence(p['text'], q)}"
for i, p in enumerate(hits, 1))
print(search_web("rate limit retry status code"))
print()
print(search_web("quantum chromodynamics"))1. HTTP 429 Too Many Requests (https://kb.example/http/429-too-many-requests) Status code 429 means the client has sent too many requests in a given amount of time. 2. HTTP 503 Service Unavailable (https://kb.example/http/503-service-unavailable) Status code 503 means the server cannot handle the request right now, usually because it is overloaded or down for maintenance. 3. Indirect prompt injection (https://kb.example/security/indirect-prompt-injection) Treat tool output as data, never as instructions, and limit what an agent can do with it. No results for 'quantum chromodynamics'. Try fewer or more general keywords.
The third hit is a false friend: the prompt-injection page shares only the word limit, used in another sense (“limit what an agent can do”). Counting shared words cannot tell senses apart; Module 5 builds retrieval that does better. The second search shows that an empty result is an observation too, and a useful one if it suggests what to try next.
Now the cost. Here are three ways to return the same three hits, measured in tokens with the course’s rough estimate of 4 bytes per token (Notebook 2a measured the real ratio):
from agentlab.llm.pricing import estimate_tokens
query = "rate limit retry status code"
top = sorted(PAGES.values(), key=lambda p: -score(set(terms(query)), p))[:3]
designs = {
"full pages as JSON": json.dumps(top, indent=2),
"title, URL, snippet": search_web(query),
"URLs only": "\n".join(p["url"] for p in top),
}
for name, text in designs.items():
print(f"{name:>20}: {estimate_tokens(text):4d} tokens") full pages as JSON: 467 tokens
title, URL, snippet: 140 tokens
URLs only: 37 tokens
The output of a tool call stays in the history, so it is paid for again on every later
step (Module 1). Full pages cost several times more here, and on the real web, where a
page is thousands of words, the difference is far larger. URLs alone are cheapest but force
a read_page call per result, and each call is a whole extra step. The usual design is the
middle one: enough to decide what to read, plus a second tool to read it. Module 8 calls the
same idea progressive disclosure.
One more property of this tool’s output: it is text from outside your control. A page can contain instructions aimed at the model (indirect prompt injection, Module 12), so treat tool output as data, never as orders.
8. Everything together
Three tools as agentlab tools, with the validation callback from section 5, and two
questions for the offline model.
tools = [tool(search_web), tool(read_page), tool(convert_currency)]
agent = Agent(model=llm, tools=tools, before_tool_callbacks=[validation_callback(tools)],
instructions="Answer using the tools. Cite the URL you used.")
for question in ["Search the web for the status code that means too many requests",
"How many yen is 120 euros?"]:
show_trajectory(await agent.run(question))
print()[user] Search the web for the status code that means too many requests
[agent -> search_web] {"query": "the status code that means too many requests"}
[search_web ok] 1. HTTP 429 Too Many Requests (https://kb.example/http/429-too-many-requests) Status code 429...
[agent] According to `search_web`: 1. HTTP 429 Too Many Requests (https://kb.example/http/429-too-man...
--- status: complete, steps: 2
[user] How many yen is 120 euros?
[agent -> convert_currency] {"amount": 120.0, "from_currency": "EUR", "to_currency": "JPY"}
[convert_currency ok] 120 EUR = 20,000.00 JPY
[agent] According to `convert_currency`: 120 EUR = 20,000.00 JPY
--- status: complete, steps: 2
Try this
- Add a
minimumkey to the schema ofamountby hand, teachvalidate_argsto checkminimumandmaximum, and remove the check from insideconvert_currency. Which error message is better for the model?- Give
search_webasiteargument that filters by URL prefix. Runlint_toolon the new definition, and fix what it reports.- Make
ToolRegistry.dispatchaccept arguments that are an already-parseddictas well as a JSON string, as you would need for the Anthropic format in section 1.- With a live model, offer both
convertandconvert_currencyat once. Which does it call, and with what arguments?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 13 (fake: 7, scripted: 6) | ≈ 3,841 | ≈ 311 | ≈ USD 0.0051 (reference price) |