Chapter 7 of 32 · ~22 min read & lab+80 XP
Chapter 7 · Agentic AI

LLM Function Calling: JSON Tool Schemas, Argument Validation & Dispatch

How LLMs invoke real Python functions safely: crafting high-signal JSON Tool Schemas (ACI design), allowlisted registry dispatch without eval(), strict Pydantic argument validation, and structured {ok, data, error} envelopes.

What Is It?

Function Calling lets an LLM emit structured JSON tool requests matching a strict parameter schema, which your runtime validates and dispatches to real Python/API functions.

Why Is It Required?

Unvalidated LLM arguments crash backend functions or pass wrong types; schema validation + safe dispatch is the bridge between language and reliable software execution.

Everyday Analogy: A waiter writing orders onto a standardized kitchen ticket with checked boxes so the chef never misreads a dish.
Why ML Engineers & Data Scientists Actually Need This

Tool Calling is what turns an LLM from a chatbot that talks into an agent that acts — and 80% of agent failures come from sloppy tool schemas!

ML / AI Engineer

Anthropic famously spent more time refining their SWE-bench Agent-Computer Interface (ACI) (tool docstrings, parameter formats, error messages) than tweaking the prompt itself!

Data Scientist

Never trust raw LLM arguments: even with strict: true, business-logic invariants (date ranges, positive amounts, tenant permissions) MUST be validated inside your dispatcher!

Interview & Debug Edge

Core Agentic AI coding question: 'Implement a safe Tool Call Dispatcher with allowlisted lookup, required/type validation, exception catching, and structured observations!'

Step 0 · Test Your Gut Before Any Math!

What is the #1 rule when mapping an LLM's emitted tool_name string to executable code in your backend?

What You Will Master in This Chapter
  • Author unambiguous JSON Tool Schemas using explicit parameter types, enums, format examples ('YYYY-MM-DD'), and required arrays
  • Implement a safe Allowlisted Tool Dispatcher (TOOLS.get(name)) that validates arguments before invoking any function
  • Apply Agent-Computer Interface (ACI / Poka-Yoke) principles to prevent tool-calling mistakes by design
  • Return consistent structured JSON envelopes ({ok, data, error}) so the LLM recovers cleanly from unknown tools or bad arguments
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Tool Schema\text{Tool Schema}Say aloud:“JSON function specification”
Plain-English Meaning
Typed JSON contract describing a tool's name, purpose, parameters, enums, and required keys
Everyday Example
status: {enum: ['open', 'shipped']}
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of a Tool Schema like a restaurant menu with clear checkboxes: if you just hand a customer a blank piece of paper (query_db(q)), they will order things that don't exist! Giving them crisp checkboxes (status ∈ ['open', 'shipped'], since: 'YYYY-MM-DD') and a polite waiter (Allowlisted Dispatcher) who checks the order before sending it to the kitchen eliminates 90% of kitchen errors!

1. Anatomy of a High-Signal JSON Tool Schema

Everyday Story First (Zero Math Yet!)

Click "open", "shipped", and invalid "pending" in the mini-lab below to see how strict enum validation catches hallucinated arguments BEFORE touching your database!

Anatomy of a Production Function-Calling JSON Tool Schema"name": "search_orders","description": "Find orders by status & date","parameters": {"status": {"enum": ["open","shipped"]},"since": {"type":"string","desc":"YYYY-MM-DD"}}, "required": ["status"]Why Each Field Matters• enum: prevents invented values ("pending")• format hint: stops "yesterday" vs "2026-12-03"• required: enforces mandatory args upfront• strict: true → FSM-enforced schema ✓
A Tool Schema is a typed JSON contract (name, clear description, parameter types, enums, and required fields) that teaches the LLM exactly HOW and WHEN to invoke your Python function!

4 Rules for Bulletproof Tool Schemas

  1. Use enum relentlessly for any finite choice (["open", "shipped"]) so the LLM cannot invent synonyms.
  2. Include exact format examples inside descriptions ("ISO date, e.g. 2026-12-03").
  3. Cap output sizes (limit: int = 10) so a single tool call never dumps 50,000 rows into the context window!
  4. Enable strict: true whenever your LLM provider supports FSM Constrained Decoding on tool calls.
Animated Mini-Lab • 2.1

Allowlisted Tool Argument Validator (`enum: ["open", "shipped"]`)

PASS ✓ Dispatching search_orders(status="open")

2. Safe Allowlisted Tool Dispatch Pipeline

Everyday Story First (Zero Math Yet!)

Every tool invocation flows through 5 deterministic stages: Proposal → Allowlist → Validation → Sandboxed Execution → Structured Envelope.

Safe Allowlisted Tool Dispatch Pipeline (Zero eval()!)1. LLM Call{name, args}2. AllowlistTOOLS.get(name)3. ValidatePydantic schema4. ExecuteTimeout + sandbox5. Envelope{ok, data, err}
Safe Tool Dispatch NEVER executes raw LLM strings with eval(): it looks up an allowlisted registry, validates arguments with Pydantic/JSON Schema, executes in a sandbox, and returns structured JSON.

Dispatcher Pattern in 10 Lines of Python

