Intermediate level · Module 3: Agent Tools and Function Calling · Lesson 2 of 3
A Safe Function-Calling Loop
Learners implement the loop: the model requests a tool, the program checks the allow-list, validates arguments, runs the tool with a timeout, returns the result, and limits the number of steps.
In this lesson you will
- Implement an allow-listed tool dispatcher
- Handle invalid tool calls safely
Key concepts
tool calldispatcherallow-listargument validationstep limit
The lesson
The program, not the model, decides what runs. A dispatcher looks the tool name up in an allow-list (a dictionary of permitted functions); anything else is refused. Arguments are parsed and validated before the call.
Errors are returned to the model as tool results ('tool not allowed', 'bad arguments: ...') so that it can correct itself, rather than crashing the agent. Each tool call has a timeout, and the loop has a maximum number of steps.
Every call, allowed or refused, is logged with its arguments and outcome. Refused calls are a useful signal of confused or manipulated agents.
Step by step
- Implement dispatch(tool_call) with an allow-list.
- Validate arguments with the Pydantic models.
- Add a timeout and a step limit to the loop.
- Test with valid, unknown and malformed tool calls from the scripted model.
An allow-listed tool dispatcher with a read-only course lookup
The program, not the model, decides which tools run: an allowed lookup succeeds, an unlisted write tool is refused and bad arguments are reported back.
import jsonimport sqlite3 # Fictional course data (in a real deployment: sqlite3.connect("file:courses.db?mode=ro", uri=True))db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE courses (code TEXT, name TEXT, level TEXT, weeks INTEGER, seats_left INTEGER);INSERT INTO courses VALUES ('PY-B', 'Python', 'Beginner', 4, 6), ('PY-I', 'Python', 'Intermediate', 8, 0), ('DA-B', 'Data Analytics', 'Beginner', 4, 12);""") def search_courses(name: str) -> list[dict]: """Read-only: the levels of one course and the seats left.""" rows = db.execute( "SELECT code, level, weeks, seats_left FROM courses WHERE name = ? ORDER BY weeks", (name,), # parameterised: never build SQL from model text ).fetchall() return [{"code": c, "level": l, "weeks": w, "seats_left": s} for c, l, w, s in rows] TOOLS = {"search_courses": search_courses} # allow-list: the only tool the agent may call def dispatch(tool_call: dict) -> dict: name = tool_call["name"] if name not in TOOLS: return {"error": f"tool '{name}' is not allowed"} args = json.loads(tool_call["arguments"]) try: return {"result": TOOLS[name](**args)} except TypeError as exc: return {"error": f"bad arguments: {exc}"} # Tool calls as a model might request them (scripted, so the output is repeatable)calls = [ {"name": "search_courses", "arguments": '{"name": "Python"}'}, {"name": "update_seats", "arguments": '{"code": "PY-I", "seats_left": 5}'}, {"name": "search_courses", "arguments": '{"course": "Python"}'},]for call in calls: print(call["name"], "->", dispatch(call))
Output
search_courses -> {'result': [{'code': 'PY-B', 'level': 'Beginner', 'weeks': 4, 'seats_left': 6}, {'code': 'PY-I', 'level': 'Intermediate', 'weeks': 8, 'seats_left': 0}]}
update_seats -> {'error': "tool 'update_seats' is not allowed"}
search_courses -> {'error': "bad arguments: search_courses() got an unexpected keyword argument 'course'"}How it works
The model only proposes tool calls; dispatch() decides. The first call is on the allow-list and returns the Python course's two levels, using a parameterised query, so the model's text never becomes SQL. The second call asks for update_seats, a write action that was never registered, so it is refused, even if a manipulated document had persuaded the model to request it. The third call uses the wrong argument name; instead of crashing, the error goes back to the model so that it can correct the call. In a real deployment, the database connection itself would also be read-only (mode=ro), so even a coding mistake could not change data. That is two independent layers of least privilege. Every call, allowed or refused, would also be written to the audit log.
Key concepts
allow-listread-only, parameterised querieserrors returned to the modeldefence in depthleast privilege
Practice activity
Implement and test the project's function-calling loop.
Expected result: A loop that runs allowed tools, refuses others, reports bad arguments and stops at the step limit.
Check your understanding
-
What does an allow-list do?
Show answer
It lists the only tools the agent is permitted to call; anything else is refused.
-
Why return errors to the model rather than crashing?
Show answer
So that the model can correct its request, while the program stays in control.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.