[{"data":1,"prerenderedAt":420,"buildId":421},["ShallowReactive",2],{"page-\u002Fbuild\u002Fai-agent-tutorial":3},{"id":4,"title":5,"body":6,"description":403,"extension":404,"how_to_steps":405,"hub":384,"meta":406,"navigation":407,"path":408,"primary_keyword":409,"published_at":410,"schema_types":411,"seo":415,"status":416,"stem":417,"updated_at":418,"wave":283,"__hash__":419},"pages\u002Fbuild\u002Fai-agent-tutorial.md","AI Agent Tutorial: Build a Simple Agent That Works",{"type":7,"value":8,"toc":387},"minimark",[9,13,18,21,24,36,40,65,76,90,93,97,102,129,133,142,152,155,163,171,192,196,229,238,242,246,260,266,272,295,299,313,319,326,332,338,349,352,356,362,368],[10,11,12],"p",{},"In this AI agent tutorial, you'll build a small Python program that reviews the headings on a pretend library website.\nAsk it to check the hours page and it will point out where an H1 jumps straight to an H3.\nAsk for a page the library doesn't have and it will stop without trying to read it.\nYou'll run the same program with a scripted model stand-in, so you can see each decision without an AI account or an internet connection.",[14,15,17],"h2",{"id":16},"what-an-agent-is","What an agent is",[10,19,20],{},"An AI agent is a program that uses a model to choose what to do next toward a goal.\nThe 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.\nA 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.\nThe agent loop is the part of the program that repeats this exchange and decides when it has to stop.",[10,22,23],{},"In this exercise the goal is narrower: check the heading order on one named page and report the first problem, if there is one.\nThe first decision is to ask which pages are in the sample site.\nThe next decision depends on the answer: request the headings if the page exists, or finish with a message if it doesn't.\nOnce the headings come back, the program can name a problem using the actual heading text from the sample.",[10,25,26,27,31,32,35],{},"There are two parts to keep straight when you read the code.\nThe function named ",[28,29,30],"code",{},"scripted_model"," makes decisions using rules you can read in Python.\nIt stands in for a model, so the same input and tool results produce the same decision each time.\nA real language model could choose a different next action given the same context, and its explanation could be wrong.\nThe function named ",[28,33,34],{},"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.",[14,37,39],{"id":38},"tools-and-memory-explained","Tools and memory, explained",[10,41,42,43,46,47,50,51,54,55,57,58,60,61,64],{},"A tool is a function the loop can call by name.\nHere, ",[28,44,45],{},"list_pages"," takes no argument and returns the page names, while ",[28,48,49],{},"read_headings"," takes one name and returns that page's headings in order.\nAn argument is the value supplied to a function, such as ",[28,52,53],{},"hours"," when requesting the hours page.\nThe tool names are fixed in ",[28,56,34],{},", and ",[28,59,49],{}," is only called when the supplied name matches an entry in ",[28,62,63],{},"PAGES",".\nA filename would have no special meaning to this program, since the tool only looks up entries in that dictionary.",[10,66,67,68,71,72,75],{},"The decision function requests a tool by returning a pair such as ",[28,69,70],{},"(\"read_headings\", \"hours\")",".\nThat request is data, so it has no effect until the loop checks it and calls the corresponding function.\nThe same pair format lets the decision function say ",[28,73,74],{},"finish"," and supply the message to return.\nThe loop doesn't run the message as code or write it to a file.",[10,77,78,79,82,83,86,87,89],{},"Memory here is a list named ",[28,80,81],{},"history"," that the loop starts fresh for each run.\nEach entry records which tool was called and what came back.\nOn its next turn the decision function sees those entries and can use the page list before asking for headings.\nAn empty history means it hasn't received any results yet.\nNothing gets saved between runs, so checking ",[28,84,85],{},"home"," and then checking ",[28,88,53],{}," starts two independent reviews.",[10,91,92],{},"The limit is three decision turns, including a turn that asks to finish.\nFor a page in the sample, that leaves one turn to list pages, one to read headings, and one to return the review.\nThe missing-page path only needs two turns.\nIf 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.",[14,94,96],{"id":95},"the-first-project","The first project",[98,99,101],"h3",{"id":100},"set-up-a-practice-folder","Set up a practice folder",[10,103,104,105,108,109,112,113,116,117,120,121,124,125,128],{},"You'll need Python 3, a plain text editor, and a terminal.\nRun ",[28,106,107],{},"python3 --version"," to check that your terminal can find Python.\nOn a Windows setup that uses the Python launcher, use ",[28,110,111],{},"py -3"," in place of ",[28,114,115],{},"python3"," in the commands below.\nCreate an empty folder called ",[28,118,119],{},"heading-practice",", open a terminal in it, and save the example as ",[28,122,123],{},"heading_agent.py"," in that folder.\nCopy just the code inside the Python block and check that your editor didn't append ",[28,126,127],{},".txt"," to the filename.\nThere are no packages to install or credentials to enter.",[98,130,132],{"id":131},"read-the-sample-and-run-the-code","Read the sample and run the code",[10,134,135,137,138,141],{},[28,136,63],{}," holds a small set of made-up records, also called a fixture.\nEach heading is a pair: the number ",[28,139,140],{},"1"," means H1, and the text next to it is what a visitor would read on the page.\nThe program does not fetch the pages or parse HTML.\nIt 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.\nComing back up from H3 to H2 is fine because it closes a subsection and starts a new section at the earlier level.",[143,144,150],"pre",{"className":145,"code":147,"language":148,"meta":149},[146],"language-python","import sys\n\nPAGES = {\n    \"home\": (\n        (1, \"Riverbend Library\"),\n        (2, \"Upcoming events\"),\n        (3, \"Saturday story time\"),\n        (2, \"Plan a visit\"),\n    ),\n    \"hours\": ((1, \"Opening hours\"), (3, \"Weekend hours\")),\n    \"contact\": ((2, \"Contact the library\"), (3, \"Front desk\")),\n}\nSTEP_LIMIT = 3\n\n\ndef list_pages():\n    return tuple(PAGES)\n\n\ndef read_headings(page):\n    return PAGES[page]\n\n\ndef scripted_model(page, history):\n    if not history:\n        return (\"list_pages\", None)\n    if len(history) == 1:\n        if page not in history[0][1]:\n            return (\"finish\", f\"No page named '{page}' in the fixture.\")\n        return (\"read_headings\", page)\n\n    headings = history[-1][1]\n    if not headings or headings[0][0] != 1:\n        return (\"finish\", f\"{page}: first heading must be H1.\")\n    for (before, _), (after, title) in zip(headings, headings[1:]):\n        if after > before + 1:\n            return (\"finish\", f\"{page}: H{before} to H{after} at '{title}'.\")\n    return (\"finish\", f\"{page}: no issues found by these two checks.\")\n\n\ndef run(page, decide=scripted_model):\n    history = []\n    for _ in range(STEP_LIMIT):\n        action, value = decide(page, tuple(history))\n        if action == \"finish\":\n            return value\n        if action == \"list_pages\" and value is None:\n            result = list_pages()\n        elif action == \"read_headings\" and isinstance(value, str) and value in PAGES:\n            result = read_headings(value)\n        elif action in (\"list_pages\", \"read_headings\"):\n            return \"Stopped: invalid tool argument.\"\n        else:\n            return f\"Stopped: tool '{action}' is not allowed.\"\n        history.append((action, result))\n    return \"Stopped: step limit reached.\"\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 2:\n        raise SystemExit(\"Usage: python3 heading_agent.py PAGE\")\n    print(run(sys.argv[1]))\n","python","",[28,151,147],{"__ignoreMap":149},[10,153,154],{},"Run the example from the folder where you saved it:",[143,156,161],{"className":157,"code":159,"language":160,"meta":149},[158],"language-sh","python3 heading_agent.py hours\n","sh",[28,162,159],{"__ignoreMap":149},[143,164,169],{"className":165,"code":167,"language":168,"meta":149},[166],"language-text","hours: H1 to H3 at 'Weekend hours'.\n","text",[28,170,167],{"__ignoreMap":149},[10,172,173,174,176,177,180,181,184,185,187,188,191],{},"Find the ",[28,175,53],{}," entry in the fixture.\nIt lists ",[28,178,179],{},"Opening hours"," at level 1 and ",[28,182,183],{},"Weekend hours"," at level 3 immediately after it.\nIn ",[28,186,30],{},", ",[28,189,190],{},"zip(headings, headings[1:])"," pairs each heading with the one that follows it, so the check compares 1 with 3.\nSince 3 is more than one level deeper, the review finishes with the name of the second heading.",[98,193,195],{"id":194},"follow-one-result-through-the-loop","Follow one result through the loop",[10,197,198,199,201,202,204,205,207,208,211,212,214,215,218,219,221,222,224,225,228],{},"For the first call, ",[28,200,34],{}," passes an empty ",[28,203,81],{}," to ",[28,206,30],{}," and gets back ",[28,209,210],{},"(\"list_pages\", None)",".\nIt calls ",[28,213,45],{}," and records the resulting names under that action.\nFor the next call, ",[28,216,217],{},"history[0][1]"," means the result from that first tool entry: the page names, including ",[28,220,53],{},".\nThat is why the next request is ",[28,223,70],{},".\nThe last tool result, ",[28,226,227],{},"history[-1][1]",", is now the ordered headings for that page.\nOn the third turn the decision function uses those headings and asks to finish with the message you saw in the terminal.",[10,230,231,232,234,235,237],{},"If Python says it can't open the file, check the working folder and the saved filename before changing any code.\nIf you see the usage message, add one page name after ",[28,233,123],{},".\nNames are exact in this example, so use ",[28,236,53],{}," in lowercase.",[14,239,241],{"id":240},"testing-your-agent","Testing your agent",[98,243,245],{"id":244},"check-the-result-against-the-sample","Check the result against the sample",[10,247,248,249,251,252,255,256,259],{},"Run these in the same folder and compare the output with the expected lines.\nThe ",[28,250,85],{}," case checks that the program accepts a return to H2 after a subsection.\nThe ",[28,253,254],{},"contact"," case isolates the rule about the first heading because the page goes only one level deeper afterward.\nThe ",[28,257,258],{},"parking"," case checks the response to a name that isn't in the sample.",[143,261,264],{"className":262,"code":263,"language":160,"meta":149},[158],"python3 heading_agent.py home\npython3 heading_agent.py contact\npython3 heading_agent.py parking\n",[28,265,263],{"__ignoreMap":149},[143,267,270],{"className":268,"code":269,"language":168,"meta":149},[166],"home: no issues found by these two checks.\ncontact: first heading must be H1.\nNo page named 'parking' in the fixture.\n",[28,271,269],{"__ignoreMap":149},[10,273,274,275,277,278,204,281,284,285,287,288,291,292,294],{},"Next, change the ",[28,276,183],{}," level from ",[28,279,280],{},"3",[28,282,283],{},"2"," in ",[28,286,63],{},", save the file, and run the hours command again.\nIt should now print ",[28,289,290],{},"hours: no issues found by these two checks.","\nRun the contact case again to confirm that fixing one page left the other page's report unchanged.\nRestore ",[28,293,280],{}," if you want the original failing example back.",[98,296,298],{"id":297},"check-that-the-loop-can-say-no","Check that the loop can say no",[10,300,301,302,305,306,309,310,312],{},"The ",[28,303,304],{},"decide"," parameter lets you swap in a short test function that makes the same request on every turn.\nUse Python's interactive mode so you can try it without creating another file.\nThe ",[28,307,308],{},"-i"," option runs the script first, then leaves you at a Python prompt with ",[28,311,34],{}," available.\nYou should see the home report before the prompt appears.",[143,314,317],{"className":315,"code":316,"language":160,"meta":149},[158],"python3 -i heading_agent.py home\n",[28,318,316],{"__ignoreMap":149},[10,320,321,322,325],{},"Paste these lines at the Python prompt, one at a time.\nA ",[28,323,324],{},"lambda"," here is a short function that accepts the page name and history and returns the specified request, ignoring both inputs.",[143,327,330],{"className":328,"code":329,"language":148,"meta":149},[146],"print(run(\"home\", lambda page, history: (\"write_headings\", \"home\")))\nprint(run(\"home\", lambda page, history: (\"read_headings\", \"notes.txt\")))\nprint(run(\"home\", lambda page, history: (\"list_pages\", None)))\n",[28,331,329],{"__ignoreMap":149},[143,333,336],{"className":334,"code":335,"language":168,"meta":149},[166],"Stopped: tool 'write_headings' is not allowed.\nStopped: invalid tool argument.\nStopped: step limit reached.\n",[28,337,335],{"__ignoreMap":149},[10,339,340,341,344,345,348],{},"The first request is rejected because the loop has no write tool.\nThe second names a real tool but supplies a value that the tool cannot read because ",[28,342,343],{},"notes.txt"," is not a page in the fixture.\nThe third uses a permitted tool and still stops because the test function never asks to finish.\nType ",[28,346,347],{},"exit()"," when you're ready to leave the prompt.\nUse only test functions you trust, since Python runs the function itself before the loop checks the request it returns.",[10,350,351],{},"A clean report means only that the sample passed the two rules in the code.\nFor instance, it says nothing about whether a heading describes the following text clearly or whether the page is usable with a keyboard.\nFor the loop itself, success means the report agrees with the fixture and unexpected requests stop with the matching reason.",[14,353,355],{"id":354},"where-to-go-next","Where to go next",[10,357,358,359,361],{},"Add one more fictional page to ",[28,360,63],{}," before adding a new tool.\nWrite its expected result first, then check that the page list picks up its name without a change to the decision function.\nIf 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.\nThat keeps the experiment small enough to tell whether a mistake came from the sample or the review rule.",[10,363,364,365,367],{},"A real model would replace the scripted decisions with proposed tool requests and answers.\nTreat those requests as data and check their shape and arguments in the program before acting on them.\nKeep the tool list and step limit in the loop, where the program can enforce them independently of what the model says.\nBefore trusting a model's report, compare it with the tool results, just as you did with ",[28,366,183],{},".",[10,369,370,371,376,377,381,382,386],{},"Read about ",[372,373,375],"a",{"href":374},"\u002Fbuild\u002Fwhat-is-an-ai-coding-agent","what an AI coding agent does"," to see how the same basic loop applies when the task is editing code.\nIf you're choosing a tool for a small site, ",[372,378,380],{"href":379},"\u002Fbuild\u002Fvibe-coding-tools","compare the leading vibe coding tools",".\nThe ",[372,383,385],{"href":384},"\u002Fbuild","Build with AI hub"," has other projects you can try once you've worked through this one.",{"title":149,"searchDepth":388,"depth":388,"links":389},2,[390,391,392,398,402],{"id":16,"depth":388,"text":17},{"id":38,"depth":388,"text":39},{"id":95,"depth":388,"text":96,"children":393},[394,396,397],{"id":100,"depth":395,"text":101},3,{"id":131,"depth":395,"text":132},{"id":194,"depth":395,"text":195},{"id":240,"depth":388,"text":241,"children":399},[400,401],{"id":244,"depth":395,"text":245},{"id":297,"depth":395,"text":298},{"id":354,"depth":388,"text":355},"A step-by-step AI agent tutorial in plain language: what an agent is, how tools and memory work, and a first project you can finish.","md",[100,131,244,297],{},true,"\u002Fbuild\u002Fai-agent-tutorial","ai agent tutorial","2026-12-01T06:24:13Z",[412,413,414],"Article","BreadcrumbList","HowTo",{"title":5,"description":403},"draft","build\u002Fai-agent-tutorial",null,"Gwl8AfJSuVo-_6nOmtK0vdkOJUQ4hYSXMfEtrqNMzV8",1796185435708,"a1d53563-3a78-4678-8315-e5bd6a5bd80c"]