def dispatch_tool(name: str, args: dict) -> dict:
    spec = TOOL_REGISTRY.get(name)
    if not spec:
        return {"ok": False, "error": f"Unknown tool '{name}'. Available: {list(TOOL_REGISTRY)}"}
    try:
        validated = spec.schema(**args)
        return {"ok": True, "data": spec.fn(validated)}
    except Exception as e:
        return {"ok": False, "error": f"Tool error: {e}"}

3. Agent-Computer Interface (ACI) Design

Everyday Story First (Zero Math Yet!)

Spend as much engineering care on your ACI (how the Agent interacts with tools) as you do on your human UI!

Agent-Computer Interface (ACI): Bad vs. High-Signal Tool DesignVague Tool (High Error Rate ✗)query_db(q: str) # "Query DB"• No table names, no row cap, raw SQL risk• Returns 50,000 rows → blows context window!Poka-Yoke ACI Tool (99% Reliable ✓)get_order(order_id: str, limit: int = 10)• Clear doc + example ID "ORD-1234"• Built-in truncation & pagination hint!
Agent-Computer Interface (ACI) design matters as much as UI design: crystal-clear parameter descriptions, enums, and format examples ('YYYY-MM-DD') slash tool-calling errors by 50%+!

Poka-Yoke (Mistake-Proofing) Tips

  • Prefer absolute file paths over relative paths (agents forget cd state!).
  • Return concise, high-signal observations (strip HTML boilerplate, truncate huge logs with "... [truncated, 420 more lines]").
  • Keep tool count lean (5–15 tools max per agent); if you have 100 tools, use an Intent Router or dynamic Tool Search first!
Walk Through With Me · Interactive Worked Example

Worked Example: Handling a Hallucinated Tool Name Gracefully

Registry has ['get_order', 'refund_order']. LLM hallucinates fetch_order(id='ORD-9').

11. Allowlist lookup missesStep 1 / 2

TOOL_REGISTRY.get('fetch_order') returns None — zero crash!

Teacher's Note: Never raise an uncaught KeyError to the end user!
Pause & Check · Quick Intuition Pulse

What should your Tool Dispatcher do if the LLM emits a tool name that is NOT in your TOOL_REGISTRY?

Try It YourselfStandard

Why should a tool return "... [truncated, showing top 20 of 4,200 rows; add a filter]" instead of returning all 4,200 SQL rows?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Your API call passes the tools=[...] JSON Schema array alongside messages[]. The LLM provider serializes those schemas into the System Prompt using the model's native tool-calling template!

Interactive Visual Lab
Lab Challenge: Trace all 4 stages of the 60 FPS Tool-Call Registry & Schema Dispatch Pipeline.
Interactive Animation • 2.1 Deep Lab

Safe Tool-Call Registry & Schema Dispatch Pipeline

Trace an LLM tool call through allowlist lookup, strict Pydantic validation, and structured observation return.

Stage 1 / 4
1. LLM Emits Tool Call
{"name": "get_order", "args": {"order_id": "ORD-402"}}
2. Allowlist Registry Lookup
TOOLS['get_order'] found ✓ (eval() never used!)
3. Pydantic Schema Validation
order_id: str matches ^ORD-\d+$ ✓
4. Sandboxed Execution → JSON
{"ok": true, "status": "shipped", "eta": "2026-12-05"} ✓
0%
1. LLM Emits Tool Call
Intuition Takeaway: Safe Function Calling pairs Poka-Yoke JSON Schemas (enums, formats, row caps) with an Allowlisted Validating Dispatcher that injects auth server-side and returns clean {ok, data, error} envelopes.
Where This Powers Real ML, Deep Learning & Generative AI

Enterprise CRM, SQL & Ticketing Agents

Strict allowlisted dispatchers enforce RBAC permissions and schema validation on every database or API call.

Production NumPy & PyTorch Code Patterns
from typing import Any, Callable

# Strict Tool Schema Registry, Argument Validation & Safe Dispatch
SCHEMA = {
    "get_weather": {
        "required": {"city": str, "unit": str},
        "fn": lambda city, unit="celsius": f"{city}: 22°{unit[0].upper()}",
    }
}

def dispatch_tool(name: str, args: dict[str, Any]) -> dict[str, Any]:
    spec = SCHEMA.get(name)
    if not spec:
        return {"ok": False, "error": f"Unknown tool: {name}"}
    for field, expected_type in spec["required"].items():
        if field not in args or not isinstance(args[field], expected_type):
            return {"ok": False, "error": f"Invalid or missing '{field}' ({expected_type.__name__})"}
    fn: Callable = spec["fn"]
    return {"ok": True, "result": fn(**args)}

print(dispatch_tool("get_weather", {"city": "Tokyo", "unit": "celsius"}))
print(dispatch_tool("get_weather", {"city": 123, "unit": "celsius"}))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Trusting user_id or tenant_id supplied by the LLM inside tool arguments!
Best Practice: ALWAYS inject user_id / tenant_id from your authenticated server session, NEVER from LLM-generated arguments (prevents cross-tenant data leaks via prompt injection)!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1In a multi-tenant AI app, where should tenant_id / user_id come from when executing a database tool call?

Apply What You Learned — Solve Matching Coding Problems