ProjekinAja. Agentic AI Stage 4 · Building Agents Lesson 4.5
● Stage 4 · Lesson 4.5

Giving Your Agent Tools

A chat loop talks. Add tools and it acts — this is the exact moment your code becomes a real agent. Here it is, in Python.

⏱ ~18 min read 🛠️ It becomes an agent 🐍 Real code

🎯 By the end you'll understand

How to define a tool in real Python (name, description, input schema), how to write the tool-use loop — call the model, run the tool it asks for, feed the result back, repeat — how the assistant tool_use / user tool_result messages flow, how to dispatch across multiple tools, how to hand errors back to the agent, and why tools that act in the world need guardrails.

KEY INSIGHTThe one idea to take away

The model doesn't run your tools. It asks you to — and the few lines of code that hear the ask, run the function, and hand back the result are the entire difference between a chatbot and an agent.

In Lesson 4.4 you built a chat loop: a messages list, a while loop, one model call. It could talk, but it couldn't do — ask it the weather and it shrugged. This lesson closes that exact gap. We take that same loop and add the one capability that turns words into outcomes: tools.

And it's smaller than you'd guess. You'll add a tool definition, one branch in the loop, and a function that runs when the model asks. That's it. When you finish, you will have written — not configured, not dragged-and-dropped — a working agent.

🔑 Hold onto this

A tool is just a normal function you described to the model. The model never touches it. It returns a request — "please run get_weather('Tokyo')" — and your code runs the real function and feeds the answer back. The loop spins until the model has what it needs and replies in plain text. That request → run → feed-back cycle is the agent loop (2.1) made real.

CORE CONCEPTHow tools actually work — a quick recap

You met tools conceptually in Lesson 2.2. Here's the mechanism in five precise steps, because every line of code below maps onto one of them:

1

You define the tools

Each gets a name, a description (plain English — this is how the model decides when to reach for it), and an input schema (what arguments it takes).

2

You pass them to the model

On the same call you already make, you hand over the list of tool definitions. Now the model knows what hands it has.

3

The model requests a call

Instead of replying with text, it can reply with a tool_use block: "run get_weather with {"city": "Tokyo"}." It does not run anything itself.

4

Your code runs it

You read the request, call your actual Python function, and capture the result. This is the only step that touches the real world.

5

You feed the result back

You append the result as a tool_result and call the model again. It reads the result and either asks for another tool or answers in plain text. Loop.

📖 Function calling / tool use

Function calling (also called tool use) is the protocol by which a model requests that your code run a function, then continues its reasoning with the result. The model picks which tool and what arguments; your code does the actual running. Two names, one idea.

PRACTICALDefine a tool — name, description, schema

Let's make it concrete. Here's a real Python function — a weather lookup. For the lesson it returns a canned answer, but in production this is where you'd call a real weather API:

weather.pypython
def get_weather(city):
    # In real life: call a weather API here. We fake it for the lesson.
    fake = {"Tokyo": "18°C, light rain", "Paris": "24°C, sunny"}
    return fake.get(city, "unknown city")

The function is ordinary Python. The model can't see inside it and doesn't need to. What the model does need is a description of the tool — a small dict telling it the name, what the tool is for, and what arguments it takes. This is the tool definition (or tool schema):

tools.pypython
tools = [
    {
        "name": "get_weather",                       # must match what we dispatch on
        "description": "Get the current weather "
                       "for a given city.",           # how the model decides to use it
        "input_schema": {                            # JSON Schema: the arguments
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name, e.g. Tokyo",
                },
            },
            "required": ["city"],
        },
    },
]

Three things earn their place here. The name is the handle your code will match on later. The description is the most important field you'll write — the model reads it to decide whether and when to use the tool, so be specific and plain. And the input schema describes the arguments in JSON Schema, which is just a structured way of saying "this takes a string called city, and it's required."

💡 The description is a prompt

Treat the description like a tiny instruction to the model. "Get the current weather for a city" is good. "weather" is not — the model can't tell when to reach for it. Write descriptions a new teammate could read and immediately understand. Most "the agent ignored my tool" bugs are really "my description was vague" bugs.

CORE CONCEPTThe tool-use loop — line by line

