Course
AI · Module 06: Tool Calling, MCP & AI AgentsTutorial 16 of 21
AI Course·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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:

KEY MENTAL MODEL: THE LLM NEVER CALLS YOUR API — YOUR SERVER DOES!1. SEND SCHEMASApp sends prompt + JSON tool definitions2. EMIT INTENTLLM pauses & outputs tool_call(name, args)3. RUN DETERMINISTICYOUR code validates ACL & runs SQL/HTTP4. FINAL ANSWERApp appends tool_result -> LLM replies!
Figure: An LLM only emits a structured JSON intent (`stop_reason: "tool_use"`) — your backend owns credentials, validation, and execution.
  1. Advertise Schemas: Your server sends the user message plus an array of JSON Schema tool definitions (get_order_status, lookup_weather).
  2. Model Emits Intent & Pauses: Instead of replying with prose, the LLM halts with stop_reason = "tool_use" (or tool_calls) and outputs a structured JSON payload: {"call_id": "call_91", "name": "get_order_status", "arguments": {"order_id": "ord_42"}}.
  3. Your Backend Validates & Executes: Your Python/TypeScript code verifies the caller's session permissions, calls your real database/microservice, and serializes the result.
  4. Feed tool_result Back → Final Answer: Your server appends both the assistant's tool_call message and a matching tool_result (call_id: "call_91") to messages[] 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:

  1. 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.
  2. 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.5s latency!). Expose one get_customer_billing_overview(email: str) tool (1 round-trip = 0.8s)!
  3. Cap Tool Count (<= 15–20 Active Tools Per Turn): Passing 90 tool schemas burns 18,000 input tokens on every turn and drops tool-selection accuracy! Use an intent router to inject only the relevant tool group.
  4. Return Actionable Error Strings — Never Crash the Loop! If the model passes an invalid date "11/27/26", catch the ValueError and return "Error: expected YYYY-MM-DD format (e.g. 2026-11-27)" as the tool_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!

Tracing Parallel Tool Execution & call_id Correlation
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. LLM Emits Multiple Parallel Tool Intents)
Wire Telemetry:in=280 tokout=36 toklatency=390ms
1→resp1 = await llm(messages, tools=[WEATHER_TOOL])
2→# Model emits 2 tool_calls in ONE turn: call_A (Bengaluru), call_B (Tokyo)
3results = await asyncio.gather(*[run_tool(tc) for tc in resp1.tool_calls])
4messages += [resp1.assistant_msg, *format_tool_results(results)]
5resp2 = await llm(messages, tools=[WEATHER_TOOL]) # Final answer!
Assistant Turn #1 (`tool_calls`)2 PARALLEL CALLS
[{"id": "call_A", "name": "get_weather", "args": {"city": "Bengaluru"}},
 {"id": "call_B", "name": "get_weather", "args": {"city": "Tokyo"}}]
What's Happening: Instead of 2 sequential LLM turns, the model requests both cities simultaneously, each tagged with a unique correlation ID (`call_A`, `call_B`).

4. Production SDK Code: Complete Tool Loop Across OpenAI, Gemini, Claude & TS

SDK:
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)

  1. Tool Output Context Bombs (500 KB SQL/API Dump): A tool list_github_commits() returns 400 raw commit objects (180,000 tokens!) and immediately blows past the context window! Always paginate/cap tool return sizes (limit=20, max 6,000 chars) and add a hint telling the model how to filter narrower.
  2. Missing tool_result Breaking Chat State Forever: If an unhandled exception crashes your backend after saving the assistant's tool_use turn to your database but before saving a matching tool_result, every future message in that chat session will fail with 400 Bad Request (tool_use ids were found without tool_result blocks)! Always wrap tool execution in try / except so even crashes emit an is_error: True tool_result!
  3. Enabling "strict": True Without additionalProperties: False: OpenAI's Constrained Tool Calling requires "additionalProperties": False and every property listed in "required" (use Pydantic helpers to generate this automatically!).

Module 6.1 Mastery Check — Function & Tool Calling

Q1.When an LLM 'calls a tool' like `query_postgres(sql)`, where does the SQL query actually execute?
Q2.What happens on the next API call if an assistant message contains 2 `tool_use` blocks (`call_1` and `call_2`), and your code only sends back a `tool_result` for `call_1`?
Q3.What is the best practice when a tool receives an invalid argument format (e.g., wrong date format) from the LLM?
Q4.Why should you prefer 1 coarse-grained business tool (`get_customer_billing_summary(email)`) over 4 tiny low-level CRUD endpoints?

Keep Exploring: Related Lessons & Tools

All Courses →