Skip to main content

AI Agents and Tool Calling Explained from Zero

How a language model goes from writing text to doing things: tool calling, the agent loop, the parts of an agent, why agents fail in practice, and when a simpler design is the better choice.

AI Agents and Tool Calling Explained from Zero

You type “Book me a table for four on Friday evening near the office” into an assistant, and a few moments later a table is booked. But a language model is a program that writes text. Text cannot phone a restaurant. So what actually happened between your sentence and the booking?

The answer is two ideas that are simpler than they sound: tool calling and the agent loop. In plain words, an AI agent is a language model connected to your software so that it can ask for real actions (search, check, book), see what happened and decide the next step, again and again until the job is done. This post explains how that works, from zero: it is for anyone who has used a chat assistant and wondered how it can do things, not only write. No prior knowledge of AI needed.

First, the words

These are the only terms you need to follow this post. Each one is explained again where it first appears.

  • Language model (LLM, large language model) — a program trained on vast amounts of text that takes text in and writes text out; on its own it cannot do anything else.
  • Prompt — everything you send to the model in one go: standing instructions, the conversation so far and the question.
  • Function — a named piece of a program that does one job when it is called, such as “search restaurants”.
  • Tool — a function in your program that the model is allowed to ask for.
  • Tool calling — the model replying with a structured request to run a tool, instead of plain text.
  • Agent — a model that can ask your software to run tools, sees the results, and decides its own next step until the job is done.
  • Agent loop — the repeating cycle: the model decides, a tool runs, the model reads the result, and so on.
  • API (application programming interface) — a defined way for one program to ask another program for something.

The short answer

A language model can only produce text. An AI agent is ordinary software wrapped around that model: the model writes a request to use a tool, your program runs the tool, hands the result back, and the two repeat until the job is done.

The analogy I’ll use throughout: an expert on the phone. Imagine a very capable advisor who is stuck at the other end of a phone line. They cannot see your screen or touch anything. They can only say things like “please look up restaurants near the office and read me the list”. You do the looking up, read the results back, and they tell you the next step. The model is the voice on the phone. Your code is the hands.

Keep one fact from this section: the model never executes anything itself.

Why it exists

A large language model (LLM, the kind of AI behind chat assistants) takes text in and predicts text out. It learned to do that during training, by being shown a huge amount of text. On its own that leaves three gaps.

It cannot look anything up. The model learned from a snapshot of text collected up to some date. It does not know which restaurants have a free table this Friday, what is in your calendar, or even what today’s date is, unless someone puts that into its input.

It cannot change anything. It can write “Your table is booked!”, and that sentence will look exactly like a real confirmation. Nothing was booked.

It cannot check its own work. Without a way to observe the world, the model has no feedback. If its guess is wrong, nothing tells it so.

Tool calling closes these gaps with an agreed format: the model is told which tools exist, and when it wants one it answers with a structured request (text in a fixed, machine-readable shape) that your code can read reliably.

How it works, step by step

Here is the whole picture first. The numbers match the steps below. Along the way you will meet the six parts every agent is made of; they are summed up in “The parts of an agent” right after the steps.

The agent loop: the user gives a goal to your code, your code sends messages and tool descriptions to the model, the model returns a tool request, your code runs the tool and feeds the result back, repeating until an answer or a stop condition

Our running example: a booking assistant with three tools: search restaurants, check availability, create a booking. All names, addresses and data below are invented for illustration.

Step 1: You describe the tools

A tool is a function (a named piece of code that does one job when called) in your own program that you allow the model to ask for. You describe each one with three things: a name, a plain-language description of what it does and when to use it, and an input schema: a formal list of the inputs it accepts and their types.

In plain words, the availability tool from our example is described like this:

  • Name: check availability.
  • What it does: shows free time slots at one restaurant for a given date and number of people; use it before booking; it does not reserve anything.
  • What it needs: which restaurant, which date, how many people.

In practice the same description is written in JSON, a simple text format that programs use to exchange structured data, and the input schema uses a standard way of describing inputs called JSON Schema. This example uses the field names of Anthropic’s API:

{
  "name": "check_availability",
  "description": "Returns free time slots at one restaurant for a date and party size. Call this before create_booking. Does not reserve anything.",
  "input_schema": {
    "type": "object",
    "properties": {
      "restaurant_id": { "type": "string" },
      "date":          { "type": "string", "description": "YYYY-MM-DD" },
      "party_size":    { "type": "integer" }
    },
    "required": ["restaurant_id", "date", "party_size"]
  }
}

