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.
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.
Unvalidated LLM arguments crash backend functions or pass wrong types; schema validation + safe dispatch is the bridge between language and reliable software execution.
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!
Anthropic famously spent more time refining their SWE-bench Agent-Computer Interface (ACI) (tool docstrings, parameter formats, error messages) than tweaking the prompt itself!
Never trust raw LLM arguments: even with strict: true, business-logic invariants (date ranges, positive amounts, tenant permissions) MUST be validated inside your dispatcher!
Core Agentic AI coding question: 'Implement a safe Tool Call Dispatcher with allowlisted lookup, required/type validation, exception catching, and structured observations!'
What is the #1 rule when mapping an LLM's emitted tool_name string to executable code in your backend?
- 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
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
Click "open", "shipped", and invalid "pending" in the mini-lab below to see how strict enum validation catches hallucinated arguments BEFORE touching your database!
4 Rules for Bulletproof Tool Schemas
- Use
enumrelentlessly for any finite choice (["open", "shipped"]) so the LLM cannot invent synonyms. - Include exact format examples inside descriptions (
"ISO date, e.g. 2026-12-03"). - Cap output sizes (
limit: int = 10) so a single tool call never dumps 50,000 rows into the context window! - Enable
strict: truewhenever your LLM provider supports FSM Constrained Decoding on tool calls.
Allowlisted Tool Argument Validator (`enum: ["open", "shipped"]`)
2. Safe Allowlisted Tool Dispatch Pipeline
Every tool invocation flows through 5 deterministic stages: Proposal → Allowlist → Validation → Sandboxed Execution → Structured Envelope.
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
Spend as much engineering care on your ACI (how the Agent interacts with tools) as you do on your human UI!
Poka-Yoke (Mistake-Proofing) Tips
- Prefer absolute file paths over relative paths (agents forget
cdstate!). - 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!
Worked Example: Handling a Hallucinated Tool Name Gracefully
Registry has ['get_order', 'refund_order']. LLM hallucinates fetch_order(id='ORD-9').
TOOL_REGISTRY.get('fetch_order') returns None — zero crash!
What should your Tool Dispatcher do if the LLM emits a tool name that is NOT in your TOOL_REGISTRY?
Why should a tool return "... [truncated, showing top 20 of 4,200 rows; add a filter]" instead of returning all 4,200 SQL rows?
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!
Safe Tool-Call Registry & Schema Dispatch Pipeline
Trace an LLM tool call through allowlist lookup, strict Pydantic validation, and structured observation return.
{ok, data, error} envelopes.Enterprise CRM, SQL & Ticketing Agents
Strict allowlisted dispatchers enforce RBAC permissions and schema validation on every database or API call.
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"}))
user_id or tenant_id supplied by the LLM inside tool arguments!user_id / tenant_id from your authenticated server session, NEVER from LLM-generated arguments (prevents cross-tenant data leaks via prompt injection)!tenant_id / user_id come from when executing a database tool call?