Now the heart of it. We take the chat loop from 4.4 and add two things: we pass the tools on the model call, and we add a branch that handles a tool request. Read the comments — they're numbered to match the five steps above.

agent.pypython
import anthropic

client = anthropic.Anthropic()              # reads your key from the environment (4.4)

# the user's request — note: it needs a tool to answer
messages = [
    {"role": "user", "content": "What's the weather in Tokyo?"},
]

while True:                                  # the agent loop (2.1)
    response = client.messages.create(
        model="claude-sonnet-5",            # the brain (1.3) — id may change
        max_tokens=1024,
        tools=tools,                         # 2. hand the model its tools
        messages=messages,
    )

    # save the model's whole turn (text AND any tool_use blocks)
    messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":   # model answered in text → done
        break

    # 3 + 4: the model asked for one or more tools — run each one
    tool_results = []
    for block in response.content:
        if block.type == "tool_use":           # a tool request block
                        result = get_weather(**block.input)  # run our real function
            tool_results.append({
                "type": "tool_result",
                "tool_use_id": block.id,         # MUST match the request's id
                "content": str(result),
            })

    # 5: feed the result(s) back as a user turn, then loop
        messages.append({"role": "user", "content": tool_results})

# final answer is the last assistant text block
for block in response.content:
    if block.type == "text":
        print(block.text)

That's a complete, working agent. Walk the highlighted lines and you have the whole story: loop → call the model with tools → if it asked for a tool, run it and append the result → otherwise break. Everything else is bookkeeping.

One honest caveat: this bare loop is the happy path. Production code needs the tool-error handling shown next, plus a fallback for the case where the final turn has no text block (so the print loop above prints nothing) — both of which we add as you go.

Two details are load-bearing. First, we append response.content — the model's entire turn, including the tool_use block — not just its text. The model needs to see its own request in the history. Second, the stop_reason: the model tells us why it stopped. "tool_use" means "I need a tool, keep the loop going"; anything else means "I'm done, here's my answer." That single check is the loop's exit condition — the agent equivalent of the chat loop's quit command.

▸ The shape to memorize

Loop: call model (with tools) → check stop_reason → if tool_use, run the tool and append the result → else break. This is the chat loop from 4.4 with exactly one new branch. That branch is the entire leap from talking to acting.

FRAMEWORKThe message flow: tool_use → tool_result

The trickiest part to picture is how the conversation actually grows. Tools introduce two new kinds of message block, and they come in matched pairs. Here's the round trip:

user "What's the weather in Tokyo?" assistant · tool_use run get_weather(city="Tokyo") ↓ your code runs get_weather("Tokyo") → "18°C, light rain" user · tool_result "18°C, light rain" assistant · text "It's 18°C and lightly raining."

Read it top to bottom. The assistant turn carries the tool_use block — the request. Then your code runs the function (the middle step, off to the side — the model never sees this happen, only the result). You package the answer as a tool_result block and put it in a user turn. The model reads it and replies with plain text. Done.

📖 tool_use & tool_result

A tool_use block is the model's request to run a tool — it carries an id, the tool name, and the input arguments. A tool_result block is your reply — it carries the matching tool_use_id and the content (the function's output). The id is the thread that ties request to result; if they don't match, the API rejects the turn.

One subtlety: the tool_result goes in a message with "role": "user", even though no human typed it. That's just the protocol's convention — "input flowing into the model" uses the user role, whether it came from a person or from a tool. Don't overthink it.

SEE ITThe tool-use loop, live

Here's the loop running for a request that needs two tool calls: "What's the weather in Tokyo and Paris?" Press ▶ Step to advance one beat at a time. Watch the messages list grow on the right, and watch which Python runs each beat. Tool calls and results are tinted — that's the agent acting.

🛠️ Interactive · Execute a tool-using agent, beat by beat

Request: "What's the weather in Tokyo and Paris?" — two cities, so two tool calls.

Beat 0 · Ready

Press ▶ Step to begin. We'll trace the full loop.

runs this beat
—
messages list
(empty)
Beat 0 of 8

Notice the rhythm: the model asks (tool_use), your code runs get_weather, you hand back a tool_result, and only when the model has both answers does it stop asking and reply in text. The loop ran three model calls and two tool runs to answer one question — and every step was your code deciding what to do with the model's request. That's an agent.

