Skip to content

Module 03 · Lesson 3.1

How Tool Calling Works

40 minUpdated 18 Nov 2026Part of Tools, APIs and Function Calling · AI Agent Development
On this page
  1. What you will learn
  2. What is a tool in an AI agent?
  3. The tool-calling round trip, step by step
  4. Who runs what: the model asks, your code acts
  5. Why the split makes AI agents safer
  6. Function calling and tool use: same idea, different names
  7. See the round trip in a short Python script
  8. How this maps to the ask_agent loop from the lab
  9. Conclusion and your next step
  10. Common errors and fixes
  11. Validation checklist
  12. Hands-on exercise
  13. Knowledge check
  14. Frequently asked questions
  15. References

Think about a visit to a doctor. The doctor writes a prescription, but never hands you the medicine. You take the paper to a pharmacist. The pharmacist checks it, hands over the medicine only if it makes sense, and keeps a record. Two people, two jobs, one safe result.

Tool calling works the same way. An AI model can write a request such as "please look up order QF-1042". Your own program checks that request and does the work. In this lesson you follow that round trip step by step, see who does what, and connect it to the ask_agent loop you built in the lab. Most of the lesson needs no coding. One short Python example prints the whole trip.

What you will learn

  • Explain what a tool is and why the model only asks for it.
  • Name the five steps of the tool-calling round trip in order.
  • Say which parts are run by the model and which by your application.
  • Run a short Python script that prints a numbered trace of one tool call.

Before you start

What is a tool in an AI agent?

A tool is a function in your program that you allow the model to ask for. Examples: "look up an order", "search the help pages", "create a return request".

On its own, a language model can only produce text. It cannot open your database or send an email. A tool is the bridge. You describe the function to the model, the model asks for it when it needs it, and your code does the real work.

You already have one. In the lab, lookup_order was a tool. The made-up bike shop Quillfeather Cycles has two tools in this module:

  • lookup_order(order_id) is read-only. It only reads an order and changes nothing.
  • request_return(order_id, reason) creates a return request. A staff member must approve it before anything happens.
Tool (function)
A function in your code that the model is allowed to ask for. People also say "function calling" or "tool calling" for the whole idea.
Tool description
A short card you send to the model: the tool's name, what it does and which inputs it needs. The model reads the card, never your code.
Arguments
The inputs the model fills in for a tool. For lookup_order, the argument is the order ID.
Observation
The result of a tool, sent back to the model so it can continue. An error is also an observation, for example {"error": "order not found"}.

The Agent Components lesson introduced tools as one part of an agent. This lesson opens that part and shows how it moves.

The tool-calling round trip, step by step

One tool call is a short trip between your application and the model. Here is the trip for the question "Where is QF-1042?".

The five steps of one tool call
  1. 1. Your app sends

    The question plus the tool descriptions

  2. 2. Model asks

    lookup_order with order_id QF-1042

  3. 3. Your code runs

    Checks the request, then runs the function

  4. 4. Your app sends back

    The result: dispatched, 2026-11-18

  5. 5. Model replies

    A final answer, or a request for another tool

Steps 1, 3 and 4 belong to your code. Steps 2 and 5 are the model's turns.

  1. Step 1: Step 1: Your app sends the question and the tool descriptions

    Your program sends the customer's words together with the description card of every tool the model may use.

  2. Step 2: Step 2: The model replies with a tool request

    If it needs a fact, the model does not answer yet. It replies with a request: a tool name and the arguments to use. It cannot know the status of QF-1042 without asking.

  3. Step 3: Step 3: Your code checks the request and runs the function

    Your program looks at the request. Is this tool on my list? Are the arguments valid? If yes, it runs the real function. If not, it refuses.

  4. Step 4: Step 4: Your code sends the result back

    The result goes back to the model as an observation. It might be the order data, or an error message.

  5. Step 5: Step 5: The model answers or asks for another tool

    With the result in hand, the model writes the final answer. Or it asks for one more tool, and the trip repeats from step 3.

Who runs what: the model asks, your code acts

This is the most important idea of the module: the model never runs your function. It only writes a request. Your application decides whether to run it.

Back to the prescription. The doctor (the model) knows medicine and writes what is needed. The pharmacist (your application) holds the medicine cabinet, checks the paper and decides. A prescription for something unsafe does not get filled, however nicely it is written.

JobModel (the doctor)Your application (the pharmacist)
Understand the customer's wordsYesNo
Choose which tool to ask forYesNo
Fill in the argumentsYesNo
Check the request is allowedNoYes
Run the real functionNoYes
Hold passwords and API keysNoYes
Stop the loop after too many roundsNoYes
The model suggests. Your code decides.

This matches the lab. In ask_agent, the model's reply is only checked for function_call steps. The function run_tool is yours. It runs lookup_order or returns an error for any other name.

