Free AI agents course
Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.
Schemas from functions, validation, output limits and helpful errors.
Why validate tool arguments before running the registered function?
The schema tells the model and harness which inputs the tool accepts. Validation at dispatch turns malformed input into recoverable feedback before the application performs work.
Model supplies a named tool and arguments
Registry matches the tool and checks its input schema
Valid calls run and output is capped for the model
Model supplies a named tool and arguments
Registry matches the tool and checks its input schema
Valid calls run and output is capped for the model
Given Model supplies a named tool and arguments and Valid calls run and output is capped for the model, write down the missing step that connects them.
Registry matches the tool and checks its input schema
Now take Registry matches the tool and checks its input schema and the result above. Write an input and an implementation that could produce this trace.
Model supplies a named tool and arguments. Check that your implementation produces the result shown above.
A tool expects a numeric limit, but the model passes an object. What should the registry return?
Return a schema error that identifies the limit argument and its expected type. The tool should remain uncalled so the model can correct the request safely.
Check this when debugging. Assuming the schema guarantees correct input.
Tools are the agent's hands, and the registry is where the harness keeps them. A registry does four jobs: describe each tool to the model, check what the model sends, run the tool, and shape what comes back. Each job has a classic failure. A vague description gets the wrong tool picked. A missing check runs a call with a bad argument. A huge output pushes everything else out of context. This lesson builds a registry that avoids all three.
The names and descriptions you write for each tool
A model only sees each tool's name, description and input schema, so those decide when it reaches for a tool and what it sends. The registry also checks inputs, runs the tool and shapes its result.
Recall: The core loop, built properly answered every tool_use with a tool_result, and Build a server: tools described tools with an inputSchema. The registry is where a harness keeps all of them.
tool_use gets a tool_result that carries its id, and all of them go back in the next user message. What does this print?tool_uses = [{"id": "tu_1", "name": "search"}, {"id": "tu_2", "name": "read"}]
def run_tool(use):
return {"type": "tool_result", "tool_use_id": use["id"],
"content": use["name"] + " ok"}
results = [run_tool(use) for use in tool_uses]
print(len(results), [r["tool_use_id"] for r in results])2 ['tu_1', 'tu_2']
The model asked for two tools in one reply, so two results go back, each carrying the id of the request it answers. run_tool here is a stub. The registry in this lesson is what stands behind it: the table that finds the right function for each name and checks its input before it runs.
Picture a new hire handed a cabinet of labeled drawers, who isn't allowed to open any until they've picked one. All they have is the labels. For each tool, the model gets three things: a name, a description and an input schema (JSON Schema). That is all it knows. It never sees your code. So the description must say:
Compare these two:
| weak | strong |
|---|---|
search: "Searches." | search_code: "Find lines matching a regular expression in the project. Use it to find where a name is defined or used. Returns up to 50 matches as path:line: text. Searches only inside the project folder." |
Names matter too. Use clear verbs, snake_case, and a prefix when several areas share a word (github_search, wiki_search).
Writing JSON Schema by hand for every tool gets tedious and drifts from the code. Most SDKs build it from the function itself: the parameter names, their type hints, which ones have defaults, and the docstring. Python's inspect module gives you all of that.
Seven steps. The model sees labels; the registry owns everything else.
"Find lines matching a regex in the project. Use it to locate where a name is defined or used. Returns up to 50 path:line matches."
Say what it does, when to use it, and what it returns. The model sees nothing but the name, description and schema.
Models sometimes send wrong or missing arguments, and a clear error lets them correct the call
A schema guides the model but doesn't always bind it. Checking first turns a crash into a helpful message.
Write a sentence or two, then compare it with a good answer in the lesson.
Type hints become JSON types, and parameters without defaults become required.
import inspect, json JSON_TYPES = {int: "integer", float: "number", str: "string", bool: "boolean", list: "array", dict: "object"} def schema_for(fn): props, required = {}, [] for name, p in inspect.signature(fn).parameters.items(): props[name] = {"type": JSON_TYPES[p.annotation]} if p.default is inspect.Parameter.empty: required.append(name) doc = inspect.getdoc(fn) or "" return {"name": fn.__name__, "description": doc.split("\n")[0], "input_schema": {"type": "object", "properties": props, "required": required}} def read_file(path: str, offset: int = 0, limit: int = 200): """Read lines from a text file in the project, starting at offset.""" print(json.dumps(schema_for(read_file), indent=2))
This is the idea behind decorators like the Python SDK's @beta_tool. Real versions also read per-parameter descriptions from the docstring and handle optional and list types.
Send three calls: one good, one missing a field, one with the wrong type. The validator's message is what the model reads.
def validate(args, schema): for name in schema["required"]: if name not in args: return f"Missing required parameter: {name}" for name, value in args.items(): want = schema["properties"][name]["type"] ok = {"integer": int, "string": str}[want] if not isinstance(value, ok): return f"{name} must be {want}, got {value!r}" return None schema = {"properties": {"path": {"type": "string"}, "offset": {"type": "integer"}}, "required": ["path"]} for call in [{"path": "a.py"}, {"offset": 3}, {"path": "a.py", "offset": "ten"}]: print(call, "->", validate(call, schema))
When a call is wrong, the error goes back as a tool_result with is_error: true, and the model reads it. So write errors the way you'd write them for a colleague: say what was wrong and what to do instead.
| unhelpful | helpful |
|---|---|
KeyError: 'sku' | Missing required parameter: sku (the product code, like TENT-2). |
Invalid input | Parameter limit should be integer, got string "fifty". |
File not found | No file src/util.py. Did you mean src/utils.py? Use glob to list files. |
Don't leak internals in errors: no stack traces, secrets or file paths outside the project.
In plain words: an error is the model's only clue about what to try next, so make it a useful clue.
Asking for one fact and getting a whole filing cabinet doesn't help anyone. A tool that returns a 2 MB log would fill the context window in one call. The registry should cap every result, say a few thousand characters, and tell the model it was cut:
...first 4000 characters... [Output truncated: showing 4000 of 182,311 characters. Narrow the search or use offset to read more.]
The note matters. It's like a book with pages torn out: without a note saying so, the model thinks it saw everything. Good tools also offer ways to ask for less: offset and limit for reads, a match cap for searches, filters for lists.
A test run can print thousands of lines, and the failure is usually near the end. Cutting from the middle keeps both the start and the part you need.
def cap(text, limit=120): if len(text) <= limit: return text keep = limit // 2 cut = len(text) - 2 * keep return f"{text[:keep]}\n[... {cut} characters cut ...]\n{text[-keep:]}" log = "\n".join(f"test_{n} passed" for n in range(500)) log += "\ntest_500 FAILED: expected 3, got 4" print("before:", len(log), "characters") capped = cap(log) print(capped) print("kept the failure:", "FAILED" in capped)
Telling the model how much was cut matters too. It can then ask for more, instead of believing it has seen everything. A cap that only keeps the first part would have lost the one line that mattered.
output = "x" * 5000 limit = 2000 print(len(output[:limit]))
2000
output[:limit] keeps the first 2000 characters, so len gives 2000. Capping tool output protects the context window from one huge result.
Write cap_lines(text, max_lines): if the text has more than max_lines lines, keep the first max_lines and add a final line ... (N more lines not shown); otherwise return it unchanged. The note tells the model the output was cut, so it doesn't assume it saw everything.
def cap_lines(text, max_lines): return "\n".join(text.splitlines()[:max_lines]) log = "\n".join(f"line {i}" for i in range(1, 8)) print(cap_lines(log, 3))
Every definition costs input tokens on every call, and long tool lists make choosing harder. Keep the set small and task-shaped.
If you need hundreds, think of a book's index: you look something up when you need it, instead of reading every page first. The Claude API's tool search tool lets you mark rarely used tools defer_loading: true. The model then searches for them when it needs them, and only those definitions load. Keep the common tools loaded; deferring everything would hide them all.
Every tool definition is sent on every call. With many tools that's a real cost, so a harness can send a short list and let the model search for the rest.
tools = [{"name": f"tool_{n}", "description": f"Does job number {n} for the shop.",
"tokens": 300} for n in range(60)]
tools[41] = {"name": "refund_order", "description": "Refund a customer's order.",
"tokens": 300}
def search(query, tools):
return [t for t in tools if query in t["description"].lower()]
everything = sum(t["tokens"] for t in tools)
found = search("refund", tools)
print("send all 60:", everything, "tokens on every call")
print("search first:", [t["name"] for t in found],
"for", sum(t["tokens"] for t in found), "tokens")That's the difference between 18,000 tokens on every turn and a few hundred. A long list also makes the model choose worse, so fewer tools can help quality as well as cost.
Otherwise the model assumes it saw everything and may miss what it needs
The note tells the model to narrow its request or page through the rest.
Write tool_error(tool, exc): return TOOL failed: TYPE: MESSAGE (the exception's class name and text), followed by Check the arguments and try again. for a ValueError, KeyError or TypeError, or This may be temporary; try once more. for anything else.
def tool_error(tool, exc): return str(exc) print(tool_error("get_campaign", KeyError("cmp_9")))
Write a sentence or two, then compare it with a good answer in the lesson.
A form can say "numbers only", and people still write letters in the box. It's easy to assume that if you gave the model a schema, its input will match. Usually it will. But the schema is guidance for the model, and your code must still check what it receives. A model can send a string where you asked for a number, leave out a required field, or invent one you never mentioned. Validate every call before you run it, and send problems back as tool errors. The API's strict mode (strict: true on the tool, with additionalProperties: false in the schema) does make the input match the schema's shape, but it can't check what a schema can't say, such as whether a path exists or is yours to change. So the check stays.
limit is an integer, and strict mode is off. What must your tool code still do?Check the input it receives: the schema is guidance for the model
Usually the input matches, and sometimes it doesn't: a string where a number belongs, a missing field. Validate it, and return an error the model can read and fix.
If a tool's output is truncated with no notice, the model believes it saw everything. It may then say "there are no failing tests" because the failures were on the part you cut. Always say what was removed and how to get more: "showing lines 1 to 200 of 4,180, use offset to read further."
What strict mode does guarantee. With strict: true the API constrains the model so its input matches the schema: right types, every required field, and no extra keys when additionalProperties is false. It still does not guarantee that a path exists, that a value makes sense or that the call is allowed. Those checks stay in your code.
Check every call before running it
A schema is guidance for the model. It can still send the wrong type, leave out a field or invent one, so validate and send problems back as tool errors.
A good office has one help desk, so you don't have to visit three windows to get one answer. Wrapping each API endpoint as a tool is quick, and it's rarely the best design. The model has to learn your API's structure, make several calls to do one thing, and hold all the intermediate data in its context. A single tool built around the task, such as find_order_status(email), does the joining in code, which is cheaper and more reliable. As a rule, if you find the model always calling the same three tools in a row, make them one.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What does a model know about a tool?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.
Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write