esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

AI engineering / Beginner / 01.34

AI Agents

What an AI agent is, how it differs from a plain call or a fixed workflow, when it is worth building, and the guards that keep it safe.

11 min readFree

From tools to a whole job

The last lesson, Fine-tuning, ended with a promise: next, AI agents, models that plan and use tools to finish a job. Here they are.

Picture a new assistant on their first day. You do not hand over a script. You say, "Find out if this customer can return the shoes, and tell them the total." The assistant looks things up, does a sum, asks you before anything risky, and comes back when done. An AI agent is a model working like that assistant.

By the end you will know what an agent is, how it differs from a single call and from a fixed workflow, what its parts are, and when it is worth the trouble. You will also run a small agent loop and watch a guard block a risky action.

Key words

Agent
A system where a model decides its own next step, uses tools, and keeps going until the job is done.
Workflow
A system where your code fixes the steps in advance. Models may do some steps, but the path is set.
Tool
A function the model can ask your code to run, like a search or a calculator.
Loop
The same cycle repeated: decide, act, look at the result.
Step limit
A hard cap on how many times the loop may run.
Approval gate
A check that stops a risky action until a person says yes.
Stand-in
A tiny fake used so code runs free. Here, a fixed script plays the model.

What an agent is

The word agent is older than AI chat. Wikipedia says an intelligent agent "is an entity that perceives its environment, takes actions autonomously to achieve goals, and may improve its performance through by acquiring knowledge". It adds that a basic thermostat counts. A thermostat senses the room and acts to reach a goal temperature.

Today the word usually means a model-driven version. Anthropic's article "Building effective agents" says agents are "systems where LLMs dynamically direct their own processes and tool usage, maintaining control over how they accomplish tasks". It also says they are "typically just LLMs using tools based on environmental feedback in a loop".

So the short version is: a model, using tools, in a loop, toward a goal. Autonomously means it picks its own next move instead of following your list. Be careful with the word, though. The same article notes that "Agent" can be defined in several ways, and some people use it for fixed, step-by-step systems too.

You met the loop already in the ReAct lesson: think, act, observe, repeat. You met the tools in the Function Calling lesson: the model asks, your code runs. An agent is those two ideas pointed at a goal, with rules around them.

Call, workflow, or agent

Three setups look alike from outside. They differ in who decides the next step.

  • A single call

    You send one prompt and get one answer. Like asking a friend one question. Cheap, quick, and often enough.

  • A workflow

    Your code runs fixed steps, maybe with a model in some of them. Like a recipe: the order never changes. Anthropic defines workflows as systems where models and tools are "orchestrated through predefined code paths".

  • An agent

    The model chooses what to do next, step by step, and decides when it is done. Like the new assistant who works out their own route.

A recipe is great when the task is the same every time. A person who must find out why a parcel is late cannot follow a recipe, because each case is different. That is where an agent fits.

Tip

Ask one question to tell them apart: could I write every step down before the task starts? If yes, it is a workflow or a single call. If no, it may need an agent.

The parts of an agent

Anthropic calls the basic building block "an LLM enhanced with augmentations such as retrieval, tools, and memory". Add instructions and a loop, and you have the parts of an agent.

  1. 1

    The model

    The part that reads the situation and decides what to do next.

  2. 2

    Instructions

    Plain-language rules that say the goal, the style, and the limits. The System Prompting lesson covers how to write them.

  3. 3

    Tools

    The things it can do: search, calculate, send, create. Each needs a clear name and description, because the model reads them to choose.

  4. 4

    Memory

    What it keeps from earlier steps, such as the results so far. The Memory Systems lesson goes deeper.

  5. 5

    The loop and a stop rule

    The cycle that repeats, plus a clear way to end: the model says it is done, or a limit is reached.

The article says it is crucial for the agent "to gain ground truth from the environment at each step", such as tool results, to check its progress. In plain words: it should look at what really happened, not guess.

It also says agents can pause for human feedback, and that it is common to include stopping conditions, "such as a maximum number of iterations", to maintain control. We will build exactly that next.

Run a small agent

Now the code. It has a tiny FAQ lookup, a calculator that only does sums, and a create_ticket tool that needs approval. Each step is printed so you can follow it.

The planner here is a stand-in. It is a fixed script, not a real model, so the code runs free with no keys and no network. A real model is slower, costs money for every token, can give a different answer each run, and can fail or refuse. Your loop must be ready for all of that.

The prices are made up: 3 items at 12.50 each is just a sum to practise on.

Python
import ast
import operator

FAQ = {
    "return window": "You can return an item within 30 days.",
    "shipping": "Standard shipping takes 3 to 5 days.",
}

def search_faq(query):
    for topic, answer in FAQ.items():
        if topic in query.lower():
            return answer
    return "No answer found."

OPS = {ast.Add: operator.add, ast.Sub: operator.sub,
       ast.Mult: operator.mul, ast.Div: operator.truediv}

def calculator(expression):
    def walk(node):
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in OPS:
            return OPS[type(node.op)](walk(node.left), walk(node.right))
        raise ValueError("not allowed")
    return str(walk(ast.parse(expression, mode="eval").body))

def create_ticket(text):
    return "Ticket #101 created: " + text

TOOLS = {"search_faq": search_faq, "calculator": calculator,
         "create_ticket": create_ticket}
NEEDS_APPROVAL = {"create_ticket"}

# STAND-IN planner: a fixed script, not a real model.
SCRIPT = [
    ("search_faq", "return window"),
    ("calculator", "3 * 12.50"),
    ("create_ticket", "Customer asks for a return"),
    ("final", "Returns are open for 30 days. Three items cost 37.5."),
]