The exact field names differ between vendors, the companies that provide the models (Anthropic calls the schema input_schema, OpenAI calls it parameters), but the three ingredients are the same everywhere.

Why it matters: the description is all the model ever learns about your tool. It never sees your code. Wrong tool choices often start with a vague description.

Step 2: The user states a goal, and your code sends everything to the model

Your code builds a request containing the instructions (also called the system prompt: standing rules for the assistant), the tool descriptions, and the user’s message. The instructions carry facts the model cannot know: today’s date, where “the office” is, and rules such as “ask before booking”.

Skip those facts and the model has to guess what “Friday” means. It will guess confidently.

Step 3: The model replies with a tool request, not an answer

The model reads everything and decides it cannot answer yet. Instead of prose, it returns a small structured message: the name of a tool and the arguments to pass (the concrete input values, such as an address or a date). This is tool calling, also called function calling. The vendors describe it the same way: in Anthropic’s documentation the model “never runs anything on its own”, and OpenAI’s guide has your application run the code after the model returns a tool call. (Some providers also offer built-in tools, such as web search, that run on the provider’s servers, its own computers, instead of in your code. The principle is the same: the model only writes the request.)

That request is still just text in an agreed shape: the expert saying “please search near 12 Harbour Street”. Nothing has happened yet.

Step 4: Your code runs the tool and returns the result

Your program reads the request, checks that it is allowed and that the arguments make sense, runs the real function (which calls the real restaurant system through its API), and sends the output back to the model as a tool result.

One tool call as a message sequence: user to your code, your code to the model, the model returns a tool request, your code calls the restaurant API and gets a result, sends it back to the model, and the model produces the next request or the final answer

This step is where all of your control lives. Because your code sits between the model and the world, it can refuse a request, ask a person first, limit what data comes back, and write a log line (a record of what happened, kept so it can be checked later).

If the tool fails, return the error as the result (“no such restaurant ID”). The model can often correct itself, but only if it is told what went wrong.

Step 5: The loop repeats

The model now sees the search result and decides the next step: check availability. Your code runs that, returns the result, and so on. This cycle of think → act → observe → repeat is the agent loop. (The pattern of interleaving reasoning with actions was studied in the 2022 paper ReAct by Yao and colleagues.)

One detail is easy to miss: the model has no memory between calls. In the basic setup, on every round your code sends the entire conversation again: instructions, the user’s message, every earlier tool request and every result. The model’s whole “awareness” of the task is that growing list.

Here is the full back-and-forth for our example:

ILLUSTRATIVE EXAMPLE (invented data)

[instructions]   You are a booking assistant. Today is Tuesday 2026-11-17.
                 The user's office is at 12 Harbour Street.
                 Always ask the user to confirm before creating a booking.

[user]           Book me a table for four on Friday evening near the office.

[model → request]  search_restaurants { "near": "12 Harbour Street", "max_walk_min": 10 }
[code  → result]   [ { "id": "r_17", "name": "Luna Trattoria", "walk_min": 4 },
                     { "id": "r_42", "name": "Kobo Sushi",     "walk_min": 6 },
                     { "id": "r_08", "name": "The Oak Grill",  "walk_min": 9 } ]

[model → request]  check_availability { "restaurant_id": "r_17", "date": "2026-11-20", "party_size": 4 }
[code  → result]   { "slots": [] }

[model → request]  check_availability { "restaurant_id": "r_42", "date": "2026-11-20", "party_size": 4 }
[code  → result]   { "slots": ["19:00", "20:30"] }

[model → user]   Luna Trattoria is full on Friday evening. Kobo Sushi, a 6-minute
                 walk away, has a table for four at 19:00 or 20:30. Shall I book 19:00?

[user]           Yes, 19:00.

[model → request]  create_booking { "restaurant_id": "r_42", "date": "2026-11-20", "time": "19:00", "party_size": 4 }
[code  → result]   { "status": "confirmed", "booking_id": "BK-5521" }

[model → user]   Done. Kobo Sushi, Friday 20 November, 19:00, table for four.
                 Booking reference BK-5521.

