LESSON 60 Β· AI AGENTS

Tools

Learn how AI agents use tools to interact with the real world. Understand tool schemas, tool selection, execution, results, safety, and practical Python patterns.

30 min readβ€’Intermediateβ€’Generative AI

By the end of this lesson, you will be able to:

  • Explain what a tool is in an AI agent system.
  • Understand the difference between an LLM response and a real tool execution.
  • Design clear tool names, descriptions, and input schemas.
  • Build a simple Python tool registry and execution loop.
  • Understand tool selection, validation, errors, retries, and permissions.
  • Choose when to use a tool, RAG, a deterministic function, or a human approval step.
1

What Is a Tool?

A tool is a capability that an AI application can invoke to perform an operation outside the model's text generation. Examples include searching a knowledge source, calling an API, running a calculation, reading a database, or creating a ticket.

MODELReasons about the task

The model decides what information or action may be useful based on the available tool descriptions.

TOOLPerforms the operation

Your application executes a real function or service and returns a structured result.

Remember:An LLM does not magically execute an API because it wrote a function name. Your application must validate the request, execute the permitted tool, and return the result to the model.
2

Why Agents Need Tools

Language models are strong at reasoning over text, but many real tasks require current data or actions. Tools connect the model to systems that can provide those capabilities.

LIVE INFORMATIONSearch or APIs

Retrieve information that is outside the model's static knowledge.

CALCULATIONCalculator

Delegate exact arithmetic instead of relying on generated mental math.

BUSINESS DATADatabase

Look up permitted customer, product, order, or inventory information.

ACTIONCreate or update

Open tickets, send messages, update records, or trigger workflows with authorization.

3

Tool Calling vs Tool Execution

These are two different stages. The model can produce a structured tool call request. The application then performs the actual tool execution.

1. UserStates a goal
β†’
2. ModelSelects a tool
β†’
3. AppValidates arguments
β†’
4. ToolRuns the operation
β†’
5. ModelUses the result

This separation is important for security. The model should recommend an action; the application remains responsible for deciding whether that action is actually allowed.

4

A Good Tool Has a Clear Contract

A tool description is an interface contract between the model and your application. The model needs enough information to select the correct tool without guessing.

NAME

Specific

Prefer get_order_status over a vague name like helper.

DESCRIPTION

Action-oriented

Explain what the tool does and when it should be used.

INPUTS

Explicit

Define required fields, types, ranges, and allowed values.

OUTPUT

Structured

Return predictable data that the model can interpret reliably.

5

Tool Schemas

A schema describes the arguments a tool accepts. For example, an order-status tool might require an order ID and reject unknown fields.

</> Python
tool = {
    "name": "get_order_status",
    "description": "Get the current shipping status for an order.",
    "parameters": {
        "type": "object",
        "properties": {
            "order_id": {"type": "string"}
        },
        "required": ["order_id"]
    }
}

In a real API, the exact schema format depends on the framework or model provider. The design principle is the same: make the contract explicit.

6

Tool Registry in Python

Your application can maintain a registry that maps safe tool names to actual Python functions.

</> Python
def get_weather(city):
    return {"city": city, "temperature_c": 28, "condition": "Sunny"}


def calculate_total(price, quantity):
    return {"total": price * quantity}


tools = {
    "get_weather": get_weather,
    "calculate_total": calculate_total,
}

print(tools["calculate_total"](19.99, 3))

The registry creates a controlled boundary: only functions that you explicitly register can be called.

7

How an Agent Selects a Tool

The model receives the user's goal plus the available tool descriptions. It can then return either a final response or a structured tool request.

User goalβ€œWhat is the weather?”
β†’
Available toolsWeather + calculator
β†’
Model decisionSelect weather
β†’
Argumentscity = London

Good tool descriptions reduce ambiguity. Poor descriptions can cause wrong-tool selection, missing arguments, or unnecessary calls.

8

Example 1: Weather Tool

Suppose a user asks: β€œWill I need an umbrella in London today?” A model may recognize that current weather information is required.

MODELChoose the weather tool

The model identifies that a current condition is needed rather than inventing an answer.

APPLICATIONValidate the city

The application checks that the city argument is valid and allowed.

TOOLFetch current data

The weather service returns structured conditions.

MODELExplain the result

The model turns the tool result into a natural-language answer.

9

Example 2: Customer Support Tool

Imagine a support agent with these tools: get_order_status, get_tracking_events, and create_support_ticket.

STEP 1Look up the order

Retrieve the permitted order status using the customer's authenticated account.

STEP 2Inspect delivery events

If the order is delayed, retrieve tracking details.

STEP 3Decide what is needed

The next action depends on the information returned.

STEP 4Escalate when necessary

Create a ticket only when the business rules allow it.

This is where tools become especially useful in an agent loop: the result of one operation can influence the next permitted operation.

10

Tool Results Should Be Structured

Returning predictable fields makes downstream reasoning easier and reduces ambiguity.

</> Python
result = {
    "status": "delayed",
    "carrier": "Example Express",
    "estimated_delivery": "2026-09-14",
    "events": 4,
}

if result["status"] == "delayed":
    print("Explain the delay and check the next permitted action.")

Avoid returning huge unstructured blobs when a small set of relevant fields is enough.

11

Validation: Never Trust Tool Arguments

Model-generated arguments are untrusted input. Validate them before calling a real service.

Type checks

Confirm strings, numbers, arrays, and objects have the expected types.

Range checks

Reject impossible quantities, oversized requests, or invalid dates.

Authorization

Verify that the current user can access the requested resource.

Allow lists

