Chapter 9 of 13
Course Progress0 of 13 completed (0%)

Generative AI & LLM Engineering · Chapter 9 · ~20 min · Hands-on Interactive

Tool Use, Function Calling & ReAct Agents

LLMs are fundamentally isolated text engines — they have no eyes, no calendar access, and no database connection. Tool calling is the bridge that lets an LLM execute code, query live APIs, and interact with the world. Learn how tools work, how to build multi-turn ReAct agents, and how to guard against unintended actions.

  • The 4-step tool calling round-trip
  • Defining robust JSON schemas with strict validation
  • The ReAct loop: Reason, Act & Observe
  • Parallel tool dispatch & Human-in-the-Loop guardrails

1The Core Mechanism: What Tool Calling Actually Is

A common misconception is that the model itself runs Python code, visits websites, or executes database queries. It does not. The LLM only ever outputs tokens.

When tool calling is enabled, the model is trained to pause text generation when it spots an information gap and instead emit a structured tool_calls JSON payload naming a function and its arguments. Your application runs the real code, then feeds the result back to the model.

The Tool-Calling 4-Step Round Trip

Watch how the model pauses, issues a function call, and waits for your app to execute real code.

User → LLM APIStep 1 of 4
User Submits Natural Language Request

The user asks for live weather in Tokyo. The LLM has no internet access and its training data has a cutoff — it cannot know right now's weather from weights alone.

[
  { "role": "user", "content": "What is the weather in Tokyo right now, and should I bring an umbrella?" }
]
Step 1 of 4
Concept Check

Who actually executes the code when an LLM requests a tool call like 'search_google'?

2JSON Schema: Teaching the LLM What Tools Exist

How does the model know what functions are available and what parameters they require? When you make an API request (e.g. OpenAI or Anthropic), you pass an array of tools defined as JSON Schema.

Parameter descriptions act as instructions to the model. A vague description like "query": "string" often leads to malformed inputs, whereas "query": "ISO 8601 formatted date e.g. 2026-11-15" guarantees clean extraction.

JSON Schema Tool Definition & Argument Extractor

The model never guesses what tools do randomly — it reads parameter descriptions and schemas you pass in the request.

Tool Registration JSON Schemastrict: true
{
  "name": "create_calendar_event",
  "description": "Create an appointment on Google Calendar with title, ISO start time, and attendees list.",
  "parameters": {
    "type": "object",
    "properties": {
      "title": {
        "type": "string",
        "description": "Title of the calendar invite"
      },
      "start_iso": {
        "type": "string",
        "description": "Start time formatted as ISO 8601 (e.g. 2026-11-15T14:00:00Z)"
      },
      "duration_minutes": {
        "type": "integer",
        "description": "Duration in minutes, default 30"
      },
      "attendees": {
        "type": "array",
        "description": "List of email addresses to invite"
      }
    },
    "required": [
      "title",
      "start_iso"
    ]
  }
}
Model Parameter ExtractionSelect user input:
Extracted Function Arguments:
{
  "title": "Architecture Review",
  "start_iso": "2026-11-15T15:00:00Z",
  "duration_minutes": 45,
  "attendees": [
    "dev@company.com"
  ]
}
Matches schema types & required fields precisely without code execution errors.
Concept Check

Why are tool and parameter descriptions critical when registering tools with an LLM?

3The ReAct Pattern: Reason, Act & Observe

A single tool call lets an LLM answer simple queries like "what is the stock price of Apple?". Real-world problem solving, however, requires multi-step investigation: checking an inventory, looking up an address, calculating shipping fees, and finally confirming an order.

The ReAct pattern (Reason + Act) alternates between thinking out loud (Thought), invoking an action (Action), and reading the environment's response (Observation) in a loop until the goal is achieved.

The ReAct Agent Execution Loop (Reason → Act → Observe)

Multi-step agents decompose problems into iterative loops until they reach their termination condition.

Current Phase
Thought
Loop Cycle
#1 of 4
Accumulated Context
145 tokens
Agent Status
In Progress
ThoughtAnalyze User Intent & Determine Sub-Goals
Turn 1