Notice what nobody scripted. The model turned “Friday” into a date using the instructions, saw an empty list of slots and moved to the next restaurant on its own. That flexibility is the reason to use an agent.

Step 6: A person confirms before anything irreversible

Searching and checking are harmless: run them twice and nothing changes. Creating a booking is different, so the assistant stopped and asked.

In the example the pause comes from a line in the instructions. In a real system I would not rely on that alone, because instructions are a request to the model, not a guarantee. The safer design is in your code: when a request for create_booking arrives, the program itself shows the details to the user and runs the tool only after a “yes”.

Step 7: The loop stops

The loop ends when the model replies with plain text instead of a tool request. That is the normal exit, and a question to the user counts too: in the example the loop paused at “Shall I book 19:00?” and started again when the user answered. You also need exits the model does not control: a maximum number of steps, a spending or time limit, and a rule for what to tell the user when one is hit. Without them, a confused agent can circle indefinitely while you pay for every round.

The parts of an agent

Every agent is assembled from the same six parts:

  • Model: the LLM that reads the situation and chooses the next step.
  • Instructions: the standing rules, role and facts (the system prompt).
  • Tools: the functions the model may ask for, each with a name, description and schema.
  • Memory / context: the list of messages so far. The context window is the limit on how much text the model can read at once. Longer-term memory is simply notes saved somewhere and loaded back in later.
  • Stop conditions: the rules that end the loop.
  • Guardrails: checks in your code around the model: validating arguments, restricting permissions, asking for confirmation.

Single call, workflow or agent?

Not everything with an LLM in it is an agent. Anthropic’s widely cited article Building effective agents draws the line this way: workflows are systems where models and tools follow code paths a developer defined in advance, and agents are systems where the model itself directs the process and decides which tools to use.

Single LLM callWorkflow (fixed chain of steps)Agent
Who decides the stepsThere is one stepThe developer, in codeThe model, while the task runs
Example“Summarise this review”Extract the date and party size, then call the booking API, then write a confirmation“Find and book something suitable for Friday”
PredictabilityHighHighLower
Cost and speedCheapest, fastestFixed and knownVaries per task
TestingEasyStep by stepNeeds evals (repeatable tests, explained below) over whole runs
Best whenOne input, one outputThe steps are always the sameThe steps depend on what is found along the way

A workflow is often the better choice. If every booking request goes through the same three steps in the same order, write those three steps in code and use the model only where language is involved. The same article recommends starting with the simplest solution and adding complexity only when it demonstrably improves results.

Why agents fail in practice, and the basic defences

Demos show the run that worked. These are the ways the others go wrong.

  • Wrong tool choice. The model picks a similar-sounding tool or fills in arguments badly. Defence: few tools, each with a clear description that says when to use it and when not to. OpenAI’s guide gives a soft suggestion of fewer than about 20 functions available at once.
  • Loops. The agent retries the same failing call or wanders between two steps. Defence: step limits, and error messages that say what to change.
  • Context filling up. Every tool result is appended to the message list. Long results crowd the window, earlier details get less attention, and each round costs more. Defence: return only what is needed (three restaurants, not three hundred), and summarise older steps. This is the subject of context engineering: deciding everything the model sees at each step.
  • Compounding errors. A small mistake early (the wrong Friday) silently poisons everything after it. Anthropic’s article names this as a cost of autonomy (letting the model decide on its own). Defence: checkpoints where code or a person verifies key facts before the next stage.
  • Cost and latency. Latency is how long the user waits. One user request may become ten model calls, each re-reading the whole history, and each paid for by the token (a small piece of text the model reads or writes). Defence: budgets, and using a workflow where the path is known. See token economics.

Two defences apply to all of the above. Log every step: each request, result and decision, so that a bad run can be replayed and understood. And build evals: a set of test tasks with known good outcomes that you re-run after every change to a prompt, tool or model. An agent without evals is tuned by anecdote. Start with Evals in 2026.

Safety basics

Least privilege. Give the agent only the tools and permissions its task needs. A booking assistant needs to create bookings, not to issue refunds or read the whole customer database. If something goes wrong, the damage is bounded by what the tools allow.

Untrusted content can contain instructions. Everything the model reads lands in the same stream of text: your rules, the user’s message, and whatever a tool returned. If a restaurant’s description, a web page or an email contains a sentence written to look like a command, the model may follow it. This is called prompt injection; OWASP (a non-profit foundation known for its lists of top software security risks) lists it among the top risks for LLM applications, and calls the variant that arrives through external content indirect prompt injection.