Restrict actions, destinations, fields, and operations to approved values.

12

Permissions and Least Privilege

Do not expose every internal capability to every agent. Give each agent the smallest useful set of tools.

READ

Lower risk

Searching public documentation or reading permitted records may need fewer safeguards.

WRITE

Higher risk

Creating or updating records should have stronger validation.

EXTERNAL

Review carefully

Sending messages or publishing content can create real-world consequences.

DESTRUCTIVE

Require approval

Deletion, payments, and account changes often need explicit human or policy approval.

13

Tool Errors Are Normal

Networks fail, APIs time out, records disappear, and inputs can be invalid. A robust agent should handle tool errors instead of pretending the action succeeded.

</> Python
def safe_call(tool, arguments):
    try:
        return {"ok": True, "data": tool(**arguments)}
    except ValueError as exc:
        return {"ok": False, "error": "invalid_input", "message": str(exc)}
    except TimeoutError:
        return {"ok": False, "error": "timeout", "message": "Tool timed out."}

result = safe_call(get_weather, {"city": "London"})
print(result)

Keep error messages structured so the model can decide whether to retry, ask the user, choose another tool, or stop.

14

Retries and Idempotency

Retries can help with temporary failures, but blindly repeating an action can be dangerous.

SAFE RETRYRead operation

A temporary timeout while fetching information may be reasonable to retry.

CAUTIONWrite operation

Retrying a payment or message can accidentally duplicate the action.

IDEALIdempotent operation

Design APIs so repeating the same request does not unintentionally create duplicates.

CONTROLRetry limits

Use bounded retries and stop when the error indicates a permanent failure.

15

Tools vs RAG

RAG and tools can overlap, but they solve different problems.

RAGRetrieve knowledge

Find relevant chunks from a document or knowledge collection and provide them as context.

TOOLPerform an operation

Call a service, calculate a value, query a live system, or change something.

For example, answering a company policy question may use RAG, while checking a live order status requires a tool. An agent can use both.

16

Tools vs Deterministic Functions

Not every function needs an LLM to choose it. If the application always knows which function should run, call it directly.

FIXED RULE

Call directly

Use normal application code when the next action is already known.

DYNAMIC CHOICE

Tool selection

Let the model choose among permitted capabilities when the next step depends on the task.

SENSITIVE ACTION

Add approval

Keep business policy outside the model and require explicit authorization.

REPEATED LOOP

Use an agent

Agentic execution is useful when observations influence subsequent actions.

17

Tool Calling in an Agent Loop

A simple framework-free mental model looks like this:

</> Python
def run_agent(goal, model, tools, max_steps=5):
    state = {"goal": goal, "history": []}

    for _ in range(max_steps):
        decision = model(state, list(tools))

        if decision["type"] == "final":
            return decision["answer"]

        if decision["type"] == "tool":
            name = decision["name"]
            arguments = decision["arguments"]

            if name not in tools:
                return "Tool is not allowed."

            result = tools[name](**arguments)
            state["history"].append({
                "tool": name,
                "result": result,
            })

    return "Stopped: step limit reached."

This is a teaching model, not a production security boundary. Real systems should add schema validation, authorization, logging, rate limits, and safer execution isolation.

18

Observability

Tool-using agents are difficult to debug if you only store the final answer. Record enough information to understand what happened.

Tool selected

Which capability did the model request?

Arguments

What inputs were submitted after validation?

Result

What did the tool return, and was it successful?

Timing

How long did the model and external operation take?

19

Common Tool Design Mistakes

Too many tools

A huge tool catalog increases selection ambiguity and maintenance.

Vague descriptions

If the model cannot tell when to use a tool, tool selection becomes unreliable.

Unsafe arguments

Never pass model-generated values directly into sensitive operations without validation.

Huge outputs

Return focused, structured results instead of unnecessary raw payloads.

No timeout

External calls should have bounded execution time.

No audit trail

Without logs, failures and unexpected actions are hard to investigate.

20

Mini Project: Build a Safe Tool Agent

Design a small Python agent that can answer a user's request using three tools:

TOOL 1Calculator

Accept two numbers and an operation from a strict allow list.

TOOL 2Knowledge search

Return a few relevant pieces of information from a small local collection.

TOOL 3Support ticket

Create a ticket only after validating the required fields and applying an approval rule.

AGENTChoose and combine

Let the model select tools, execute them through a controlled registry, and stop after a bounded number of steps.

Challenge: Add a policy that prevents the agent from creating a ticket unless the user has explicitly requested escalation.

21

Quick Quiz

1. What is a tool?

A) A larger language model   B) A callable capability that performs an operation   C) A prompt template only

2. Who should execute a real tool?

A) The text generator itself   B) The application or tool runtime   C) The user only

3. Why are schemas useful?

A) They hide arguments   B) They define the tool's input contract   C) They remove validation

4. Should model-generated tool arguments be trusted directly?

A) Yes   B) No, validate and authorize them first   C) Only for write operations

22

30-Second Recap

1Tools give an AI system capabilities beyond text generation.
2The model requests a tool; the application executes it.
3Clear names, descriptions, schemas, and structured outputs improve reliability.
4Validate arguments, enforce permissions, and handle errors before trusting tool results.
5Use deterministic functions when the next action is already known.
23

Key Takeaways

Remember:Tools connect an AI agent to real capabilities such as APIs, databases, search, calculators, and business actions. The model can choose a permitted tool, but your application must remain in control of validation, authorization, execution, and safety.

The best tool is not the most powerful one. It is the smallest clearly defined capability that lets the system complete a useful task safely and predictably.