The user asks: 'Customer Sarah wants to return order #8421 because it arrived broken. Can we refund it and send her a return label?' I must first fetch the order details and check return eligibility.

Step 1 of 10
Concept Check

In a ReAct agent loop, what is the role of the 'Observation' step?

4Parallel Tool Calling & Latency Optimization

In early agent architectures, if a user asked "Compare temperatures in London, Tokyo, and New York", the model had to make three separate LLM round-trips sequentially.

With Parallel Tool Calling, the model emits an array of multiple tool invocations in a single response. Your backend dispatches them concurrently via asynchronous workers, cutting latency by up to 70%.

Parallel vs. Sequential Tool Execution

Modern models can emit multiple tool calls at once. Compare the latency difference when querying 3 cities.

Total Round-Trip Latency
~640 ms (1 LLM turn)
The model emits 3 tool calls in a single turn. Your app runs all 3 concurrently via Promise.all or asyncio.gather.
get_weather('London')
210ms
210ms
get_weather('Tokyo')
190ms
190ms
get_weather('New York')
240ms
240ms
Concept Check

What is the primary benefit of parallel tool calling?

5Agent Safety, Loops & Human-in-the-Loop (HITL)

Autonomous agents introduce new engineering failure modes that simple chatbots never face:

Critical Agent Risks

  • Infinite Loops: Agent repeats the same failed tool call continuously until budget is drained.
  • Indirect Prompt Injection: Untrusted web content fetched by a tool instructs the agent to leak keys.
  • Unintended Side Effects: Accidentally deleting database rows or triggering real financial payments.

Production Guardrails

  • Max Iterations Limit: Hard cap (e.g. max 6 turns) before forcing agent termination.
  • Read vs. Write Segregation: Read-only tools run freely; write tools require user approval.
  • Human-in-the-Loop (HITL): Pause execution and ask human to confirm sensitive actions.

Human-in-the-Loop (HITL) Execution Interceptor

Read actions run autonomously. High-impact write and financial actions halt execution for human confirmation.

HITL Approval Gate Triggered
status: pending

State-changing / Financial: transfer $4,500 to external routing account.

initiate_wire_transfer(amount=4500, recipient="acct_9918", currency="USD")
Destructive/Financial write action requires human sign-off before invocation.
Concept Check

Why should high-impact tools (e.g., refunds, database deletes) incorporate a Human-in-the-Loop gate?

6When to Use Agents vs. Deterministic Code

Agents are powerful, but they are nondeterministic, slower, and significantly more expensive than traditional software. Choosing the right tool for the job is the mark of a senior AI engineer.

Great for AI Agents

  • Open-ended research across multiple unknown sources
  • Customer support triage with varied, branching paths
  • Transforming unstructured user intent into structured API workflows
  • Automated bug debugging where error recovery steps vary

Better as Deterministic Code / Pure RAG

  • Fixed, predictable workflows (e.g. step A always leads to step B)
  • Low-latency requirements (< 500 ms)
  • Standard CRUD database queries with known parameters
  • High-volume batch processing where token costs compound

7Chapter Challenge

Tool Calling & Agent Architecture Mastery

Answer all four questions correctly to demonstrate your understanding of tool calling and agent design.

0 / 4 correct
  1. 1What is the primary difference between a simple prompt and a tool call?

  2. 2In the ReAct pattern, what is the purpose of the 'Thought' phase?

  3. 3What happens if an external tool returns an error code or timeout message?

  4. 4What is an effective safeguard against an agent entering an infinite tool execution loop?

8Recap

  • LLMs don't run code: They emit structured JSON function arguments that your backend application executes.
  • JSON Schema is the contract: Clear parameter types and descriptions guide the model's tool selection and argument formatting.
  • ReAct loops enable multi-step autonomy: Alternating Thought, Action, and Observation lets agents solve complex, branching tasks.
  • Parallel tool calls optimize latency: Modern models emit multiple tools in one turn to be executed concurrently.
  • Guardrails protect production: Always enforce maximum iteration limits, idempotency keys, and Human-in-the-Loop approvals for destructive actions.

Solve the challenge above to complete the chapter, or mark it complete now:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us