No prompt wording reliably prevents this, so the defences are structural: treat tool results as data to be weighed, keep permissions narrow, and require human approval for actions that spend money, send messages or delete things. The expert on the phone can be misled by something you read out to them. What protects you is that your hands do not do everything the voice says. Securing Agentic Development covers these defences in depth.

Where MCP and RAG fit in

MCP (Model Context Protocol) is an open standard for connecting AI applications to external systems; its own site compares it to a USB-C port for AI applications. A tool is packaged once as an “MCP server” (a small program that offers tools in this standard form) and any compatible application can plug it in, instead of each team writing its own glue code (small custom code that connects one system to another). The mechanics inside the loop do not change: the model still sees a name, a description and a schema. More in What is MCP and why it matters.

RAG (retrieval-augmented generation) means finding relevant passages in your documents and putting them into the model’s input before it answers. Classic RAG is a fixed workflow: always search, then answer. In an agent, retrieval becomes just another tool, say search_documents, that the model may call when it decides it needs to, perhaps several times with different queries. See RAG explained for beginners.

Common mistakes and misconceptions

  • “The AI booked the table.” The model wrote a request. Your code booked the table, which is why your code is where safety and permissions belong.
  • “An agent is a special kind of model.” It is a regular model inside a loop that your code runs.
  • “More tools make a smarter agent.” More tools make the choice harder and the input longer. Start with three good ones.
  • “If the model says it is done, it is done.” A model can write “Booked!” without calling the tool. Trust the tool result, not the prose.
  • “A rule in the prompt is a guarantee.” Instructions shape behaviour most of the time. Anything that must never happen has to be enforced in code.

When you don’t need an agent

  • The steps never change. Use a workflow. It is cheaper, faster and easier to test.
  • One call does the job. Summarising, translating, classifying and drafting need no loop.
  • Mistakes are expensive and hard to undo. Either keep a person approving each important action or do not automate that part.
  • You are considering several agents. In my view, one agent with a handful of well-described tools covers far more than you might expect. Splitting work between agents adds coordination overhead, so treat it as a later step and read Multi-agent systems in 2026: when one agent beats five first.

How to get there

This section is for readers who want to build an agent themselves. If you only wanted to understand how agents work, you can skip it.

A learning order that works for a beginner:

  1. Basic Python and one model API. Python is a popular programming language and the common default; if you already know C#, Java or Go, you can build agents in it. Send a message from code and print the reply.
  2. Structured output. Ask the model for JSON with fixed fields and parse it (read it into your program). This is half of tool calling.
  3. One tool, by hand. Define a single tool (a calculator, or “current time”), receive the tool request, run it yourself, send the result back. No framework (a ready-made library that runs the loop for you) yet: Anthropic’s article also advises starting with the model API directly, so you can see what a framework later hides.
  4. The loop. Wrap step 3 in a while loop (code that repeats until a condition says stop) with a step limit. You now have an agent in a few dozen lines.
  5. A real small agent. Three tools, one of them with a side effect (it changes something outside the program, such as creating a record), plus a confirmation step enforced in code and a log of every round.
  6. Break it and measure it. Write roughly 20–50 test tasks (an example size, not a rule), including awkward ones (no tables free, an ambiguous date). Run them after every change.
  7. Then the wider toolbox. Expose a tool through MCP, add retrieval as a tool, and try a framework or agent SDK (a vendor’s ready-made library for building agents) knowing what it does for you.

Practice projects, in order: a “what’s the weather and should I cycle?” assistant with one tool; a notes assistant that can search, read and create notes in a folder, with confirmation before writing; the booking assistant from this post against a fake restaurant API you write yourself.

Mini glossary

  • LLM (large language model): an AI model that reads and writes text.
  • Tool: a function in your program that the model is allowed to ask for.
  • Tool calling (function calling): the model replying with a structured request to run a tool instead of plain text.
  • Input schema: the formal description of a tool’s inputs.
  • Tool result: the output your code sends back after running a tool.
  • Agent loop: think, act, observe, repeat, until an answer or a stop condition.
  • Workflow: a fixed sequence of model calls and code steps defined by the developer.
  • Context window: the maximum amount of text the model can read in one call.
  • Guardrail: a check in your code that limits what the agent can do.
  • Prompt injection: text inside content the model reads that tries to redirect its behaviour.

