What an agent is
Permalink:An AI agent is a program that uses a model to choose what to do next toward a goal. The program can give the model a choice of tools, run an allowed tool on its behalf, and show it the result before asking for another decision. A tool might look up a town library's opening hours, for example, and the result might tell the model whether it has enough information to answer. The agent loop is the part of the program that repeats this exchange and decides when it has to stop.
In this exercise the goal is narrower: check the heading order on one named page and report the first problem, if there is one. The first decision is to ask which pages are in the sample site. The next decision depends on the answer: request the headings if the page exists, or finish with a message if it doesn't. Once the headings come back, the program can name a problem using the actual heading text from the sample.
There are two parts to keep straight when you read the code.
The function named scripted_model makes decisions using rules you can read in Python.
It stands in for a model, so the same input and tool results produce the same decision each time.
A real language model could choose a different next action given the same context, and its explanation could be wrong.
The function named run is the working loop: it checks each request, calls an allowed tool, records the result, and enforces a limit even if the decision maker never asks to finish.
Tools and memory, explained
Permalink:A tool is a function the loop can call by name.
Here, list_pages takes no argument and returns the page names, while read_headings takes one name and returns that page's headings in order.
An argument is the value supplied to a function, such as hours when requesting the hours page.
The tool names are fixed in run, and read_headings is only called when the supplied name matches an entry in PAGES.
A filename would have no special meaning to this program, since the tool only looks up entries in that dictionary.
The decision function requests a tool by returning a pair such as ("read_headings", "hours").
That request is data, so it has no effect until the loop checks it and calls the corresponding function.
The same pair format lets the decision function say finish and supply the message to return.
The loop doesn't run the message as code or write it to a file.
Memory here is a list named history that the loop starts fresh for each run.
Each entry records which tool was called and what came back.
On its next turn the decision function sees those entries and can use the page list before asking for headings.
An empty history means it hasn't received any results yet.
Nothing gets saved between runs, so checking home and then checking hours starts two independent reviews.
The limit is three decision turns, including a turn that asks to finish. For a page in the sample, that leaves one turn to list pages, one to read headings, and one to return the review. The missing-page path only needs two turns. If a faulty decision function keeps asking for the same valid tool, the third call may still run, but the loop won't give it a fourth turn.
The first project
Permalink:Set up a practice folder
Permalink:You'll need Python 3, a plain text editor, and a terminal.
Run python3 --version to check that your terminal can find Python.
On a Windows setup that uses the Python launcher, use py -3 in place of python3 in the commands below.
Create an empty folder called heading-practice, open a terminal in it, and save the example as heading_agent.py in that folder.
Copy just the code inside the Python block and check that your editor didn't append .txt to the filename.
There are no packages to install or credentials to enter.
Read the sample and run the code
Permalink:PAGES holds a small set of made-up records, also called a fixture.
Each heading is a pair: the number 1 means H1, and the text next to it is what a visitor would read on the page.
The program does not fetch the pages or parse HTML.
It uses the sample to check two rules for this project: the first heading should be H1, and the next heading should not jump more than one level deeper.
Coming back up from H3 to H2 is fine because it closes a subsection and starts a new section at the earlier level.
import sys
PAGES = {
"home": (
(1, "Riverbend Library"),
(2, "Upcoming events"),
(3, "Saturday story time"),
(2, "Plan a visit"),
),
"hours": ((1, "Opening hours"), (3, "Weekend hours")),
"contact": ((2, "Contact the library"), (3, "Front desk")),
}
STEP_LIMIT = 3
def list_pages():
return tuple(PAGES)
def read_headings(page):
return PAGES[page]
def scripted_model(page, history):
if not history:
return ("list_pages", None)
if len(history) == 1:
if page not in history[0][1]:
return ("finish", f"No page named '{page}' in the fixture.")
return ("read_headings", page)
headings = history[-1][1]
if not headings or headings[0][0] != 1:
return ("finish", f"{page}: first heading must be H1.")
for (before, _), (after, title) in zip(headings, headings[1:]):
if after > before + 1:
return ("finish", f"{page}: H{before} to H{after} at '{title}'.")
return ("finish", f"{page}: no issues found by these two checks.")
def run(page, decide=scripted_model):
history = []
for _ in range(STEP_LIMIT):
action, value = decide(page, tuple(history))
if action == "finish":
return value
if action == "list_pages" and value is None:
result = list_pages()
elif action == "read_headings" and isinstance(value, str) and value in PAGES:
result = read_headings(value)
elif action in ("list_pages", "read_headings"):
return "Stopped: invalid tool argument."
else:
return f"Stopped: tool '{action}' is not allowed."
history.append((action, result))
return "Stopped: step limit reached."
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit("Usage: python3 heading_agent.py PAGE")
print(run(sys.argv[1]))
Run the example from the folder where you saved it:
python3 heading_agent.py hours
hours: H1 to H3 at 'Weekend hours'.
Find the hours entry in the fixture.
It lists Opening hours at level 1 and Weekend hours at level 3 immediately after it.
In scripted_model, zip(headings, headings[1:]) pairs each heading with the one that follows it, so the check compares 1 with 3.
Since 3 is more than one level deeper, the review finishes with the name of the second heading.
Follow one result through the loop
Permalink:For the first call, run passes an empty history to scripted_model and gets back ("list_pages", None).
It calls list_pages and records the resulting names under that action.
For the next call, history[0][1] means the result from that first tool entry: the page names, including hours.
That is why the next request is ("read_headings", "hours").
The last tool result, history[-1][1], is now the ordered headings for that page.
On the third turn the decision function uses those headings and asks to finish with the message you saw in the terminal.
If Python says it can't open the file, check the working folder and the saved filename before changing any code.
If you see the usage message, add one page name after heading_agent.py.
Names are exact in this example, so use hours in lowercase.
Testing your agent
Permalink:Check the result against the sample
Permalink:Run these in the same folder and compare the output with the expected lines.
The home case checks that the program accepts a return to H2 after a subsection.
The contact case isolates the rule about the first heading because the page goes only one level deeper afterward.
The parking case checks the response to a name that isn't in the sample.
python3 heading_agent.py home
python3 heading_agent.py contact
python3 heading_agent.py parking
home: no issues found by these two checks.
contact: first heading must be H1.
No page named 'parking' in the fixture.
Next, change the Weekend hours level from 3 to 2 in PAGES, save the file, and run the hours command again.
It should now print hours: no issues found by these two checks.
Run the contact case again to confirm that fixing one page left the other page's report unchanged.
Restore 3 if you want the original failing example back.
Check that the loop can say no
Permalink:The decide parameter lets you swap in a short test function that makes the same request on every turn.
Use Python's interactive mode so you can try it without creating another file.
The -i option runs the script first, then leaves you at a Python prompt with run available.
You should see the home report before the prompt appears.
python3 -i heading_agent.py home
Paste these lines at the Python prompt, one at a time.
A lambda here is a short function that accepts the page name and history and returns the specified request, ignoring both inputs.
print(run("home", lambda page, history: ("write_headings", "home")))
print(run("home", lambda page, history: ("read_headings", "notes.txt")))
print(run("home", lambda page, history: ("list_pages", None)))
Stopped: tool 'write_headings' is not allowed.
Stopped: invalid tool argument.
Stopped: step limit reached.
The first request is rejected because the loop has no write tool.
The second names a real tool but supplies a value that the tool cannot read because notes.txt is not a page in the fixture.
The third uses a permitted tool and still stops because the test function never asks to finish.
Type exit() when you're ready to leave the prompt.
Use only test functions you trust, since Python runs the function itself before the loop checks the request it returns.
A clean report means only that the sample passed the two rules in the code. For instance, it says nothing about whether a heading describes the following text clearly or whether the page is usable with a keyboard. For the loop itself, success means the report agrees with the fixture and unexpected requests stop with the matching reason.
Where to go next
Permalink:Add one more fictional page to PAGES before adding a new tool.
Write its expected result first, then check that the page list picks up its name without a change to the decision function.
If you want to try headings from a page you've made, copy their levels and text into the fixture by hand and compare the report with what you see in your editor.
That keeps the experiment small enough to tell whether a mistake came from the sample or the review rule.
A real model would replace the scripted decisions with proposed tool requests and answers.
Treat those requests as data and check their shape and arguments in the program before acting on them.
Keep the tool list and step limit in the loop, where the program can enforce them independently of what the model says.
Before trusting a model's report, compare it with the tool results, just as you did with Weekend hours.
Read about what an AI coding agent does to see how the same basic loop applies when the task is editing code. If you're choosing a tool for a small site, compare the leading vibe coding tools. The Build with AI hub has other projects you can try once you've worked through this one.