6.1 Function & Tool Calling: The Wire-Level Execution Loop
Demystify how LLMs query databases, hit APIs, and trigger actions: trace the exact 4-step tool-calling wire handshake, execute parallel tool calls, and design 'poka-yoke' tool schemas models never misuse.
1. The #1 Mental Model: The LLM Never Calls Your Function!
Beginners imagine OpenAI or Anthropic servers reaching across the internet to call their private PostgreSQL database. That never happens. An LLM has no network socket to your backend!
Tool Calling is simply a 4-step structured JSON handshake orchestrated 100% by your server:
- Advertise Schemas: Your server sends the user message plus an array of JSON Schema tool definitions (
get_order_status,lookup_weather). - Model Emits Intent & Pauses: Instead of replying with prose, the LLM halts with
stop_reason = "tool_use"(ortool_calls) and outputs a structured JSON payload:{"call_id": "call_91", "name": "get_order_status", "arguments": {"order_id": "ord_42"}}. - Your Backend Validates & Executes: Your Python/TypeScript code verifies the caller's session permissions, calls your real database/microservice, and serializes the result.
- Feed
tool_resultBack → Final Answer: Your server appends both the assistant'stool_callmessage and a matchingtool_result(call_id: "call_91") tomessages[]and calls the LLM a second time to synthesize the human-facing reply!
2. Four Rules for Designing "Poka-Yoke" (Mistake-Proof) Tools
Anthropic's engineering team found while building SWE-bench coding agents that spending more time polishing tool docstrings & parameter schemas beat prompt tweaking every single time:
- Write Docstrings Like You're Onboarding a Junior Engineer: State when to call the tool, when NOT to call it, exact parameter formats (
ISO-8601 YYYY-MM-DD), and what the return payload contains. - Consolidate Chatty Micro-Tools Into Coarse Business Tools: Don't expose
get_user_id_by_email+get_subscriptions_by_uid+get_invoices_by_sub_id(forcing 3 sequential LLM round-trips =4.5slatency!). Expose oneget_customer_billing_overview(email: str)tool (1round-trip =0.8s)! - Cap Tool Count (
<= 15–20Active Tools Per Turn): Passing 90 tool schemas burns18,000input tokens on every turn and drops tool-selection accuracy! Use an intent router to inject only the relevant tool group. - Return Actionable Error Strings — Never Crash the Loop! If the model passes an invalid date
"11/27/26", catch theValueErrorand return"Error: expected YYYY-MM-DD format (e.g. 2026-11-27)"as thetool_result! Models self-correct syntax errors on the next turn 95%+ of the time when given a clear error message!
3. Parallel Tool Calling (Slashing Multi-Lookup Latency)
When a user asks "Compare current weather in Bengaluru, Tokyo, and London", modern models emit all 3 tool_call blocks in ONE single turn! Execute them concurrently with asyncio.gather / Promise.all and append all 3 tool_result blocks (matched by call_id) before calling the LLM again!
[{"id": "call_A", "name": "get_weather", "args": {"city": "Bengaluru"}},
{"id": "call_B", "name": "get_weather", "args": {"city": "Tokyo"}}]4. Production SDK Code: Complete Tool Loop Across OpenAI, Gemini, Claude & TS
import json
from openai import OpenAI
client = OpenAI()
TOOLS = [{
"type": "function",
"name": "get_order_status",
"description": "Fetch live shipping status for a verified order ID (e.g. ord_104).",
"strict": True, # Constrained Decoding on tool arguments!
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
"additionalProperties": False,
},
}]
def lookup_order_db(order_id: str) -> dict:
return {"order_id": order_id, "status": "out_for_delivery", "eta": "Today 6 PM"}
input_list = [{"role": "user", "content": "Where is order ord_104?"}]
resp = client.responses.create(model="gpt-4o-mini", tools=TOOLS, input=input_list)
input_list += resp.output # Preserve exact model tool_call items!
for item in resp.output:
if item.type == "function_call":
args = json.loads(item.arguments)
result = lookup_order_db(args["order_id"])
input_list.append({
"type": "function_call_output",
"call_id": item.call_id,
"output": json.dumps(result),
})
final = client.responses.create(model="gpt-4o-mini", tools=TOOLS, input=input_list)
print(final.output_text)5. What Breaks in Production (War Stories)
- Tool Output Context Bombs (
500 KBSQL/API Dump): A toollist_github_commits()returns 400 raw commit objects (180,000tokens!) and immediately blows past the context window! Always paginate/cap tool return sizes (limit=20, max6,000chars) and add a hint telling the model how to filter narrower. - Missing
tool_resultBreaking Chat State Forever: If an unhandled exception crashes your backend after saving the assistant'stool_useturn to your database but before saving a matchingtool_result, every future message in that chat session will fail with400 Bad Request(tool_use ids were found without tool_result blocks)! Always wrap tool execution intry / exceptso even crashes emit anis_error: Truetool_result! - Enabling
"strict": TrueWithoutadditionalProperties: False: OpenAI's Constrained Tool Calling requires"additionalProperties": Falseand every property listed in"required"(use Pydantic helpers to generate this automatically!).
Module 6.1 Mastery Check — Function & Tool Calling
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.