Mod 1.5How AI Agents Use Tools
Level 1›Module 1.5
Level 1: Foundations & ArchitectureModule 1.5

How AI Agents Use Tools

Tools

Level 1 • Foundations & Architecture
Est. ~24 mins
5 Key Topics
🎁 Free Learner Perk

Unlock Verified Certificate & Daily Streak Tracker

Ready to master How AI Agents Use Tools? Enable cloud sync to record your daily streak 🔥 and earn your Informational Completion Badge for your study milestones.

Day 1 Streak ActiveFree Completion BadgeSync Laptop & Phone

🎯 By the end of this module, you will:

Understand why frozen neural weights require external tools to interact with reality
Master the 8-step tool execution loop from intent to observation ingestion
Differentiate safe idempotent Read tools from mutating Write tools requiring HITL gates
Explore the Model Context Protocol (MCP) universal client-server standard
Section 1 • Grounding LLMs in Reality

The Surgeon in the Soundproof Glass Room

Even the most capable frontier LLM cannot know what the current time is, cannot look up today's stock price, cannot verify a user's account balance, and cannot dispatch an email on its own.

Neural network weights are frozen snapshots of past training data. Tools are the stethoscopes, calculators, databases, and API keys that give the model eyes and hands in the physical world.

🔇 Trapped in the Glass Room (LLM Alone)

A brilliant physician who has memorized every textbook, but is locked inside a soundproof room without instruments. They cannot measure vitals or administer treatment.

Prompt: "Check today's AAPL price" ──▶ 💥 Hallucinated past price
🩺 Equipped with Medical Instruments (Agent + Tools)

The surgeon is equipped with a digital stethoscope, real-time monitors, and laser scalpels. They perceive live patient vitals and execute precise interventions.

Prompt: "Check today's AAPL price" ──▶ 🛠️ `fetch_ticker('AAPL')` ──▶ ✅ $224.50
✍️
Instructor Note • The Execution Boundary

"Remember this fundamental law: The LLM NEVER runs python code or APIs itself. It only generates a JSON string declaring intent. Your host environment catches that string, validates it, runs the real function, and hands the result back!"

Section 2 • Tool Taxonomy

The 4 Core Tool Categories

Select a category to inspect its schema definition and invocation signature:

Category: 4. Mutating APIsMutating Write (HITL)
Python @tool Signature

Sends emails, charges Stripe accounts, triggers GitHub pull requests, and writes to production systems.

@tool
def process_stripe_refund(charge_id: str, amount_usd: float) -> dict:
    """Issues Stripe refund. Mutates financial state; requires supervisor sign-off!"""
    return stripe.Refund.create(charge=charge_id, amount=int(amount_usd * 100))
💡
Mental Model • The Restaurant Waiter

"The LLM is like a polite waiter who takes your order on a notepad (JSON). The waiter doesn't cook the meal or bake the bread—they pass the ticket to the kitchen (Runtime API), wait for the dish, and bring it back to your table!"

Section 3 • Safety & Open Standards

Read vs. Write Tools & The Model Context Protocol

In production agent engineering, two foundational concepts protect your systems and eliminate integration fragmentation:

Read vs. Write GovernanceSecurity Policy

Read tools (querying weather, searching docs) are idempotent: executing them 10 times causes zero external side effects.

Write tools (charging credit cards, dropping database tables, emailing customers) permanently alter external state and must always be protected with approval gates.

Model Context Protocol (MCP)Universal Standard

Before MCP, every AI framework had to write custom connectors for Slack, GitHub, Postgres, and Linear (an M × N nightmare).

MCP establishes a universal JSON-RPC client-server protocol: tool creators build one MCP Server, and any compliant agent can immediately discover and run it!

📌
The Strict Schema Contract Rule

"Every tool description is a prompt to the model. Write docstrings like you are explaining the function to a junior developer: specify exactly what parameters mean, provide boundary constraints, and define return schemas!"

Section 4 • Interactive Simulator
Interactive 8-Step Tool CycleLive Simulator

The Complete Tool Execution Loop

