Module 01 · Lesson 1.1
What Is an AI Agent? Concepts, terminology and examples
On this page
- What you will learn
- A working definition
- Three examples with different levels of autonomy
- Step by step: build a minimal agent loop
- Complete runnable example
- The tool contract the model sees
- Security and reliability from the first line
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- References
"Agent" is one of the most stretched words in software. It is applied to chat assistants, scheduled scripts, browser extensions and almost anything that sounds autonomous. If a team cannot agree on what an agent is, it cannot agree on what to build, how to test it or what it should be allowed to do.
This lesson gives you a working definition that is precise enough to design and review against. You will learn the vocabulary used throughout this program, compare three examples with different levels of autonomy, and run a complete agent loop in about sixty lines of Python. The loop uses a scripted stand-in for the model, so it needs no API key and behaves the same way every time you run it.
What you will learn
- Define an AI agent in terms of a goal, tools, a control loop and stop conditions.
- Use the core vocabulary of agent design: tool call, observation, step, guardrail and human approval.
- Explain why your application, not the model, executes every action.
- Trace a complete agent run and identify where each decision was made.
Before you start
- Python 3.10 or later, and the ability to run a script from a terminal.
- Comfort reading Python functions, dictionaries and loops.
- No API key or paid account: the example runs entirely offline.
A working definition
In this program, an AI agent is software in which a language model repeatedly chooses the next action towards a goal, using tools your application provides, inside a loop your application controls, until a stop condition is met.
Each part of that sentence rules something out. A model that only writes a reply is not choosing actions. A script that calls a model at fixed points is choosing its actions in code, not in the model. And a loop with no stop condition is not an agent design at all; it is an incident waiting to happen.
- Goal
- What the run is trying to achieve, stated precisely enough that you can tell when it has been achieved. For example: answer one customer's question about one order.
- Language model
- The component that reads the goal, the instructions and everything observed so far, then proposes the next action or a final answer. It produces text. It does not execute anything.
- Tool
- A function your application makes available to the model, described by a name, a purpose and a schema for its arguments. Looking up an order is a tool; so is drafting an email for someone to review.
- Tool call
- A structured request from the model to run one tool with specific arguments. It is a request, not an action: your code decides whether to honour it.
- Observation
- The result of a tool call, passed back to the model so it can choose what to do next. Errors are observations too.
- Step
- One pass around the loop: the model decides, then the runtime acts or stops.
- Stop condition
- A rule that ends the run: a final answer, a step or spending limit, too many errors, or a hand-over to a person.
- Guardrail
- A check enforced in code, outside the model, such as an allowlist of tools, argument validation or a cap on steps.
- Human approval
- A point at which a person must confirm an action before it takes effect. Required for anything consequential, such as refunds, payments, outbound messages or deleting data.
- Goal and instructions
The task, its limits and the tools on offer
- Model proposes
A tool call or a final answer
- Runtime checks
Allowed tool? Valid arguments? Approval needed? Steps left?
- Tool runs
Your code calls the real system
- Observation
The result or error goes back to the model
- Stop
Final answer, limit reached or hand-over to a person
One agent run. The loop repeats until a stop condition fires, and only the runtime touches real systems.
Three examples with different levels of autonomy
All three examples belong to Quillfeather Cycles, a fictional online bike-parts shop used throughout this module. Each is an agent by the definition above, but they differ sharply in how much they are allowed to do.
| Example | Tools | What the model decides | What a person decides |
|---|---|---|---|
| Order-status helper | One read-only order lookup | Whether it has enough information, which order to look up and how to phrase the answer | Nothing per request; staff review a sample of conversations |
| Warehouse sync investigator | Read-only access to order records, integration logs and API status | Which evidence to gather next, based on what it has found so far | Whether the proposed diagnosis is right, and applying any fix |
| Warranty claim assistant | Read-only lookups and a tool that files a recommendation for review | Which evidence supports the claim and what to recommend | Every decision to replace, repair or reject |
Autonomy is a design choice, not a property of the model. The same model could sit behind all three. What changes is the set of tools, the permissions behind them and the points at which a person must sign off.
Step by step: build a minimal agent loop
Step 1: Create a project folder
Make a folder for this module. A virtual environment is optional for now, because the example uses only the standard library, but Module 3 installs packages into it.
Bash mkdir agent-foundations cd agent-foundations python -m venv .venv # macOS or Linux source .venv/bin/activate # Windows PowerShell .venv\Scripts\Activate.ps1What you should see: Your prompt shows (.venv), and
python --versionreports 3.10 or later.Step 2: Add fictional data and one read-only tool
ORDERSis a small dictionary of invented orders.lookup_order()returns a dictionary in every case, including an error case, so the model always receives an observation it can reason about instead of an exception.Step 3: Write the model stand-in
call_model()receives the conversation so far and returns either a tool call or a final answer. A real model makes that choice from its instructions, the tool descriptions and the history; this scripted version uses a regular expression so you can predict every step. Later modules replace only this function.Step 4: Write the loop and its guards
run_agent()asks the model for a decision, checks the requested tool against an allowlist, runs it, records the observation and goes round again.MAX_STEPSends the run even if the model never produces a final answer.Step 5: Run it
Save the complete file below as
minimal_agent.pyand runpython minimal_agent.py.What you should see: Three questions, each followed by the steps the loop took and the final answer.
Complete runnable example
"""A minimal agent loop that runs offline.
call_model() is a scripted stand-in for a language model, so you can watch
the loop work without an API key. Later modules swap in a real provider;
the loop around it stays the same.
"""
import json
import re
# Fictional sample data for Quillfeather Cycles. Not real customers or orders.
ORDERS = {
"QF-1042": {"status": "dispatched", "estimated_delivery": "2026-11-18"},
"QF-1043": {"status": "packing", "estimated_delivery": "2026-11-20"},
}
def lookup_order(order_id: str) -> dict:
"""Read-only tool: report one order's status, or an error."""
order = ORDERS.get(order_id)
if order is None:
return {"error": f"no order with id {order_id}"}
return {"order_id": order_id, **order}
TOOLS = {"lookup_order": lookup_order} # the only actions the agent can take
MAX_STEPS = 4 # hard stop, whatever the model wants
def call_model(messages: list[dict]) -> dict:
"""Scripted stand-in for a model: returns a tool call or a final answer."""
last = messages[-1]
if last["role"] == "user":
match = re.search(r"QF-\d{4}", last["content"])
if match is None:
return {"type": "final", "text": "Which order? Order IDs look like QF-1234."}
return {"type": "tool_call", "name": "lookup_order",
"arguments": {"order_id": match.group()}}
result = json.loads(last["content"]) # the most recent tool result
if "error" in result:
return {"type": "final", "text": "I could not find that order ID. Please check it."}
return {"type": "final",
"text": f"Order {result['order_id']} is {result['status']}; "
f"estimated delivery {result['estimated_delivery']}."}
def run_agent(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
for step in range(1, MAX_STEPS + 1):
decision = call_model(messages)
if decision["type"] == "final":
print(f" step {step}: final answer")
return decision["text"]
name, args = decision["name"], decision["arguments"]
print(f" step {step}: model requests {name} {args}")
tool = TOOLS.get(name)
if tool is None:
result = {"error": f"unknown tool {name}"}
else:
try:
result = tool(**args)
except TypeError as exc: # missing or unexpected arguments
result = {"error": f"bad arguments: {exc}"}
# The model sees the result on its next turn, as an observation.
messages.append({"role": "assistant", "content": json.dumps(decision)})
messages.append({"role": "tool", "content": json.dumps(result)})
return "Stopped: step limit reached without a final answer."
if __name__ == "__main__":
for question in ["Where is my order QF-1042?",
"Has QF-9999 shipped yet?",
"Where is my parcel?"]:
print(question)
print(" ->", run_agent(question))Runs offline. The model is scripted; the loop around it is the shape you will keep.
Where is my order QF-1042?
step 1: model requests lookup_order {'order_id': 'QF-1042'}
step 2: final answer
-> Order QF-1042 is dispatched; estimated delivery 2026-11-18.
Has QF-9999 shipped yet?
step 1: model requests lookup_order {'order_id': 'QF-9999'}
step 2: final answer
-> I could not find that order ID. Please check it.
Where is my parcel?
step 1: final answer
-> Which order? Order IDs look like QF-1234.Read the trace for the second question. The model asked for an order that does not exist, the tool returned an error as data, and the model turned that observation into an honest answer. Nothing crashed and nothing was guessed. The third question shows the model deciding that no tool call is possible until the customer supplies an order ID.
The tool contract the model sees
The model never sees your Python function. It sees a contract: a name, a description of what the tool does and when to use it, and a schema for the arguments. Here is a provider-neutral contract for lookup_order, with the arguments described in JSON Schema (opens in a new tab).
{
"name": "lookup_order",
"description": "Look up the current status of one Quillfeather Cycles order. Use it when the customer gives an order ID and asks where the order is or when it will arrive. Read-only: it never changes an order. Returns the status and estimated delivery date, or an error if the ID is unknown.",
"parameters": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "Order ID: QF- followed by four digits, for example QF-1042.",
"pattern": "^QF-[0-9]{4}$"
}
},
"required": ["order_id"],
"additionalProperties": false
}
}The description does as much work as the schema. It says what the tool returns, when to use it and that it is read-only, which helps the model choose correctly and helps a reviewer judge the risk.
Security and reliability from the first line
Even this small loop shows the habits that matter in production.
- Allowlist the tools. The runtime looks the requested name up in
TOOLS. A request for anything else becomes an error observation, never a dynamic import or a shell command. - Bound the loop.
MAX_STEPSis enforced in code. A model that keeps asking for tools, through a bug or a manipulated input, is stopped after four steps. - Start read-only. The only tool reads data. Any tool that changes something, such as a cancellation, a refund or an outbound email, needs argument validation and a human approval step, which Lesson 3 adds.
- Return errors as data. Failures inside a tool become structured observations. The model can explain the problem, the loop keeps its shape and the trace shows what happened.
- Do not let the model invent facts it could look up. The final answer quotes the tool result. When the tool fails, the answer says so instead of guessing a delivery date.
- Keep secrets out of the conversation. When a real tool needs credentials, its code reads them from environment variables. They never appear in instructions, messages or tool results.
Common errors and how to fix them
The loop never ends, or runs up a large bill.
Why it happens: There is no step limit, or the limit exists only in the instructions.
Fix: Enforce a maximum number of steps (and later, tokens and spend) in the runtime, and return a clear stopped result when it is reached.
The agent gives a delivery date that is not in the data.
Why it happens: The model answered from a guess because no tool was called, or a tool error was swallowed.
Fix: Instruct the model to look facts up, confirm in the trace that a tool call happened, and make every tool return an explicit error observation rather than an empty result.
A KeyError or TypeError crashes the run when the model requests a tool.
Why it happens: The runtime calls the requested name directly, or passes arguments without checking them.
Fix: Look tools up in an allowlist and catch argument errors, turning both into error observations, as run_agent() does.
The model says an action was done, but nothing changed.
Why it happens: The interface trusts the model's text instead of the tool result.
Fix: Report actions from the runtime's log of executed tool calls, and treat model prose about actions as unverified.
You cannot tell why the agent did what it did.
Why it happens: Nothing records the decisions, tool calls and observations.
Fix: Print or log every step, as the example does. Module 9 turns this into proper tracing.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Break the loop on purpose
Show that the runtime, not the model, keeps this agent safe. Make three deliberate changes to call_model(), run the script after each, and record what the loop does. Then restore the original and add a second read-only tool.
You will need
minimal_agent.pyfrom this lesson.- Change 1: make
call_model()return alookup_ordertool call on every turn, even after it has a result. - Change 2: make it request a tool called
refund_orderwith the argumentorder_idset toQF-1042. - Change 3: make it call
lookup_orderwith an argument namedidinstead oforder_id. - New tool:
lookup_returns_window(order_id), which returns the last date a return is accepted, from a new fictional field inORDERS.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- For change 1, the scripted model currently branches on the role of the last message; return the tool call before that check.
- Adding a tool means registering it in
TOOLSas well as writing the function. The allowlist is the point. - A simple check such as
"return" in last["content"].lower()is enough for the stand-in model to choose the new tool.
Show a model answer
Change 1 asks for a tool forever, but run_agent() only iterates MAX_STEPS times, so the run ends with the stopped message after four tool calls. The limit is a counter in code, so no wording in any instruction could remove it. Change 2 fails at TOOLS.get(name): refund_order is not in the allowlist, so the runtime records an unknown-tool observation and the scripted model answers from that error. No refund function exists, and even if one were written it would not be reachable until someone registered it. Change 3 reaches the tool but raises TypeError for the unexpected keyword; the try block turns it into a bad arguments observation and the loop continues. For the new tool, a good answer adds a returns_until field to each fictional order, writes lookup_returns_window() to return the order ID and that date or an error dictionary, registers it in TOOLS, and extends call_model() so a user message mentioning a return leads to the new tool instead of lookup_order. The note should name the step limit, the allowlist and the exception handler, and observe that none of them depends on the model behaving well.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The model returns a structured request and your runtime decides whether to run it, then calls the function. That is why allowlists, validation and approval belong in your code. The first option is tempting because people say the model "calls" a tool, but for tools you define, the model only asks. Some providers also run a few built-in tools on their own servers; Module 3 covers that distinction.
Show the answer and explanation
Answer: C. Only the third has a model choosing the next action in a loop with tools. The nightly script is the tempting choice because it uses a model on real data, but code fixes every step and the model never chooses an action, which makes it an LLM workflow rather than an agent.
Show the answer and explanation
Answer: A. Instructions are useful guidance, but a bug, an ambiguous request or a manipulated input can push a model past them. A counter in your loop cannot be talked out of stopping. The second option overstates the problem: models generally follow instructions, which is exactly why the gap is easy to miss in testing.
- Written by
- PromptFable Editorial
- Last updated 13 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.
- Tool use with Claude(opens in a new tab)
Anthropic · Official documentation · Vendor documentation for Anthropic's API, including the round trip for tools your application runs.
- Function calling with the Gemini API(opens in a new tab)
Google · Official documentation · Vendor documentation for function calling in Google's Gemini API.
- OWASP Top 10 for Large Language Model Applications(opens in a new tab)
OWASP Foundation · Official documentation
- What is a schema?(opens in a new tab)
JSON Schema · Official documentation
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.