def fake_planner(history):
    return SCRIPT[len(history)]

def stuck_planner(history):
    return ("search_faq", "refund")  # never finishes

def run(planner, max_steps, approved):
    history = []
    for step in range(1, max_steps + 1):
        tool, arg = planner(history)
        if tool == "final":
            print(f"step {step}: FINAL {arg}")
            return
        if tool in NEEDS_APPROVAL and not approved:
            result = "BLOCKED: needs approval"
        else:
            result = TOOLS[tool](arg)
        print(f"step {step}: {tool}({arg!r}) -> {result}")
        history.append((tool, arg, result))
    print(f"STOP: step limit {max_steps} reached")

print("Run 1: approved=False")
run(fake_planner, 5, approved=False)
print("Run 2: approved=True")
run(fake_planner, 5, approved=True)
print("Run 3: stuck planner")
run(stuck_planner, 3, approved=False)
print(calculator("2 * (3 + 4)"))
try:
    calculator("__import__('os')")
except ValueError as e:
    print("calculator refused:", e)

Output

Run 1: approved=False
step 1: search_faq('return window') -> You can return an item within 30 days.
step 2: calculator('3 * 12.50') -> 37.5
step 3: create_ticket('Customer asks for a return') -> BLOCKED: needs approval
step 4: FINAL Returns are open for 30 days. Three items cost 37.5.
Run 2: approved=True
step 1: search_faq('return window') -> You can return an item within 30 days.
step 2: calculator('3 * 12.50') -> 37.5
step 3: create_ticket('Customer asks for a return') -> Ticket #101 created: Customer asks for a return
step 4: FINAL Returns are open for 30 days. Three items cost 37.5.
Run 3: stuck planner
step 1: search_faq('refund') -> No answer found.
step 2: search_faq('refund') -> No answer found.
step 3: search_faq('refund') -> No answer found.
STOP: step limit 3 reached
14
calculator refused: not allowed

Read the three runs. In Run 1, approved is False, so the agent did the safe steps, then the gate blocked create_ticket. The agent still finished and reported. In Run 2, approved is True, so the ticket was created.

Run 3 uses a stuck planner that repeats the same search forever. Without the step limit it would never stop. With the limit of 3, the loop ended and said so. A real model can get stuck the same way.

The calculator uses Python's ast module to read the sum as a tree and allow only numbers and plain arithmetic. That is why it refused the sneaky input in the last line, instead of running it. Never feed model text to eval.

Notice the final answer, 37.5, came from the calculator tool, not from the model's head. Tools give an agent facts it can check.

When an agent is worth it

Anthropic's advice is blunt: "we recommend finding the simplest solution possible, and only increasing complexity when needed". It adds that this "might mean not building agentic systems at all", because they "often trade latency and cost for better task performance". Latency means waiting time.

The article says agents suit "open-ended problems where it's difficult or impossible to predict the required number of steps, and where you can't hardcode a fixed path". It says workflows give "predictability and consistency for well-defined tasks".

One idea is worth keeping in your head. Each extra loop is another model call, so another wait and another bill. A workflow with three fixed steps costs three calls every time. An agent might use two or twenty.

  • Use a single call

    When one good prompt, maybe with a lookup or a few examples, does the job. Anthropic says this is usually enough for many applications.

  • Use a workflow

    When the steps are known: summarise, then translate, then check. It is predictable and easy to test.

  • Use an agent

    When each case is different and you cannot list the steps first, such as fixing a bug across many files or researching a messy question.

Quick check

A form always needs three steps in the same order: read, check, save. What fits best?

Risks and guards

Giving a model freedom has a price. The article says "the autonomous nature of agents means higher costs, and the potential for compounding errors". Compounding means a small early mistake grows as later steps build on it. It recommends "extensive testing in sandboxed environments, along with the appropriate guardrails". A sandbox is a safe test area where mistakes cannot hurt anything real.

  • Cost

    Every loop costs time and tokens. A long run can cost far more than you expected.

  • Loops

    The agent may repeat itself and never finish, like Run 3 above.

  • Wrong actions

    It may pick the wrong tool or send the wrong input. If the tool changes something real, the damage is real too.

The guards are plain code you write around the model. They are not clever. They are the seat belt.

  1. 1

    Cap the steps

    Set a step limit and stop with a clear message when it is reached. Setting a cost cap too is a good habit.

  2. 2

    Gate risky actions

    Reading is safe. Sending, paying, deleting and creating are not. Make them wait for a person, as create_ticket did.

  3. 3

    Log every step

    Print or save each tool, input and result. If something goes wrong, the log shows where. The article stresses transparency by showing the agent's planning steps.

  4. 4

    Test in a sandbox

    Try new agents on fake data first, with tools that cannot do real harm.

Tip

Start every new tool as read-only. Add actions that change things only after you have watched the agent use the read-only ones sensibly.

Quick check

Your agent keeps repeating the same search and never answers. Which guard helps most?

What to remember

An agent is a model that uses tools in a loop toward a goal, choosing its own steps. A single call is one question. A workflow is a recipe your code fixes. Pick the simplest one that works.

The ReAct paper's abstract describes the core idea as models producing "both reasoning traces and task-specific actions in an interleaved manner". The parts around it are yours to build: instructions, tools, memory, and a loop with a stop rule.

Keep the guards on: step limits, approval for risky actions, and logs. Then an agent is a helpful assistant instead of a runaway one.

Next: MCP, a standard plug for connecting models to tools and data.

Sources

How is this lesson?

Last updated on 16 November 2026

Learn with me

Every lesson is free. I add new ones as I learn. Have a question, or want help with your own work? Book a short call.