Lesson 61 Β· AI Agents

Tool Calling

Learn how an AI model decides to use a tool, sends structured arguments, receives the result, and continues the conversation.

What Is Tool Calling?

Tool calling is the process where an AI model requests that an application execute a specific tool with structured arguments.

The model does not magically run the function itself. Your application receives the tool call, validates it, executes the tool, and sends the result back to the model.

1. Userβ€œWhat is the weather in London?”
2. ModelRequests get_weather(city="London")
3. ApplicationValidates and executes the tool
4. ToolReturns structured weather data
5. ModelUses the result to answer the user
30 min readβ€’Intermediateβ€’Generative AI

Tool Calling vs Tool Execution

Tool Calling

The model produces a structured request describing which tool it wants and which arguments it needs.

Tool Execution

Your application actually runs the function, API, database query, or service and returns the result.

This separation is important because your application remains in control of permissions, validation, errors, and side effects.

A Tool Needs a Clear Contract

A good tool definition tells the model what the tool does and exactly which arguments are accepted.

  • Name: a short, descriptive identifier.
  • Description: when and why the tool should be used.
  • Parameters: structured inputs with clear types.
  • Required fields: arguments that must be supplied.
  • Return shape: predictable output for the model.

Python: Define a Simple Tool

Here is a simple Python tool contract and implementation:

</> Python
def get_weather(city: str) -> dict:
    # Replace this with a real weather API call.
    return {
        "city": city,
        "temperature_c": 24,
        "condition": "Sunny"
    }

tool = {
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "parameters": {
        "city": {
            "type": "string",
            "description": "City name"
        }
    },
    "required": ["city"]
}

The Tool-Calling Loop

A typical agent application follows this loop:

Prompt→Model→Tool Call?→Execute→Tool Result→Model

If the model does not request a tool, the application can return the model's normal response. If it does, the application executes the approved tool and gives the result back to the model.

Structured Arguments

Tool calls should use structured data rather than asking the model to produce arbitrary text for your application to parse.

Example:{"city": "London", "units": "celsius"}

Structured arguments make validation, logging, retries, and error handling much more reliable.

Python: Validate Before Execution

Never assume model-generated arguments are safe or complete.

</> Python
def run_weather_tool(arguments: dict) -> dict:
    city = arguments.get("city")

    if not isinstance(city, str) or not city.strip():
        return {"error": "A valid city is required."}

    city = city.strip()

    if len(city) > 100:
        return {"error": "City name is too long."}

    return get_weather(city)

Handling Tool Errors

Validation error

Tell the model what input is missing or invalid so it can correct the request.

Runtime error

Return a controlled error instead of exposing internal stack traces or sensitive implementation details.

Timeout

Use time limits and decide whether the operation should be retried.

Unavailable service

Give the model a clear failure result and allow a graceful fallback when appropriate.

Tool Calling with Multiple Tools

An agent may have many tools. The model can select the tool that best matches the user's request, but the application should still enforce an allowlist.

search_productsFind products matching a query.
get_order_statusRetrieve the status of an order.
create_support_ticketCreate a support ticket after permission checks.

For sensitive actions, require stronger controls such as confirmation, authentication, authorization, or human approval.

Tool Calling + RAG

RAG retrieves knowledge, while tools let an agent perform operations or access live systems. They can work together.

RAG

Retrieve relevant documents or knowledge for grounded answers.

Tool

Call a service, database, calculator, API, or application capability.

For example, a support agent could retrieve the return policy with RAG and then call an order-status tool to inspect a customer's current order.

Permissions and Safety

  • Give each tool the minimum permissions it needs.
  • Validate every argument on the application side.
  • Never trust a model-generated tool call as authorization.
  • Separate read-only tools from tools that change data.
  • Require confirmation for high-impact actions.
  • Log tool calls without exposing secrets or sensitive values unnecessarily.

Common Mistakes

  1. Writing vague tool descriptions.
  2. Accepting arbitrary arguments without validation.
  3. Letting the model directly control credentials.
  4. Returning inconsistent tool-result formats.
  5. Giving an agent too many overlapping tools.
  6. Allowing irreversible actions without confirmation.

Practice

Design a support tool

Create a Python tool contract for get_order_status. Define its purpose, required order_id, validation rules, and a predictable result structure.

Goal: make the tool safe and easy for an agent to call.

Quick Quiz

1. Who actually executes a tool call?

A. The model directly   B. The application/tool runtime   C. The user

2. Why validate tool arguments?

A. For safety and reliability   B. To make prompts longer   C. To remove tools

3. What should sensitive actions often require?

A. No checks   B. Confirmation or authorization   C. Random arguments

30-Second Recap

1. Model requestsThe model chooses a tool and produces structured arguments.
2. Application validatesYour application checks the tool call and permissions.
3. Tool executesThe approved function or service runs and returns a result.
4. Model continuesThe model uses the result to produce the final response or another tool call.

Key Takeaways

Remember: Tool calling is the bridge between an AI model's decision and real application capabilities.

Good tool design combines clear schemas, strict validation, controlled permissions, predictable results, and safe execution.