PRACTICALMany tools, one dispatch

One tool is a demo. A real agent has several — search, calculator, send-email, read-file. The loop barely changes. You just need a way to map the tool name the model requested to the right Python function. That mapping is the dispatch.

The cleanest way is a dictionary from name to function:

dispatch.pypython
def get_weather(city):
    return {"Tokyo": "18°C, rain", "Paris": "24°C, sun"}.get(city, "unknown")

def calculator(expression):
    return str(eval(expression))          # NEVER use raw eval in production — see safety below

TOOL_FUNCTIONS = {                          # name → function: the dispatch table
    "get_weather": get_weather,
    "calculator": calculator,
}

def run_tool(name, tool_input):
        fn = TOOL_FUNCTIONS.get(name)           # look up the function by name
    if fn is None:
        return f"Error: unknown tool '{name}'"
    return fn(**tool_input)               # call it with the model's arguments

Now the loop's tool branch becomes generic — it works for any number of tools without changes:

agent.py (tool branch)python
    for block in response.content:
        if block.type == "tool_use":
                        result = run_tool(block.name, block.input)  # dispatch by name
            tool_results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": str(result),
            })

Add a tool by writing the function, adding one line to TOOL_FUNCTIONS, and adding its schema to the tools list. The loop never needs touching again. (This name-to-function map is exactly what the no-code "tool nodes" of Lesson 4.3 were doing under the hood — you're now writing it yourself.)

💡 The model can ask for several at once

In a single turn the model may return multiple tool_use blocks — like asking for Tokyo and Paris together. That's why we loop over response.content and collect all the results before calling the model again. Send every result back in one user turn; sending them one at a time will confuse the conversation.

CORE CONCEPTWhen a tool fails, tell the agent

Tools touch the real world, and the real world breaks. The API is down, the city doesn't exist, the math is invalid. The instinct is to let the exception crash your program. Resist it. The right move is to catch the error and hand it back to the agent as the tool result — so the agent can react.

Why? Because an agent that gets an error message can recover: try a different city, fix its arguments, or tell the user honestly. An agent whose program crashed can do none of that. Errors are information; feed them in:

safe_dispatch.pypython
    for block in response.content:
        if block.type == "tool_use":
                        try:
                result = run_tool(block.name, block.input)
                is_error = False
                        except Exception as e:                # the tool blew up
                result = f"Error: {e}"                # hand the message to the agent
                is_error = True
            tool_results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": str(result),
                                "is_error": is_error,             # flags it as a failure
            })

The "is_error": True flag tells the model "this tool call failed." The model reads the message, understands what went wrong, and adapts — maybe it asks you to clarify, maybe it retries with a corrected argument. Your program keeps running; the agent stays in control of how to handle the failure. That's the whole point of an agent: it copes with the unexpected.

▸ Errors are just results

A failed tool isn't an exception to escape from — it's a result to report. try/except around the tool, return the error string as the tool_result, set is_error. The agent treats a failure as one more piece of information to reason about.

WEAKNESSTools act — so guard them

Here's the sober truth that follows directly from the power you just unlocked. A chatbot can only ever produce words; the worst it does is be wrong. An agent with tools can do things — send the email, run the shell command, charge the card, delete the file. The model deciding which tool to call is a probabilistic system that is sometimes confident and wrong. So the question is no longer "is the answer good?" but "what can this tool do if the model misfires?"

Two habits, starting today:

⚠️ Validate inputs; never eval model output

The model's tool arguments are not safe by default. eval(block.input["expression"]) hands the model arbitrary code execution. os.system(block.input["cmd"]) hands it your shell. Always parse, validate, and constrain what a tool will accept and do before it acts. This is the single most important habit when your code can touch the world.

We're scratching the surface here on purpose — this is the foundation. Lesson 4.10 goes deep on safety: permissions, sandboxing, approval flows, and running agents that act in the world without handing them the keys to everything. For now, internalize the reflex: every tool that acts is a tool that needs a guardrail.

WEAKNESSCommon mistakes to avoid

✗ No error handling in your tools

