Module 03 · Lesson 3.1
How Tool Calling Works
On this page
- What you will learn
- What is a tool in an AI agent?
- The tool-calling round trip, step by step
- Who runs what: the model asks, your code acts
- Why the split makes AI agents safer
- Function calling and tool use: same idea, different names
- See the round trip in a short Python script
- How this maps to the ask_agent loop from the lab
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- 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
- Practical Lab: Build and Test Your First AI Agent, Step by Step. You will look again at the
ask_agentloop from that lab. - No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
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?".
- 1. Your app sends
The question plus the tool descriptions
- 2. Model asks
lookup_order with order_id QF-1042
- 3. Your code runs
Checks the request, then runs the function
- 4. Your app sends back
The result: dispatched, 2026-11-18
- 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.
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.
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.
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.
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.
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.
| Job | Model (the doctor) | Your application (the pharmacist) |
|---|---|---|
| Understand the customer's words | Yes | No |
| Choose which tool to ask for | Yes | No |
| Fill in the arguments | Yes | No |
| Check the request is allowed | No | Yes |
| Run the real function | No | Yes |
| Hold passwords and API keys | No | Yes |
| Stop the loop after too many rounds | No | Yes |
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_toolanswers{"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_returncreates something a person must approve. The agent can ask, but staff decide. - Step limit.
MAX_ROUNDSstops 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.
| Provider | The model's request is called | Your reply is called | Official guide |
|---|---|---|---|
| Google Gemini | a function_call step | a function_result | Function calling with the Gemini API (opens in a new tab) |
| Anthropic Claude | a tool_use block | a tool_result | How tool use works (opens in a new tab) |
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.
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
ORDERSis made-up data that stands in for the shop's database. It is the same data as in the lab.TOOLSis 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 forlookup_order. After it sees a tool result, it writes an answer, or an apology if the result is an error.historyis 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 TOOLSis 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.
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 step | In round_trip.py | In the lab's agent.py |
|---|---|---|
| 1. Send question and tools | history and list(TOOLS) | send(question) with tools=[LOOKUP_ORDER] |
| 2. Model asks | fake_model(history) | function_call steps in interaction.steps |
| 3. Check and run | allowed and TOOLS[...] | run_tool(call) |
| 4. Send result back | history.append(...) | send([...], interaction.id) |
| 5. Answer or ask again | "answer" in reply | if not calls: return interaction.output_text |
| Step limit | MAX_ROUNDS | MAX_ROUNDS and the handover to a person |
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.
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.
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.
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.
- Function calling with the Gemini API(opens in a new tab)
Google · Official documentation · Covers the function_call step and the function_result reply used in the lab.
- How tool use works(opens in a new tab)
Anthropic · Official documentation · Explains how Claude asks for tools and how results go back.
- Tool use with Claude(opens in a new tab)
Anthropic · Official documentation
- Writing effective tools for agents(opens in a new tab)
Anthropic · Official documentation · Practical advice on designing tools that agents use well.
- LLM06:2025 Excessive Agency(opens in a new tab)
OWASP Foundation · Official documentation · Why an agent should only get the tools and permissions its job needs.
- Python tutorial: more control flow tools(opens in a new tab)
Python Software Foundation · Official documentation · Background for the `for` loop and functions in the example.
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.