Compare safe idempotent Read actions with mutating Write actions requiring approval

Step 1 of 8: User Provides InputInput Stage
Architectural Entities Involved

Human User

Provides natural language intent

ACTIVE

Agent (LLM Engine)

Generates JSON schema tool call

Host Runtime & Tool

Executes actual API / Python function

💡 Golden Principle: The LLM Does Not Run Tools!The model never executes code itself. It emits a structured JSON string. The surrounding host runtime validates it, calls the Python/Node function, and injects the output back into the conversation history.
Step 1

User Provides Input

Input Stage

The user issues a prompt requiring external or real-time information.

Payload / Runtime Streamjson / text
User: "What is the current weather in Tokyo and convert 18°C to Fahrenheit?"
Section 5 • Hands-On Code Laboratory

Interactive Tool Engineering & MCP Studio

Test Python schemas, validation resilience, and universal Model Context Protocol (MCP) servers

# Production Tool Definition in Python using Pydantic
from pydantic import BaseModel, Field
from typing import Literal

class FinancialQueryInput(BaseModel):
    """Schema for querying quarterly financial records."""
    ticker: str = Field(
        ..., 
        description="Stock ticker symbol in capital letters, e.g. 'AAPL' or 'GOOGL'"
    )
    quarter: Literal["Q1", "Q2", "Q3", "Q4"] = Field(
        ..., 
        description="Fiscal quarter to analyze"
    )
    fiscal_year: int = Field(
        ..., 
        ge=2015, 
        le=2026, 
        description="Four-digit fiscal year between 2015 and 2026"
    )

def query_financial_metrics(ticker: str, quarter: str, fiscal_year: int) -> dict:
    """
    Retrieves revenue, EPS, and gross margin for public companies.
    Returns: JSON dictionary with audited SEC filing statistics.
    """
    # 1. Pydantic validates inputs automatically
    # 2. Database query executed safely via parameterized SQL
    return {
        "ticker": ticker.upper(),
        "quarter": quarter,
        "fiscal_year": fiscal_year,
        "revenue_billions": 85.78,
        "net_income_billions": 21.45,
        "eps": 1.40,
        "status": "audited"
    }
How the magic works: The LLM never sees raw Python code! Frameworks convert Pydantic type annotations into the JSON Schema shown above. The model uses the parameter schema to formulate valid structured tool calls.
Simulate Agent Tool Calling Test Case
Runtime Stream & Validation Logs
stdout
Click "Run Tool Call Simulation" above to view live parsing, validation, and self-healing error traces...
📝
Production Pro-Tip • Schema Self-Healing

"When an LLM supplies invalid arguments that fail Pydantic validation, do not throw an unhandled exception! Catch the ValidationError, pass the exact error message back to the LLM as a tool result, and allow the model to self-correct its parameters on the next turn!"

Section 6 • Production Gotchas
TRAP #1: Vague Docstrings & Tool Confusion

Giving tools generic descriptions like `def search(q): "searches stuff"` causes the agent to pick the wrong tool or hallucinate invalid argument formats.

Fix: Write exhaustive docstrings detailing expected formats, boundary limits, and concrete examples.

TRAP #2: Raw Database Access Without Limits

Exposing raw, unparameterized SQL execution to an LLM risks SQL injection, accidental table truncation, or runaway queries locking production clusters.

Fix: Connect agents to read-only database replicas with strict query timeouts and parameterized Pydantic wrappers.

Section 7 • Key Takeaways & Quiz

Summary Checklist

Tools bridge text generation to the real world: LLMs cannot know live data or compute complex math without external tools.
Strict Pydantic schemas enforce type safety: JSON schema compilation ensures parameters conform to strict types, enabling self-healing recovery loops.
Model Context Protocol (MCP) unifies tool ecosystems: Eliminates bespoke connectors by providing a universal JSON-RPC standard for agents and data sources.
Next Step in Level 1

Module 1.6: Fundamentals of the Agentic Loop

Master the core engine of agency: Perceive ➔ Reason ➔ Act ➔ Observe ➔ Terminate.

Proceed to 1.6