If your tool function can raise — and any tool that touches the network, the filesystem, or user input can — wrap it in try/except and return the error as the tool result (with is_error: True). Letting it crash kills the whole agent; feeding the error back lets the agent recover. A failed tool is a result, not a catastrophe.

✗ Letting tools act without guardrails

The model is confident even when it's wrong. A tool that sends email, runs commands, or moves money will eventually be called with bad arguments. Validate inputs, constrain what each tool can do, and gate destructive or irreversible actions behind confirmation. Never eval or os.system raw model output. (Full treatment in 4.10.)

✗ Forgetting to feed the result back

The most common beginner bug: you run the tool, then call the model again without appending the tool_result — or you forget to append the assistant's tool_use turn first. The conversation breaks (the API rejects a tool_use with no matching tool_result, and the tool_use_id must match exactly). The loop only works if every request gets its result, appended in order.

KEY INSIGHTWhere this connects in your course

  • The agent loop (2.1) — the abstract "act → observe → decide → repeat" you learned is now a literal while loop with a tool_use branch. This lesson is 2.1 made real.
  • Tools & function calling (2.2) — the define → request → run → feed-back protocol you met conceptually is now code you've written.
  • Crossing to code (4.4) — you built the chat loop there; here you added one branch and it became an agent.
  • Giving your agent memory (4.6) — next: the messages list grows forever as tools fire; you'll learn to manage that memory deliberately.
  • A real working agent (4.7) — once it has tools, telling the agent how and when to use them becomes the real craft.
  • Safety & guardrails (4.10) — because tools act, the full story on permissions, sandboxing, and human-in-the-loop lives here.

This is the pivot lesson of Stage 4. Before it, you had a program that talks. After it, you have one that does. Everything from here — memory, prompts, multiple tools, safety — is adding capability and control to a loop you now genuinely own.

GLOSSARYKey terms introduced

Tool definition / schema
The dict describing a tool to the model: its name, a plain-English description (how the model decides to use it), and an input_schema (the arguments, in JSON Schema). It tells the model what the tool is — not how it works.
Function calling
The protocol by which a model requests that your code run a function, then continues with the result. Also called tool use — two names, one mechanism.
tool_use
A block in the model's response that requests a tool call — carries an id, the tool name, and the input arguments. The model never runs the tool; it asks.
tool_result
The block you append to reply to a tool_use — carries the matching tool_use_id and the content (your function's output). Goes in a user-role message.
Dispatch
The code (usually a name → function map) that routes a requested tool name to the correct Python function to run.
Tool-use loop
The cycle at the heart of a coded agent: call the model with tools → if it returned a tool_use, run the tool and append a tool_result → call again → repeat until it answers in plain text. The agent loop (2.1) in real code.
stop_reason
The field telling you why the model stopped. "tool_use" means it wants a tool (keep looping); anything else means it's done (break).

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1Who actually runs the tool — the model or your code? Walk the five steps.›

Your code runs the tool; the model only requests it. The steps: (1) you define the tools (name, description, input schema), (2) pass them on the model call, (3) the model requests a call via a tool_use block, (4) your code runs the matching function, (5) you feed the result back as a tool_result and call the model again. Loop until it answers in text.

2What single check in the loop decides whether to run a tool or stop?›

response.stop_reason. If it equals "tool_use", the model is asking for a tool — run it, append the tool_result, and loop again. If it's anything else (e.g. "end_turn"), the model answered in plain text — break. That check is the loop's exit condition.

3A tool raises an exception. What should you do — and why not just let it crash?›

Catch it with try/except and return the error message as the tool result, with "is_error": True. Crashing kills the agent; feeding the error back lets the agent react — retry with fixed arguments, try another approach, or tell the user honestly. A failed tool is just one more result to reason about.

4Why does an agent with tools need guardrails that a chatbot doesn't?›

Because tools act in the world — send email, run commands, move money, delete files — while a chatbot only produces words. The model picks tools probabilistically and is sometimes confidently wrong, so a misfire now has real consequences. Validate every tool's inputs (never eval raw model output), and gate destructive or irreversible actions behind confirmation, limits, or a human. Match the guardrail to the blast radius. (Full treatment in 4.10.)

It acts now. Next: give it memory →