Why the split makes AI agents safer

Because your code sits between the request and the action, you can put guards there. A model can be wrong, or can be tricked by text in a customer message. A guard in code does not get tricked.

  • Allowlist of tools. Run only tools you named in advance. An unknown name gets an error. In the lab, run_tool answers {"error": "unknown tool"}.
  • Validation. Check every argument before running. The order ID must match ^QF-[0-9]{4}$. A later lesson, Designing Tool Schemas and Validating Arguments, goes deep on this.
  • Approval for risky tools. request_return creates something a person must approve. The agent can ask, but staff decide.
  • Step limit. MAX_ROUNDS stops an agent that keeps asking for tools without finishing.

Function calling and tool use: same idea, different names

Every major provider offers this idea. The words differ, but the five steps are the same. Here are two examples, general only.

ProviderThe model's request is calledYour reply is calledOfficial guide
Google Geminia function_call stepa function_resultFunction calling with the Gemini API (opens in a new tab)
Anthropic Claudea tool_use blocka tool_resultHow tool use works (opens in a new tab)
Names and field details change with versions, so check the official guide before you code.

The lab used Gemini, so you have already seen function_call and function_result in agent.py. If you prefer Claude, the short course Build Your First Claude AI Agent uses the other set of names.

More than one tool in one reply

A model may ask for several tools in a single reply. For example, a customer asks about QF-1042 and QF-1044 together, and the model asks for two lookups at once.

Your code must run each request and send back every result. Look at the lab again: the variable calls is a list that collects every request in the reply, and [run_tool(call) for call in calls] answers each one. That is why it is a list, not a single call.

See the round trip in a short Python script

This script needs no internet, no key and no AI. A small function pretends to be the model and follows a fixed script. The loop around it is your application. It prints a numbered trace of the five steps for one question about order QF-1042.

Pythonround_trip.py
ORDERS = {"QF-1042": {"status": "dispatched", "estimated_delivery": "2026-11-18"}}
TOOLS = {"lookup_order": lambda order_id: ORDERS.get(order_id, {"error": "order not found"})}
MAX_ROUNDS = 3

def fake_model(history):  # a scripted stand-in: no network, no real AI
    last = history[-1]
    if last["role"] == "user":
        return {"tool": "lookup_order", "args": {"order_id": "QF-1042"}}
    info = last["result"]
    if "error" in info:
        return {"answer": "Sorry, I could not look that up. A colleague will help."}
    return {"answer": f"Order QF-1042 is {info['status']}, due {info['estimated_delivery']}."}

history = [{"role": "user", "text": "Where is QF-1042?"}]
print("1. App sends the question and the tool list:", list(TOOLS))
for _ in range(MAX_ROUNDS):
    reply = fake_model(history)
    if "answer" in reply:
        print("5. Model gives the final answer:", reply["answer"])
        break
    print("2. Model asks for a tool:", reply["tool"], reply["args"])
    allowed = reply["tool"] in TOOLS  # the allowlist check
    result = TOOLS[reply["tool"]](**reply["args"]) if allowed else {"error": "unknown tool"}
    print("3. App ran the function and got:", result)
    print("4. App hands the tool result to the model")
    history.append({"role": "tool", "result": result})

Runs offline with the standard library only. Save it and run python round_trip.py.

What each part does

  • ORDERS is made-up data that stands in for the shop's database. It is the same data as in the lab.
  • TOOLS is a dictionary, a list of name and value pairs. It is your allowlist: each tool name is paired with the real function.
  • lambda order_id: ... is a tiny one-line function. ORDERS.get(...) returns the order, or an error if there is none.
  • fake_model(history) plays the model. After the user's question it asks for lookup_order. After it sees a tool result, it writes an answer, or an apology if the result is an error.
  • history is the conversation so far. Each lap adds the tool result to it.
  • for _ in range(MAX_ROUNDS) is the step limit. The loop can never run more than three laps.
  • allowed = reply["tool"] in TOOLS is the allowlist check. An unknown name becomes an error instead of running.
  • TOOLS[reply["tool"]](**reply["args"]) runs the function with the arguments the model chose.
OutputCaptured from a real run
1. App sends the question and the tool list: ['lookup_order']
2. Model asks for a tool: lookup_order {'order_id': 'QF-1042'}
3. App ran the function and got: {'status': 'dispatched', 'estimated_delivery': '2026-11-18'}
4. App hands the tool result to the model
5. Model gives the final answer: Order QF-1042 is dispatched, due 2026-11-18.

The model never touched ORDERS. It wrote a request, and the loop did the work. With a real model, only fake_model changes. Everything else stays as it is.

How this maps to the ask_agent loop from the lab

The script is a toy version of ask_agent. The parts line up one to one:

Round trip stepIn round_trip.pyIn the lab's agent.py
1. Send question and toolshistory and list(TOOLS)send(question) with tools=[LOOKUP_ORDER]
2. Model asksfake_model(history)function_call steps in interaction.steps
3. Check and runallowed and TOOLS[...]run_tool(call)
4. Send result backhistory.append(...)send([...], interaction.id)
5. Answer or ask again"answer" in replyif not calls: return interaction.output_text
Step limitMAX_ROUNDSMAX_ROUNDS and the handover to a person
Open agent.py next to this table and find each row.

When the loop runs out of rounds, the lab agent returns a needs_person reply. That reply follows the contract with the four statuses answered, needs_order_number, needs_person and not_found, from System Instructions, Role, Constraints and Output Contracts.

For a one-page picture of the loop, see The Tool-Calling Loop: Reference Diagram.

Conclusion and your next step

A tool is a function your program lets the model ask for. The round trip has five steps: send the question and tool descriptions, receive a tool request, check and run it, send the result back, then get an answer or another request. The model only asks. Your application checks and acts, and that split is where your safety guards live.

Your next step: do the exercise below. Then continue to Designing Tool Schemas and Validating Arguments, where you write clear tool contracts and check every argument in code before a tool runs.

Want more background first? Read How to Build an AI Agent: A Beginner's Guide, or see the whole module at Tools, APIs and Function Calling.

Common errors and how to fix them

People think the model runs the function itself.

Why it happens: The word "calling" sounds like the model does the call.

Fix: Say "asks for" instead. The model writes a request. Your code decides and runs it.

The agent asks for a tool and then the conversation stops.

Why it happens: The tool result was never sent back to the model.

Fix: After running the tool, always send its result in step 4, even if it is an error.

The code runs whatever tool name the model sends.

Why it happens: There is no allowlist, so a made-up or risky name could run.

Fix: Look the name up in a fixed dictionary of tools. Unknown names return an error observation.

The model asks for two tools in one reply, but only the first one is answered.

Why it happens: The code assumed one request per reply.

Fix: Collect all the requests in the reply, run each one and send back one result per request.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Trace a return request through the round trip

A customer writes: "Please return my bike from order QF-1044, it is too big." Write the five steps of the round trip for this message, using the tool request_return(order_id, reason). Then mark which step is the best place to ask a person for approval.

You will need

  • The tool request_return(order_id, reason) creates a return request. Staff must approve it.
  • Order IDs match ^QF-[0-9]{4}$.
  • Tool errors go back to the model as an observation, such as {"error": "order not found"}.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Start with step 1: what does your app send besides the customer's words?
  • Ask yourself which step has the power to say no. That is where approval belongs.
  • What should the model hear back if staff do not approve?
Show a model answer

A strong answer reads like this. Step 1: the app sends the customer's message and the descriptions of its tools. Step 2: the model replies with a request, request_return with order_id QF-1044 and reason wrong_size, because the customer said the bike is too big. Step 3: the app checks that the tool is on the allowlist and that QF-1044 matches the ID pattern. Because the tool changes something, the app does not run it straight away. It creates a pending request and waits for staff approval. Step 4: the app sends the model an observation, for example that the return request was created and is waiting for approval, or an error if a check failed. Step 5: the model tells the customer that staff will review the request. Approval belongs in step 3, because that is where your code controls the action. The model never creates the return. It only asks.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.In tool calling, who runs the lookup_order function?
    Show the answer and explanation

    Answer: B. The model only sends a request with a name and arguments. Your code holds the function and runs it. The first option is tempting because the word "calling" suggests the model does it, but the model has no access to your code or data.

  2. 2.The model replies with a tool request. What is the correct next step?
    Show the answer and explanation

    Answer: B. Steps 3 and 4 are check, run and send back. The model needs the result to write its answer. Skipping the check is tempting for speed, but it removes your allowlist and validation, which are the main safety guards.

  3. 3.The model asks for two tools in one reply. What should your code do?
    Show the answer and explanation

    Answer: B. A model may ask for several tools at once, and each request needs its own result. Answering only the first is tempting because it is simpler, but the model would be left waiting for the other result and the answer would be incomplete.

Frequently asked questions

What is the difference between tool calling and function calling?

Usually nothing. Both names describe the same idea: the model asks for a function in your program, and your code runs it. Some providers say "function calling" and others say "tool use". The five steps are the same.

Does the AI model actually run my code?

No. The model only writes a request that names a tool and gives arguments. Your program decides whether to run it. This is the main reason tool calling can be made safe.

Can an AI model call more than one tool at once?

Yes. A single reply can contain several tool requests. Your code runs each one and sends back all the results. Check the guide of your provider for the exact format.

How does the model know which tools exist?

You tell it. With every request, your app sends a short description of each tool: its name, what it does and its inputs. The model chooses from that list. It cannot use a tool you did not describe.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.