Going deeper

Courses: Building LLM-Powered Apps: RAG & Agents builds tool calling and the loop end to end. Building Agents with the Claude Agent SDK covers agents that run for real users, Building MCP Servers & AI Tool Integrations packaging tools to a common standard (MCP), Building with Claude API the underlying API calls, and Prompt Engineering & AI Workflow Automation instructions and fixed workflows.

Related posts: RAG explained for beginners, What is MCP and why it matters, Context engineering, Evals, Token economics and, when one agent stops being enough, Multi-agent systems.

Sources and further reading


This post is part of the “AI engineering from zero” series: The AI engineer roadmap · Vibe coder vs AI engineer vs AI solutions engineer · 8 types of AI models · Embeddings and vector databases · RAG explained for beginners · The 7 layers of an AI system.

Part 6 of 7 in “AI engineering from zero”. Previous: RAG Explained for Beginners: How AI Answers Questions From Your Own Documents · Next: The 7 Engineering Layers of an AI System, Explained from Zero

Share this article
X LinkedIn
Next step

Turn this into a real skill

A structured path from theory to production code — projects and code reviews included.

Advanced 8 weeks

Building LLM-Powered Apps: RAG & Agents

Build production-grade AI applications using large language models. Cover vector databases, retrieval-augmented generation (RAG), autonomous agents, tool use, evaluation, and deployment patterns.

Explore course
Advanced 7 weeks

Building Agents with the Claude Agent SDK

Design and ship custom AI agents with the Claude Agent SDK. Build agent loops, define tools, manage memory and sub-agents, evaluate behavior, and deploy multi-agent systems that solve real engineering tasks autonomously.

Explore course
Advanced 6 weeks

Building MCP Servers & AI Tool Integrations

Master the Model Context Protocol (MCP) — the open standard for connecting AI models to external tools and data, created by Anthropic and now stewarded by the Agentic AI Foundation under the Linux Foundation. Build custom MCP servers, expose APIs to Claude, and architect next-gen AI integrations.

Explore course
Intermediate 6 weeks

Building with Claude API: Production AI Apps with the Anthropic SDK

Master Anthropic's Claude API end-to-end: messages API, prompt caching, tool use, extended thinking, streaming, batch processing, files, citations, and vision. Build cost-efficient, production-grade AI features in any backend.

Explore course
Beginner 4 weeks

Prompt Engineering & AI Workflow Automation

Learn to work effectively with AI models: write high-quality prompts, build automated workflows using Cursor, Copilot, and API tools, and make AI a dependable part of your daily development work.

Explore course
Oleksii Anzhiiak

Written by

Oleksii Anzhiiak

Software Architect, Senior .NET Engineer & Co-Founder

Oleksii Anzhiiak is a Software Architect, Senior .NET Engineer, and Co-Founder of ToyCRM.com and ProfectusLab. With over 15 years of experience, he specializes in distributed systems, cloud infrastructure, high-load backend development, and identity platforms. Oleksii designs complex architectures, builds secure authentication systems, and develops modern engineering education programs that help students achieve real career results.

LinkedIn

Recommended Watching

Hand-picked third-party videos related to this topic. Open on YouTube.

~6:00:00
Intermediate AI Engineer (AI Engineer World's Fair)

AI Engineer World's Fair 2025 — Day 1 Keynotes & MCP Track (ft. Anthropic MCP team)

The MCP track keynote with the Anthropic team. If you want to understand why MCP became the industry-standard protocol for connecting LLMs to tools in 2025, this is the single best primary source.

~2:00:00
Intermediate AI Engineer (Thariq Shihipar, Anthropic)

Claude Agent SDK — Full Workshop (Thariq Shihipar, Anthropic)

A hands-on workshop from Anthropic on building production agents with the Claude Agent SDK — tool use, sub-agents, hooks, MCP servers, and the patterns that scale beyond the demo.

~8:00:00
Intermediate AI Engineer (AI Engineer World's Fair)

AI Engineer World's Fair 2024 — Keynotes & CodeGen Track

The keynote stream from the largest technical AI conference of 2024. A snapshot of the state of AI engineering — what shipped, what worked, what didn't — straight from the teams building it.

Contact us