Agents from scratch · Chapter 2 of 18
Tools as functions
By the end of this chapter you can turn a Python function into a tool description, describe a tool's arguments with a Pydantic model, keep every tool in a registry that both describes and runs them, and write descriptions that make the model pick the right tool. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The loop
- 4 tasks
- Python
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
In chapter 1 you wrote a tool description by hand: a dictionary with a name, a sentence and a JSON Schema. GharFix's booking system has eight functions, and Vikram wants the agent to grow: warranty lookups, AC gas checks, invoice copies. Writing every schema by hand means writing everything twice. The function says technician_id: str; the schema says "technician_id": {"type": "string"}. Change one, forget the other, and the model is told about a parameter the function no longer takes.
There is a second problem. Meenakshi tried the bot on a test number and it answered "You can cancel for free up to 1 hour before the technician arrives", which is not GharFix's policy, while a perfectly good cancel tool sat in its list. The tool was there. Its description said nothing a customer would say. The model chooses tools by reading them, so a description is not documentation for you: it is the only thing the model knows about your function.
The lesson
A function already describes itself
Python keeps a function's parameters, their type hints and its docstring, and the inspect module reads them. Here is GharFix's find_technicians:
>>> import inspect, typing, gharfix
>>> sig = inspect.signature(gharfix.find_technicians)
>>> sig
<Signature (service: 'str', area: 'str', date: 'str | None' = None, slot: 'str | None' = None) -> 'list[dict] | dict'>
>>> for name, p in sig.parameters.items():
... print(name, repr(p.annotation), p.default is inspect.Parameter.empty)
...
service 'str' True
area 'str' True
date 'str | None' False
slot 'str | None' False
Everything a schema needs is there: the parameter names, a type for each, and which ones have no default (those are the required ones). Look closely at the annotations: they are the strings 'str' and 'str | None', not the class str. gharfix starts with from __future__ import annotations, which keeps hints as text until someone asks. typing.get_type_hints asks, and gives real types whichever way the module was written:
>>> typing.get_type_hints(gharfix.find_technicians)
{'service': <class 'str'>, 'area': <class 'str'>, 'date': str | None, 'slot': str | None, 'return': list[dict] | dict}
str | None means "a string, or nothing": for JSON Schema it is a string the model may leave out. typing.get_args(str | None) splits it into (str, NoneType). Python's types map onto JSON Schema's: str is "string", int is "integer", float is "number", bool is "boolean", list is "array" and dict is "object".
The docstring is the description. inspect.getdoc returns it with the indentation cleaned up, and its first line is the summary:
>>> inspect.getdoc(gharfix.find_technicians)
'GharFix technicians who do a service in an area, best rated first (at most 5).\n\nWith a date, only those with a free slot that day; with a slot too, only\nthose free in that slot.'
Build the schema from these and there is nothing to keep in step: rename a parameter and the next request says so. Task 1 writes tool_schema(fn) and compares it with gharfix.TOOLS, which Vikram's team wrote by hand. The parameters should match exactly. The descriptions will not, and that is worth a look: the docstrings were written for programmers, the hand-written descriptions for the model.
Arguments as a Pydantic model
A type hint says "string". A slot is not any string: it is morning, afternoon or evening, and a booking takes no keys it does not know. JSON Schema can say both, with enum and additionalProperties: false, and a Pydantic model writes that schema for you. Here is one for reschedule_booking's arguments:
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class RescheduleArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
booking_id: str = Field(description="The booking ID: GF and 6 digits")
date: str = Field(description="The new date, YYYY-MM-DD")
slot: Literal["morning", "afternoon", "evening"]
>>> RescheduleArgs.model_json_schema()
{'additionalProperties': False, 'properties': {'booking_id': {'description': 'The booking ID: GF and 6 digits', 'title': 'Booking Id', 'type': 'string'}, 'date': {'description': 'The new date, YYYY-MM-DD', 'title': 'Date', 'type': 'string'}, 'slot': {'enum': ['morning', 'afternoon', 'evening'], 'title': 'Slot', 'type': 'string'}}, 'required': ['booking_id', 'date', 'slot'], 'title': 'RescheduleArgs', 'type': 'object'}
Literal[...]becomes anenum: the model is told the only values it may write.Field(description=...)becomes the parameter's description, which the model reads to fill it.extra="forbid"becomesadditionalProperties: false.- A field with no default is required. (
titlekeys are harmless.)
The same model then checks what comes back. The model's arguments arrive as JSON text, and model_validate_json parses and validates them in one go:
from pydantic import ValidationError
for text in ['{"booking_id":"GF318075","date":"2026-10-25","slot":"night"}',
'{"booking_id":"GF318075","date":"2026-10-25","slot":"evening","fee":0}']:
try:
RescheduleArgs.model_validate_json(text)
except ValidationError as e:
print(e)
1 validation error for RescheduleArgs
slot
Input should be 'morning', 'afternoon' or 'evening' [type=literal_error, input_value='night', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/literal_error
1 validation error for RescheduleArgs
fee
Extra inputs are not permitted [type=extra_forbidden, input_value=0, input_type=int]
For further information visit https://errors.pydantic.dev/2.14/v/extra_forbidden
A good answer gives you an object, and .model_dump() turns it back into a dictionary for the function: {'booking_id': 'GF318075', 'date': '2026-10-25', 'slot': 'evening'}. One class describes the arguments to the model and checks them on the way back; chapter 7 builds the whole validator on it. Task 2 writes the model for book_slot, GharFix's biggest tool.
A registry: describe and run, in one place
An agent needs two things for every tool: the description to send and the function to run when the model asks for it by name. In chapter 1 those were two separate things, gharfix.TOOLS and gharfix.FUNCTIONS, kept in step by hand. A registry keeps both, filled by one line per tool. A decorator is the natural way to write that line: it receives the function, records it, and hands it back unchanged, so the function still works as a function:
TOOLS = []
def tool(fn):
TOOLS.append(tool_schema(fn))
return fn
@tool
def get_booking(booking_id: str) -> dict:
"""Look up a GharFix booking by its booking ID."""
return gharfix.get_booking(booking_id)
@tool above a def means get_booking = tool(get_booking): the decorator runs once, when the function is defined. Your own wrapper around a gharfix function is also where you choose what the model sees: its docstring becomes the description, and its parameters can be fewer than gharfix's. Task 3 turns this into a Registry class that also runs a call: given the name and the arguments text the model wrote, it finds the function and returns the result as JSON text, ready for a tool message.
Descriptions steer the model
The model never sees your code. It sees a name, a sentence and the parameters, and picks the tool whose description best matches what the customer wrote. Two tools with lazy descriptions, rates ("Rates.") and people ("People."), and the same two with descriptions written for a reader (temperature=0):
rates / people
How much does a tap repair cost? -> Most repairs start at ₹199, and AC service is ₹399.
Who can come to Whitefield to fix a leaking pipe? -> Our technician reaches you within 60 minutes of booking, any time of the day.
get_quote: "Get the price of a job from the rate card."
find_technicians: "Find technicians who do a service in an area."
How much does a tap repair cost? -> get_quote({"job":"tap-repair"})
Who can come to Whitefield to fix a leaking pipe? -> find_technicians({"service":"plumbing","area":"Whitefield"})
With lazy descriptions the model found no tool that fit, so it answered from training: both answers are wrong for GharFix (a tap repair is ₹249, and nobody promises 60 minutes). Nothing crashed, which is what makes it dangerous. The lab model matches the words of a description against the customer's message. Real models understand meaning far better, but they fail the same way when two descriptions are vague or alike: they guess. So write descriptions the way you would brief a new colleague:
- Start with a verb and say what the tool does: "Find", "Cancel", "Get the price of".
- Use the customer's words for what it is for: "how much", "price", "who can come".
- Make two tools different: if a person could not tell them apart from the descriptions, neither can a model.
- Describe each parameter: "GF and 6 digits", "YYYY-MM-DD".
Your turn
Task 1 builds tool_schema(fn) from a function's signature, hints and docstring (careful with gharfix's hints: they are strings). Task 2 is book_slot's arguments as a Pydantic model, used for a real booking, and task 3 the registry. The interview question hands you two tools whose descriptions say almost nothing, and six customers they fail.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
schema.py: a tool description from a function
Vikram wants every tool description built from the function it describes. Write tool_schema(fn) in schema.py. It returns the tool description of a Python function, as a dictionary in the shape of one item of gharfix.TOOLS:
type is function; the function's name is fn's name; its description is the first line of fn's docstring; its parameters are a JSON Schema object with one property per parameter of fn, each with its type, a required list of the parameters that have no default (in the function's order), and additionalProperties set to False.
Types: str is string, int is integer, float is number, bool is boolean, list is array, dict is object. A hint like str | None is the type of its non-None part.
The check runs tool_schema on every function in gharfix.FUNCTIONS and compares names, parameters, types and required lists with gharfix.TOOLS, then on functions of its own with int, float, bool and list parameters and defaults.
- Task 2
booking_args.py: book_slot's arguments in Pydantic
In booking_args.py, write a Pydantic model BookSlotArgs for book_slot's seven arguments: technician_id, date, slot, job, area, customer_name and phone, all text and all required. slot may only be morning, afternoon or evening; give every field a description; and forbid keys the model does not have.
Then make BOOK_SLOT_TOOL, a tool description named book_slot with a one-sentence description, whose parameters are BookSlotArgs's JSON Schema.
When the file is run (python3 booking_args.py), send lab-chat a system message saying it is GharFix's booking assistant and that today is 2026-10-22, the user's message, exactly:
Book T29 for a door lock change in Indiranagar on 27 Oct, afternoon. I am Kavya Iyer, phone 9900112233.
and BOOK_SLOT_TOOL as the only tool. Validate the arguments of the call the model asks for with BookSlotArgs, book the slot with gharfix.book_slot and those arguments, and print one line: the new booking's ID, a space, and its status.
- Task 3
registry.py: a registry of tools
Write a class Registry in registry.py. Its tool method is a decorator: it records the function under its name, with its description from tool_schema (import it from schema.py), and returns the function unchanged. schemas() returns the list of recorded tool descriptions, in the order the tools were added. run(name, arguments) takes a tool's name and its arguments as JSON text, runs that function with them, and returns the result as JSON text.
Make a module-level registry with two tools of your own: get_quote(job) and find_technicians(service, area), each with a docstring written for the model, each returning what gharfix's function of the same name returns.
When the file is run, send lab-chat the same system message as task 2 and the user's message, exactly:
How much is a geyser repair, and who can come to Hebbal?
with registry.schemas() as the tools. Run every call the model asks for with registry.run, send the results back, and print only the text of the model's final answer.
- Task 4 · interview question
Interview: pick_right.py, two tools the model confuses
pick_right.py offers lab-chat two tools, gf_lookup (it will run gharfix.get_booking) and gf_close (it will run gharfix.cancel_booking), and prints which tool the model picks for each of six customer messages. Their descriptions say almost nothing, and the model gets five of the six wrong: it picks the wrong tool, or answers from its training.
Rewrite the two tools' descriptions (and their parameter's description) so that lab-chat picks gf_lookup for the three questions about a booking's status, and gf_close for the three cancellations. Keep the names, the one required parameter booking_id, the six messages and what the program prints.
What you will learn
- Reading a function: its parameters, type hints and docstring, with inspect and typing.
- A tool description from a function, so the code is the only source.
- Arguments as a Pydantic model: enums, field descriptions and no extra keys, straight from model_json_schema().
- A registry: one object that knows each tool's description and runs it by name.
- Descriptions that steer the model to the right tool.
More in The loop
Build "Tools as functions" yourself
GharFix, a Bengaluru home-services company, needs an assistant that books, reschedules and refunds safely. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.