{"id":322,"date":"2026-12-01T14:38:11","date_gmt":"2026-12-01T14:38:11","guid":{"rendered":"https:\/\/devdojo.co.in\/?p=322"},"modified":"2026-12-01T14:38:11","modified_gmt":"2026-12-01T14:38:11","slug":"agentic-ai-series-part-4-build-ai-agent-python","status":"publish","type":"post","link":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/","title":{"rendered":"Agentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)"},"content":{"rendered":"\n<div class=\"dd-post\">\n<style>\n.single article:has(.dd-hero) .entry-media{display:none}\n.dd-post{--navy:#0b1020;--blue:#3178c6;--violet:#7c5cff;--ink:#1f2433;--muted:#5b6275;--line:#e3e6ef;font-size:17px;line-height:1.75;color:var(--ink)}\n.dd-post h2{margin:2.2em 0 .6em;font-size:1.6em;line-height:1.3;scroll-margin-top:90px}\n.dd-post h3{margin:1.6em 0 .5em;font-size:1.22em;scroll-margin-top:90px}\n.dd-post a{color:var(--blue);text-decoration:underline;text-underline-offset:3px}\n.dd-post pre{background:#0f1430;color:#e6e9f5;padding:18px 20px;border-radius:12px;overflow-x:auto;line-height:1.6;border:1px solid #232a52;margin:1.2em 0;font-size:14.5px !important}\n.dd-post pre code{font-size:1em !important;background:none;color:inherit;padding:0;font-family:\"JetBrains Mono\",\"Fira Code\",Consolas,Menlo,monospace;white-space:pre}\n.dd-post :not(pre)>code{background:#eef1fb;color:#2b3a8f;padding:2px 6px;border-radius:5px;font-size:.9em}\n.dd-post .dd-file{display:inline-block;background:#151b3b;color:#c9d1ff;font:600 13px\/1 \"JetBrains Mono\",Consolas,monospace;padding:7px 12px;border-radius:8px 8px 0 0;margin:1em 0 -1.2em;position:relative}\n.dd-post .dd-hero{margin:0 0 1.6em;border-radius:16px;overflow:hidden;box-shadow:0 10px 30px rgba(11,16,32,.25)}\n.dd-post .dd-hero svg{display:block;width:100%;height:auto}\n.dd-post .dd-hero .node{transition:transform .25s,filter .25s;transform-box:fill-box;transform-origin:center;cursor:pointer}\n.dd-post .dd-hero .node:hover{transform:scale(1.08);filter:drop-shadow(0 0 10px #7c5cff)}\n.dd-post .dd-series{display:inline-flex;align-items:center;gap:8px;background:#151b3b;color:#dfe3ff;border-radius:999px;padding:6px 14px;font-size:.88em;font-weight:600;margin:0 0 .8em}\n.dd-post .dd-series span{background:var(--violet);color:#fff;border-radius:999px;padding:2px 10px}\n.dd-post .dd-prereq{font-size:.96em;color:var(--muted);border-left:3px solid var(--line);padding-left:12px;margin:.6em 0 1.2em}\n.dd-post .dd-summary{background:linear-gradient(135deg,#eef3ff,#f4efff);border:1px solid #d6dcf5;border-left:5px solid var(--violet);border-radius:12px;padding:18px 22px;margin:1.4em 0}\n.dd-post .dd-summary strong.lbl{display:block;font-size:1.05em;margin-bottom:6px;color:#3a2fa0}\n.dd-post .dd-summary ul{margin:.3em 0 0 1.1em}\n.dd-post .dd-toc{background:#f8f9fc;border:1px solid var(--line);border-radius:12px;padding:16px 22px;margin:1.4em 0}\n.dd-post .dd-toc ol{margin:.4em 0 0 1.2em;columns:2;column-gap:28px}\n.dd-post .dd-toc li{break-inside:avoid;margin:.15em 0}\n@media(max-width:640px){.dd-post .dd-toc ol{columns:1}}\n.dd-post .dd-tip,.dd-post .dd-note,.dd-post .dd-warn{border-radius:10px;padding:14px 18px;margin:1.3em 0}\n.dd-post .dd-tip{background:#ecfbf3;border-left:4px solid #1f9d61}\n.dd-post .dd-note{background:#eef4ff;border-left:4px solid var(--blue)}\n.dd-post .dd-warn{background:#fff6e8;border-left:4px solid #e08a00}\n.dd-post .dd-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px;margin:1.3em 0}\n.dd-post .dd-card{border:1px solid var(--line);border-radius:12px;padding:14px 16px;background:#fff;box-shadow:0 2px 8px rgba(20,30,70,.05)}\n.dd-post .dd-card b{display:block;color:#3a2fa0;margin-bottom:4px}\n.dd-post table{width:100%;border-collapse:collapse;margin:1.3em 0;font-size:.95em}\n.dd-post th,.dd-post td{border:1px solid var(--line);padding:10px 12px;text-align:left;vertical-align:top}\n.dd-post th{background:#151b3b;color:#fff}\n.dd-post tr:nth-child(even) td{background:#f8f9fc}\n.dd-post .dd-tablewrap{overflow-x:auto}\n.dd-post figure{margin:1.6em 0;text-align:center}\n.dd-post figure svg{width:100%;height:auto;border-radius:12px}\n.dd-post figcaption{font-size:.9em;color:var(--muted);margin-top:8px}\n.dd-post details{border:1px solid var(--line);border-radius:10px;padding:12px 16px;margin:.7em 0;background:#fff}\n.dd-post details summary{cursor:pointer;font-weight:600}\n.dd-post details[open] summary{margin-bottom:8px;color:#3a2fa0}\n.dd-post .dd-roadmap{border:2px solid #d6dcf5;background:#fbfbff}\n.dd-post .dd-roadmap h4{margin:1em 0 .3em;color:#151b3b;font-size:1em;text-transform:uppercase;letter-spacing:.04em}\n.dd-post .dd-roadmap ol{margin:.2em 0 .6em 1.4em;padding:0}\n.dd-post .dd-roadmap li{margin:.2em 0}\n.dd-post .dd-roadmap .here{background:var(--violet);color:#fff;border-radius:999px;padding:1px 9px;font-size:.8em;font-weight:700;margin-left:6px}\n.dd-post .dd-roadmap .soon{color:#8a90a6;font-size:.82em;margin-left:6px}\n.dd-post .dd-tabs{border:1px solid var(--line);border-radius:12px;padding:6px 16px 16px;margin:1.4em 0;background:#fbfbfe}\n.dd-post .dd-tabs>input{position:absolute;opacity:0;pointer-events:none}\n.dd-post .dd-tabs .labels label{display:inline-block;padding:8px 16px;margin:10px 6px 0 0;border-radius:999px;border:1px solid #cfd5ea;cursor:pointer;font-weight:600;font-size:.95em;background:#fff;transition:background .2s}\n.dd-post .dd-tabs .labels label:hover{border-color:var(--violet)}\n.dd-post .dd-tabs .panel{display:none;margin-top:12px}\n.dd-post .dd-tabs #ti1:checked~.labels label[for=ti1],.dd-post .dd-tabs #ti2:checked~.labels label[for=ti2],.dd-post .dd-tabs #ti3:checked~.labels label[for=ti3],.dd-post .dd-tabs #ti4:checked~.labels label[for=ti4]{background:var(--violet);color:#fff;border-color:var(--violet)}\n.dd-post .dd-tabs #ti1:checked~.p1,.dd-post .dd-tabs #ti2:checked~.p2,.dd-post .dd-tabs #ti3:checked~.p3,.dd-post .dd-tabs #ti4:checked~.p4{display:block}\n.dd-post .dd-tabs #ti1:focus-visible~.labels label[for=ti1],.dd-post .dd-tabs #ti2:focus-visible~.labels label[for=ti2],.dd-post .dd-tabs #ti3:focus-visible~.labels label[for=ti3],.dd-post .dd-tabs #ti4:focus-visible~.labels label[for=ti4]{outline:2px solid var(--blue);outline-offset:2px}\n.dd-post .dd-cta{background:linear-gradient(135deg,#0b1020,#151b3b);color:#e8ebff;border-radius:16px;padding:24px 26px;margin:2em 0;text-align:center}\n.dd-post .dd-cta h3{color:#fff;margin-top:0}\n.dd-post .dd-cta a{color:#a99bff}\n.dd-post .dd-vsc{position:relative;margin:1.5em 0;border-radius:12px;overflow:hidden;background:#1e1e1e;border:1px solid #2b2b2b;box-shadow:0 14px 34px rgba(0,0,0,.28);font-family:\"Segoe UI\",system-ui,sans-serif}\n.dd-post .dd-vsc>input{position:absolute;opacity:0;pointer-events:none}\n.dd-post .dd-vsc-bar{display:flex;align-items:center;gap:12px;background:#323233;color:#cccccc;font-size:12.5px;padding:8px 12px}\n.dd-post .dd-dots{display:inline-flex;gap:7px}.dd-post .dd-dots i{width:12px;height:12px;border-radius:50%;background:#ff5f57;display:block}.dd-post .dd-dots i:nth-child(2){background:#febc2e}.dd-post .dd-dots i:nth-child(3){background:#28c840}\n.dd-post .dd-vsc-title{flex:1;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-right:50px;opacity:.85}\n.dd-post .dd-vsc-tabs{display:flex;align-items:stretch;background:#252526;border-bottom:1px solid #1e1e1e;overflow-x:auto}\n.dd-post .dd-vsc-tabs label{display:flex;align-items:center;gap:7px;padding:9px 16px;color:#969696;font-size:13px;cursor:pointer;background:#2d2d2d;border-right:1px solid #252526;border-top:1px solid transparent;white-space:nowrap;margin:0;transition:color .15s}\n.dd-post .dd-vsc-tabs label:hover{color:#e0e0e0}\n.dd-post .dd-vsc-tabs .ic{font:700 9.5px\/1 Consolas,monospace;padding:3px 4px;border-radius:3px;color:#1e1e1e}\n.dd-post .ic.py{background:#ffd43b}.dd-post .ic.js{background:#f1e05a}.dd-post .ic.sh{background:#89e051}\n.dd-post .dd-vsc-tabs label.run{margin-left:auto;background:transparent;border:0;color:#89d185;font-weight:600;display:none}\n.dd-post .dd-vsc-tabs label.run:hover{color:#b5f0b0;background:#2a2d2e}\n.dd-post .dd-vsc-pane{display:none}\n.dd-post .dd-vsc>.f1:checked~.dd-vsc-tabs .t1,.dd-post .dd-vsc>.f2:checked~.dd-vsc-tabs .t2,.dd-post .dd-vsc>.f3:checked~.dd-vsc-tabs .t3{background:#1e1e1e;color:#ffffff;border-top-color:#3178c6}\n.dd-post .dd-vsc>.f1:checked~.p1,.dd-post .dd-vsc>.f2:checked~.p2,.dd-post .dd-vsc>.f3:checked~.p3{display:block}\n.dd-post .dd-vsc>.f1:checked~.dd-vsc-tabs .run1,.dd-post .dd-vsc>.f2:checked~.dd-vsc-tabs .run2,.dd-post .dd-vsc>.f3:checked~.dd-vsc-tabs .run3{display:flex}\n.dd-post .dd-vsc>.f1:focus-visible~.dd-vsc-tabs .t1,.dd-post .dd-vsc>.f2:focus-visible~.dd-vsc-tabs .t2,.dd-post .dd-vsc>.f3:focus-visible~.dd-vsc-tabs .t3,.dd-post .dd-vsc>input[type=checkbox]:focus-visible~.dd-vsc-tabs .run{outline:2px solid #3178c6;outline-offset:-2px}\n.dd-post .dd-vsc-crumbs{background:#1e1e1e;color:#a9a9a9;font-size:12px;padding:5px 16px 2px}\n.dd-post .dd-vsc pre.dd-vsc-code{background:#1e1e1e;color:#d4d4d4;border:0;border-radius:0;margin:0;padding:8px 0 14px;counter-reset:ln;line-height:1.62;overflow-x:auto}\n.dd-post .dd-vsc pre code{font-family:Consolas,\"JetBrains Mono\",\"Fira Code\",Menlo,monospace;color:inherit;background:none;white-space:pre}\n.dd-post .dd-vsc .l{display:inline-block;min-width:100%;padding-right:18px;box-sizing:border-box}\n.dd-post .dd-vsc .l::before{counter-increment:ln;content:counter(ln);display:inline-block;width:3.2em;padding-right:1.4em;text-align:right;color:#6e7681;user-select:none;-webkit-user-select:none}\n.dd-post .dd-vsc .l:hover{background:#2a2d2e}.dd-post .dd-vsc .l:hover::before{color:#c6c6c6}\n.dd-post .dd-vsc .k,.dd-post .dd-vsc .kn{color:#c586c0}.dd-post .dd-vsc .kc{color:#569cd6}.dd-post .dd-vsc .s{color:#ce9178}.dd-post .dd-vsc .c{color:#6a9955}.dd-post .dd-vsc .m{color:#b5cea8}.dd-post .dd-vsc .nf{color:#dcdcaa}.dd-post .dd-vsc .nc{color:#4ec9b0}.dd-post .dd-vsc .nb{color:#4ec9b0}.dd-post .dd-vsc .nd{color:#dcdcaa}.dd-post .dd-vsc .n{color:#9cdcfe}.dd-post .dd-vsc .o{color:#d4d4d4}.dd-post .dd-vsc .gp{color:#89d185;user-select:none;-webkit-user-select:none}\n.dd-post .dd-vsc-term{display:none;border-top:1px solid #3c3c3c;background:#181818}\n.dd-post .dd-vsc>.r1:checked~.p1 .dd-vsc-term,.dd-post .dd-vsc>.r2:checked~.p2 .dd-vsc-term,.dd-post .dd-vsc>.r3:checked~.p3 .dd-vsc-term{display:block;animation:ddterm .35s ease-out}\n@keyframes ddterm{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}\n.dd-post .dd-term-head{display:flex;gap:18px;align-items:center;font-size:11px;letter-spacing:.06em;color:#8b8b8b;padding:7px 16px 0}\n.dd-post .dd-term-head span:first-child{color:#e7e7e7;border-bottom:1px solid #e7e7e7;padding-bottom:4px}\n.dd-post .dd-term-head .dd-term-note{margin-left:auto;letter-spacing:0;text-transform:none;color:#d7ba7d;border:0;font-size:11.5px}\n.dd-post .dd-vsc-term pre{background:#181818;color:#cccccc;border:0;margin:0;padding:10px 16px 14px;border-radius:0}\n.dd-post .dd-vsc-status{display:flex;flex-wrap:wrap;gap:4px 14px;background:#007acc;color:#fff;font-size:11.5px;padding:4px 12px}\n.dd-post .dd-vsc-status .sp{flex:1}\n.dd-post .dd-vsc-termonly pre.dd-vsc-code{background:#181818;padding:12px 16px}\n@media(max-width:640px){.dd-post .dd-vsc-title{padding-right:0;text-align:left}.dd-post .dd-vsc-status span:nth-child(n+4){display:none}.dd-post .dd-vsc .l::before{width:2.2em;padding-right:1em}}\n.dd-post .dd-vsc-hint{font-size:.93em;color:var(--muted);margin-top:-.6em}\n.dd-post .dd-next{border:1px dashed var(--violet);border-radius:12px;padding:16px 20px;margin:1.6em 0;background:#f7f4ff}\n<\/style>\n\n<div class=\"dd-hero\">\n<svg viewBox=\"0 0 1200 520\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"Agentic AI series Part 4 banner: a Python agent loop that thinks, calls tools, observes results and remembers the conversation\">\n<defs>\n<linearGradient id=\"ddbg\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop offset=\"0\" stop-color=\"#0b1020\"\/><stop offset=\"1\" stop-color=\"#151b3b\"\/><\/linearGradient>\n<linearGradient id=\"ddac\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\"><stop offset=\"0\" stop-color=\"#3178c6\"\/><stop offset=\"1\" stop-color=\"#7c5cff\"\/><\/linearGradient>\n<radialGradient id=\"ddglow\" cx=\".5\" cy=\".5\" r=\".5\"><stop offset=\"0\" stop-color=\"#7c5cff\" stop-opacity=\".45\"\/><stop offset=\"1\" stop-color=\"#7c5cff\" stop-opacity=\"0\"\/><\/radialGradient>\n<\/defs>\n<rect x=\"0\" y=\"-60\" width=\"1200\" height=\"640\" fill=\"url(#ddbg)\"\/>\n<circle cx=\"900\" cy=\"280\" r=\"270\" fill=\"url(#ddglow)\"\/>\n<g opacity=\".12\" stroke=\"#9fb2ff\"><path d=\"M0 100H1200M0 200H1200M0 300H1200M0 400H1200M200 0V520M400 0V520M600 0V520M800 0V520M1000 0V520\"\/><\/g>\n<rect x=\"60\" y=\"46\" width=\"128\" height=\"38\" rx=\"19\" fill=\"url(#ddac)\"\/>\n<text x=\"124\" y=\"71\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">PART 4<\/text>\n<text x=\"204\" y=\"71\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"18\" fill=\"#aab4e8\">Agentic AI Series \u00b7 DevDojo<\/text>\n<text x=\"60\" y=\"150\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"52\" font-weight=\"800\" fill=\"#ffffff\">Build Your First<\/text>\n<text x=\"60\" y=\"210\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"52\" font-weight=\"800\" fill=\"url(#ddac)\">AI Agent in Python<\/text>\n<text x=\"60\" y=\"258\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"24\" fill=\"#c9d1ff\">From scratch, no framework: model, tools,<\/text>\n<text x=\"60\" y=\"290\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"24\" fill=\"#c9d1ff\">instructions and memory in ~40 lines<\/text>\n<g fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".75\">\n<path id=\"ddp1\" d=\"M900 158 C 1010 170, 1060 210, 1060 250\"\/>\n<path id=\"ddp2\" d=\"M1060 330 C 1060 380, 1000 420, 900 420\"\/>\n<path id=\"ddp3\" d=\"M800 420 C 720 410, 690 370, 690 330\"\/>\n<path id=\"ddp4\" d=\"M690 250 C 690 200, 730 165, 800 158\"\/>\n<\/g>\n<g class=\"node\"><rect x=\"780\" y=\"120\" width=\"140\" height=\"62\" rx=\"14\" fill=\"#1b2250\" stroke=\"#3178c6\" stroke-width=\"2\"\/><text x=\"850\" y=\"148\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"20\" font-weight=\"800\" fill=\"#fff\">Think<\/text><text x=\"850\" y=\"169\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"13\" fill=\"#aab4e8\">model decides<\/text><\/g>\n<g class=\"node\"><rect x=\"990\" y=\"250\" width=\"140\" height=\"80\" rx=\"14\" fill=\"#0b1020\" stroke=\"url(#ddac)\" stroke-width=\"3\"\/><text x=\"1060\" y=\"282\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"20\" font-weight=\"800\" fill=\"#fff\">Act<\/text><text x=\"1060\" y=\"306\" text-anchor=\"middle\" font-family=\"Consolas,monospace\" font-size=\"14\" fill=\"#61dafb\">run_tool()<\/text><\/g>\n<g class=\"node\"><rect x=\"780\" y=\"390\" width=\"140\" height=\"62\" rx=\"14\" fill=\"#1b2250\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"850\" y=\"418\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"20\" font-weight=\"800\" fill=\"#fff\">Observe<\/text><text x=\"850\" y=\"439\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"13\" fill=\"#aab4e8\">read the result<\/text><\/g>\n<g class=\"node\"><rect x=\"620\" y=\"250\" width=\"140\" height=\"80\" rx=\"14\" fill=\"#0b1020\" stroke=\"#61dafb\" stroke-width=\"2\"\/><text x=\"690\" y=\"282\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"20\" font-weight=\"800\" fill=\"#fff\">Memory<\/text><text x=\"690\" y=\"306\" text-anchor=\"middle\" font-family=\"Consolas,monospace\" font-size=\"14\" fill=\"#61dafb\">self.history<\/text><\/g>\n<g class=\"node\"><circle cx=\"875\" cy=\"290\" r=\"48\" fill=\"#151b3b\" stroke=\"url(#ddac)\" stroke-width=\"3\"\/><text x=\"875\" y=\"285\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"16\" font-weight=\"800\" fill=\"#fff\">Agent<\/text><text x=\"875\" y=\"305\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"16\" font-weight=\"800\" fill=\"#fff\">loop<\/text><\/g>\n<circle r=\"7\" fill=\"#7c5cff\"><animateMotion dur=\"2.4s\" repeatCount=\"indefinite\"><mpath href=\"#ddp1\"\/><\/animateMotion><\/circle>\n<circle r=\"7\" fill=\"#61dafb\"><animateMotion dur=\"2.4s\" begin=\".6s\" repeatCount=\"indefinite\"><mpath href=\"#ddp2\"\/><\/animateMotion><\/circle>\n<circle r=\"7\" fill=\"#ffffff\"><animateMotion dur=\"2.4s\" begin=\"1.2s\" repeatCount=\"indefinite\"><mpath href=\"#ddp3\"\/><\/animateMotion><\/circle>\n<circle r=\"7\" fill=\"#3178c6\"><animateMotion dur=\"2.4s\" begin=\"1.8s\" repeatCount=\"indefinite\"><mpath href=\"#ddp4\"\/><\/animateMotion><\/circle>\n<g font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"15\" fill=\"#c9d1ff\">\n<rect x=\"60\" y=\"350\" width=\"150\" height=\"36\" rx=\"18\" fill=\"#0b1020\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"135\" y=\"374\" text-anchor=\"middle\">Pure Python<\/text>\n<rect x=\"222\" y=\"350\" width=\"150\" height=\"36\" rx=\"18\" fill=\"#0b1020\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"297\" y=\"374\" text-anchor=\"middle\">4 real tools<\/text>\n<rect x=\"384\" y=\"350\" width=\"170\" height=\"36\" rx=\"18\" fill=\"#0b1020\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"469\" y=\"374\" text-anchor=\"middle\">Terminal chat<\/text>\n<\/g>\n<text x=\"60\" y=\"505\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"16\" fill=\"#7f89b5\">devdojo.co.in \u00b7 Beginner friendly \u00b7 Runs offline, no API key needed<\/text>\n<\/svg>\n<\/div>\n\n<div class=\"dd-series\">Series: Agentic AI <span>Part 4 of 30<\/span><\/div>\n<p class=\"dd-prereq\"><strong>What you should know first:<\/strong> read <a href=\"https:\/\/devdojo.co.in\/index.php\/2026\/11\/03\/agentic-ai-series-part-3-tool-calling\/\">Agentic AI Part 3: Tool Calling for Agents<\/a> (the tool-calling round trip) and <a href=\"https:\/\/devdojo.co.in\/index.php\/2026\/10\/27\/agentic-ai-series-part-2-anatomy-of-an-ai-agent\/\">Part 2: Anatomy of an AI Agent<\/a> (model, tools, instructions and memory). Basic Python is enough.<\/p>\n\n<p>Today you will <strong>build an AI agent in Python<\/strong> from scratch, without LangChain, CrewAI or any other framework. In Part 2 we learned that every agent has four parts: a <strong>model<\/strong> (the brain), <strong>tools<\/strong> (the hands), <strong>instructions<\/strong> (the rules) and <strong>memory<\/strong> (what it remembers). In Part 3 we learned how a model asks your code to run a tool. Now we put all four parts together into one small, complete agent that you can chat with in your terminal.<\/p>\n<p>The finished agent, called <em>DevDojo Helper<\/em>, can do maths, tell the time in different cities and keep a to-do list of notes. The whole agent loop is about 40 lines of plain Python. Every main example runs <strong>offline<\/strong> with a small fake model, so you can follow along without an API key. At the end, you swap in a real LLM by changing one line.<\/p>\n\n<div class=\"dd-summary\">\n<strong class=\"lbl\">Quick Summary<\/strong>\n<ul>\n<li>An AI agent is a <strong>loop<\/strong>: the model thinks, your code runs a tool, the result goes back to the model, and this repeats until the model gives a final answer.<\/li>\n<li>Four files are enough: <code>tools.py<\/code> (hands), <code>fake_model.py<\/code> (brain), <code>agent.py<\/code> (the loop + instructions + memory) and <code>chat.py<\/code> (the chat window).<\/li>\n<li>A small <code>@tool<\/code> decorator turns normal Python functions into tools by building the JSON Schema from type hints.<\/li>\n<li>Two safety rules keep agents from breaking: turn every tool error into text, and stop after a <strong>maximum number of steps<\/strong>.<\/li>\n<li>Because the model sits behind one <code>respond()<\/code> method, you can swap the fake brain for a real LLM (OpenAI, Claude, a local model) in one line.<\/li>\n<\/ul>\n<\/div>\n\n<nav class=\"dd-toc\" aria-label=\"Table of contents\">\n<strong>In this post<\/strong>\n<ol>\n<li><a href=\"#what\">What we are building<\/a><\/li>\n<li><a href=\"#setup\">Project setup<\/a><\/li>\n<li><a href=\"#tools\">Step 1: Give the agent tools<\/a><\/li>\n<li><a href=\"#brain\">Step 2: Add a brain (fake model)<\/a><\/li>\n<li><a href=\"#loop\">Step 3: Write the agent loop<\/a><\/li>\n<li><a href=\"#chat\">Step 4: Chat with your agent<\/a><\/li>\n<li><a href=\"#safety\">Step 5: Make it safe<\/a><\/li>\n<li><a href=\"#real\">Step 6: Connect a real LLM<\/a><\/li>\n<li><a href=\"#memory\">How the memory works<\/a><\/li>\n<li><a href=\"#fixes\">Common errors and fixes<\/a><\/li>\n<li><a href=\"#best\">Best practices<\/a><\/li>\n<li><a href=\"#practice\">Practice task<\/a><\/li>\n<li><a href=\"#faq\">FAQ<\/a><\/li>\n<\/ol>\n<\/nav>\n\n<h2 id=\"what\">What we are building: an AI agent in Python with no framework<\/h2>\n<p>Frameworks are useful, but they hide the most important idea. When you build the loop yourself once, every framework you meet later (the <a href=\"https:\/\/devdojo.co.in\/index.php\/2026\/10\/08\/openai-agents-sdk-python\/\">OpenAI Agents SDK<\/a>, LangGraph, the Claude Agent SDK) suddenly makes sense, because they are all polished versions of the same loop. Here is how the four parts of an agent map to our four files:<\/p>\n<div class=\"dd-cards\">\n<div class=\"dd-card\"><b>Tools \u2192 tools.py<\/b>Normal Python functions: <code>calculator<\/code>, <code>get_time<\/code>, <code>save_note<\/code> and <code>list_notes<\/code>.<\/div>\n<div class=\"dd-card\"><b>Model \u2192 fake_model.py<\/b>The brain that decides what to do next. We start with a fake one, then swap in a real LLM.<\/div>\n<div class=\"dd-card\"><b>Instructions + Memory \u2192 agent.py<\/b>The system prompt, the conversation history and the loop that ties everything together.<\/div>\n<div class=\"dd-card\"><b>Interface \u2192 chat.py<\/b>A tiny terminal chat so you can talk to your agent.<\/div>\n<\/div>\n\n<figure>\n<svg viewBox=\"0 0 1000 380\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"Project diagram: chat.py sends user text to agent.py, which uses fake_model.py or openai_model.py as the brain and tools.py as the hands\">\n<rect width=\"1000\" height=\"380\" rx=\"16\" fill=\"#0f1430\"\/>\n<g font-family=\"Segoe UI,Arial,sans-serif\">\n<rect x=\"40\" y=\"150\" width=\"170\" height=\"80\" rx=\"14\" fill=\"#1b2250\" stroke=\"#61dafb\" stroke-width=\"2\"\/>\n<text x=\"125\" y=\"185\" text-anchor=\"middle\" font-size=\"19\" font-weight=\"700\" fill=\"#fff\">chat.py<\/text>\n<text x=\"125\" y=\"210\" text-anchor=\"middle\" font-size=\"14\" fill=\"#aab4e8\">you type here<\/text>\n<rect x=\"360\" y=\"120\" width=\"260\" height=\"140\" rx=\"16\" fill=\"#151b3b\" stroke=\"#7c5cff\" stroke-width=\"3\"\/>\n<text x=\"490\" y=\"158\" text-anchor=\"middle\" font-size=\"21\" font-weight=\"800\" fill=\"#fff\">agent.py<\/text>\n<text x=\"490\" y=\"186\" text-anchor=\"middle\" font-size=\"14\" fill=\"#c9d1ff\">INSTRUCTIONS (rules)<\/text>\n<text x=\"490\" y=\"208\" text-anchor=\"middle\" font-size=\"14\" fill=\"#c9d1ff\">self.history (memory)<\/text>\n<text x=\"490\" y=\"230\" text-anchor=\"middle\" font-size=\"14\" fill=\"#c9d1ff\">ask() loop + max_steps<\/text>\n<rect x=\"760\" y=\"40\" width=\"200\" height=\"90\" rx=\"14\" fill=\"#1b2250\" stroke=\"#3178c6\" stroke-width=\"2\"\/>\n<text x=\"860\" y=\"76\" text-anchor=\"middle\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">fake_model.py<\/text>\n<text x=\"860\" y=\"100\" text-anchor=\"middle\" font-size=\"13\" fill=\"#aab4e8\">or openai_model.py<\/text>\n<text x=\"860\" y=\"118\" text-anchor=\"middle\" font-size=\"13\" fill=\"#aab4e8\">the brain<\/text>\n<rect x=\"760\" y=\"250\" width=\"200\" height=\"90\" rx=\"14\" fill=\"#1b2250\" stroke=\"#3178c6\" stroke-width=\"2\"\/>\n<text x=\"860\" y=\"285\" text-anchor=\"middle\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">tools.py<\/text>\n<text x=\"860\" y=\"308\" text-anchor=\"middle\" font-size=\"13\" fill=\"#aab4e8\">calculator \u00b7 get_time<\/text>\n<text x=\"860\" y=\"326\" text-anchor=\"middle\" font-size=\"13\" fill=\"#aab4e8\">save_note \u00b7 list_notes<\/text>\n<\/g>\n<g stroke=\"#7c5cff\" stroke-width=\"2.5\" fill=\"none\" marker-end=\"url(#ar1)\">\n<path d=\"M212 190 H352\"\/><path d=\"M622 160 C 690 140, 700 95, 752 88\"\/><path d=\"M622 220 C 690 240, 700 290, 752 295\"\/>\n<\/g>\n<defs><marker id=\"ar1\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"8\" markerHeight=\"8\" orient=\"auto\"><path d=\"M0 0L10 5L0 10z\" fill=\"#7c5cff\"\/><\/marker><\/defs>\n<g font-family=\"Consolas,monospace\" font-size=\"13\" fill=\"#61dafb\">\n<text x=\"282\" y=\"180\" text-anchor=\"middle\">ask(text)<\/text><text x=\"672\" y=\"158\">respond()<\/text><text x=\"672\" y=\"236\">run_tool()<\/text>\n<\/g>\n<\/svg>\n<figcaption>Figure 1: The four files of our agent. Only <code>agent.py<\/code> knows about both the brain and the hands.<\/figcaption>\n<\/figure>\n\n<h2 id=\"setup\">Project setup<\/h2>\n<p>You only need Python 3.10 or newer (we use the <code>:=<\/code> operator and <code>zoneinfo<\/code>, which are built in). Create a folder and a virtual environment. No packages are needed for the offline version.<\/p>\n<div class=\"dd-vsc dd-vsc-termonly\" role=\"group\" aria-label=\"Terminal: Terminal \u2014 agentic-ai-part4\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">Terminal \u2014 agentic-ai-part4<\/span><\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># create the project folder and a virtual environment<\/span><\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> mkdir agentic-ai-part4 &amp;&amp; cd agentic-ai-part4<\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> python -m venv .venv<\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> source .venv\/bin\/activate      # Windows: .venv\\Scripts\\activate<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\"># check your Python version (3.10+)<\/span><\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> python --version<\/span><\/code><\/pre>\n<\/div>\n<div class=\"dd-tip\"><strong>Tip:<\/strong> On Windows, <code>zoneinfo<\/code> needs time zone data. If <code>get_time<\/code> raises <code>ZoneInfoNotFoundError<\/code>, run <code>pip install tzdata<\/code>.<\/div>\n\n<h2 id=\"tools\">Step 1: Give the agent tools<\/h2>\n<p>Tools are just Python functions. The model never runs them; it only asks for them by name. For the model to know what a tool does, every tool needs three things: a <strong>name<\/strong>, a <strong>description<\/strong> and a <strong>JSON Schema<\/strong> for its arguments (you saw this in Part 3). Writing that schema by hand for every function is boring and easy to get wrong, so we write a small <code>@tool<\/code> decorator that builds it automatically from the function&#8217;s type hints and docstring.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: tools.py, show_schema.py\">\n<input type=\"radio\" name=\"v1\" id=\"v1f1\" class=\"f1\" checked>\n<input type=\"radio\" name=\"v1\" id=\"v1f2\" class=\"f2\">\n<input type=\"checkbox\" id=\"v1r2\" class=\"r2\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">2 files \u2014 agentic-ai-part4 \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v1f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>tools.py<\/label>\n<label for=\"v1f2\" class=\"t2\"><b class=\"ic py\">PY<\/b>show_schema.py<\/label>\n<label for=\"v1r2\" class=\"run run2\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">agentic-ai-part4 \u203a tools.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># tools.py - the agent's \"hands\": plain Python functions + auto-built JSON Schemas.<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">inspect<\/span>, <span class=\"n\">json<\/span>, <span class=\"n\">math<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">datetime<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">datetime<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">zoneinfo<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">ZoneInfo<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">TOOLS<\/span> = {}  <span class=\"c\"># name -&gt; {\"fn\": function, \"schema\": JSON tool definition}<\/span><\/span>\n<span class=\"l\"><span class=\"n\">PY_TO_JSON<\/span> = {<span class=\"nb\">str<\/span>: <span class=\"s\">\"string\"<\/span>, <span class=\"nb\">int<\/span>: <span class=\"s\">\"integer\"<\/span>, <span class=\"nb\">float<\/span>: <span class=\"s\">\"number\"<\/span>, <span class=\"nb\">bool<\/span>: <span class=\"s\">\"boolean\"<\/span>}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">tool<\/span>(<span class=\"n\">fn<\/span>):<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"Decorator: register a function as a tool and build its schema from type hints.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">sig<\/span> = <span class=\"n\">inspect<\/span>.<span class=\"n\">signature<\/span>(<span class=\"n\">fn<\/span>)<\/span>\n<span class=\"l\">    <span class=\"n\">props<\/span> = {<span class=\"n\">name<\/span>: {<span class=\"s\">\"type\"<\/span>: <span class=\"n\">PY_TO_JSON<\/span>[<span class=\"n\">p<\/span>.<span class=\"n\">annotation<\/span>]} <span class=\"k\">for<\/span> <span class=\"n\">name<\/span>, <span class=\"n\">p<\/span> <span class=\"k\">in<\/span> <span class=\"n\">sig<\/span>.<span class=\"n\">parameters<\/span>.<span class=\"n\">items<\/span>()}<\/span>\n<span class=\"l\">    <span class=\"n\">required<\/span> = [<span class=\"n\">n<\/span> <span class=\"k\">for<\/span> <span class=\"n\">n<\/span>, <span class=\"n\">p<\/span> <span class=\"k\">in<\/span> <span class=\"n\">sig<\/span>.<span class=\"n\">parameters<\/span>.<span class=\"n\">items<\/span>() <span class=\"k\">if<\/span> <span class=\"n\">p<\/span>.<span class=\"n\">default<\/span> <span class=\"k\">is<\/span> <span class=\"n\">inspect<\/span>.<span class=\"n\">Parameter<\/span>.<span class=\"n\">empty<\/span>]<\/span>\n<span class=\"l\">    <span class=\"n\">TOOLS<\/span>[<span class=\"n\">fn<\/span>.<span class=\"n\">__name__<\/span>] = {<span class=\"s\">\"fn\"<\/span>: <span class=\"n\">fn<\/span>, <span class=\"s\">\"schema\"<\/span>: {<\/span>\n<span class=\"l\">        <span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"function\"<\/span>, <span class=\"s\">\"name\"<\/span>: <span class=\"n\">fn<\/span>.<span class=\"n\">__name__<\/span>,<\/span>\n<span class=\"l\">        <span class=\"s\">\"description\"<\/span>: <span class=\"n\">inspect<\/span>.<span class=\"n\">getdoc<\/span>(<span class=\"n\">fn<\/span>),<\/span>\n<span class=\"l\">        <span class=\"s\">\"parameters\"<\/span>: {<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"object\"<\/span>, <span class=\"s\">\"properties\"<\/span>: <span class=\"n\">props<\/span>,<\/span>\n<span class=\"l\">                       <span class=\"s\">\"required\"<\/span>: <span class=\"n\">required<\/span>, <span class=\"s\">\"additionalProperties\"<\/span>: <span class=\"kc\">False<\/span>},<\/span>\n<span class=\"l\">    }}<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">fn<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"nd\">@tool<\/span><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">calculator<\/span>(<span class=\"n\">expression<\/span>: <span class=\"nb\">str<\/span>) -&gt; <span class=\"nb\">str<\/span>:<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"Evaluate a maths expression like '18 * 4.5 + 2'. Use it for ANY arithmetic.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">allowed<\/span> = {<span class=\"n\">k<\/span>: <span class=\"nb\">getattr<\/span>(<span class=\"n\">math<\/span>, <span class=\"n\">k<\/span>) <span class=\"k\">for<\/span> <span class=\"n\">k<\/span> <span class=\"k\">in<\/span> (<span class=\"s\">\"sqrt\"<\/span>, <span class=\"s\">\"pi\"<\/span>, <span class=\"s\">\"ceil\"<\/span>, <span class=\"s\">\"floor\"<\/span>)}<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"nb\">str<\/span>(<span class=\"nb\">eval<\/span>(<span class=\"n\">expression<\/span>, {<span class=\"s\">\"__builtins__\"<\/span>: {}}, <span class=\"n\">allowed<\/span>))<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"nd\">@tool<\/span><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">get_time<\/span>(<span class=\"n\">city<\/span>: <span class=\"nb\">str<\/span>) -&gt; <span class=\"nb\">str<\/span>:<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"Get the current local time in a city. Supported: Mumbai, London, New York.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">zones<\/span> = {<span class=\"s\">\"mumbai\"<\/span>: <span class=\"s\">\"Asia\/Kolkata\"<\/span>, <span class=\"s\">\"london\"<\/span>: <span class=\"s\">\"Europe\/London\"<\/span>, <span class=\"s\">\"new york\"<\/span>: <span class=\"s\">\"America\/New_York\"<\/span>}<\/span>\n<span class=\"l\">    <span class=\"n\">zone<\/span> = <span class=\"n\">zones<\/span>.<span class=\"n\">get<\/span>(<span class=\"n\">city<\/span>.<span class=\"n\">lower<\/span>())<\/span>\n<span class=\"l\">    <span class=\"k\">if<\/span> <span class=\"n\">zone<\/span> <span class=\"k\">is<\/span> <span class=\"kc\">None<\/span>:<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> <span class=\"s\">f\"Error: unknown city '{<\/span><span class=\"n\">city<\/span><span class=\"s\">}'. Try Mumbai, London or New York.\"<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">datetime<\/span>.<span class=\"n\">now<\/span>(<span class=\"n\">ZoneInfo<\/span>(<span class=\"n\">zone<\/span>)).<span class=\"n\">strftime<\/span>(<span class=\"s\">\"%H:%M on %A\"<\/span>)<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">NOTES<\/span> = []<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"nd\">@tool<\/span><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">save_note<\/span>(<span class=\"n\">text<\/span>: <span class=\"nb\">str<\/span>) -&gt; <span class=\"nb\">str<\/span>:<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"Save a short note for the user (todo items, reminders, facts to remember).\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">NOTES<\/span>.<span class=\"n\">append<\/span>(<span class=\"n\">text<\/span>)<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"s\">f\"Saved note #{<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">NOTES<\/span>)<span class=\"s\">}.\"<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"nd\">@tool<\/span><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">list_notes<\/span>() -&gt; <span class=\"nb\">str<\/span>:<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"List all notes the user has saved so far.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">json<\/span>.<span class=\"n\">dumps<\/span>(<span class=\"n\">NOTES<\/span>) <span class=\"k\">if<\/span> <span class=\"n\">NOTES<\/span> <span class=\"k\">else<\/span> <span class=\"s\">\"No notes yet.\"<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">run_tool<\/span>(<span class=\"n\">name<\/span>: <span class=\"nb\">str<\/span>, <span class=\"n\">arguments<\/span>: <span class=\"nb\">str<\/span>) -&gt; <span class=\"nb\">str<\/span>:<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"Run a tool safely. Errors become text so the model can recover.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">if<\/span> <span class=\"n\">name<\/span> <span class=\"k\">not<\/span> <span class=\"k\">in<\/span> <span class=\"n\">TOOLS<\/span>:<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> <span class=\"s\">f\"Error: no tool named '{<\/span><span class=\"n\">name<\/span><span class=\"s\">}'.\"<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">try<\/span>:<\/span>\n<span class=\"l\">        <span class=\"n\">args<\/span> = <span class=\"n\">json<\/span>.<span class=\"n\">loads<\/span>(<span class=\"n\">arguments<\/span> <span class=\"k\">or<\/span> <span class=\"s\">\"{}\"<\/span>)<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> <span class=\"nb\">str<\/span>(<span class=\"n\">TOOLS<\/span>[<span class=\"n\">name<\/span>][<span class=\"s\">\"fn\"<\/span>](**<span class=\"n\">args<\/span>))<\/span>\n<span class=\"l\">    <span class=\"k\">except<\/span> <span class=\"n\">Exception<\/span> <span class=\"k\">as<\/span> <span class=\"n\">exc<\/span>:  <span class=\"c\"># bad JSON, wrong args, maths error...<\/span><\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> <span class=\"s\">f\"Error: {<\/span><span class=\"nb\">type<\/span>(<span class=\"n\">exc<\/span>).<span class=\"n\">__name__<\/span><span class=\"s\">}: {<\/span><span class=\"n\">exc<\/span><span class=\"s\">}\"<\/span><\/span><\/code><\/pre>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span class=\"sp\"><\/span><span>Ln 58, Col 1<\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<div class=\"dd-vsc-pane p2\">\n<div class=\"dd-vsc-crumbs\">agentic-ai-part4 \u203a show_schema.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># show_schema.py - see the JSON Schema the @tool decorator built for you.<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">json<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">tools<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">TOOLS<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"n\">json<\/span>.<span class=\"n\">dumps<\/span>(<span class=\"n\">TOOLS<\/span>[<span class=\"s\">\"calculator\"<\/span>][<span class=\"s\">\"schema\"<\/span>], <span class=\"n\">indent<\/span>=<span class=\"m\">2<\/span>))<\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"s\">\"Registered tools:\"<\/span>, <span class=\"s\">\", \"<\/span>.<span class=\"n\">join<\/span>(<span class=\"n\">TOOLS<\/span>))<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code>$ python show_schema.py\n{\n  &quot;type&quot;: &quot;function&quot;,\n  &quot;name&quot;: &quot;calculator&quot;,\n  &quot;description&quot;: &quot;Evaluate a maths expression like &#x27;18 * 4.5 + 2&#x27;. Use it for ANY arithmetic.&quot;,\n  &quot;parameters&quot;: {\n    &quot;type&quot;: &quot;object&quot;,\n    &quot;properties&quot;: {\n      &quot;expression&quot;: {\n        &quot;type&quot;: &quot;string&quot;\n      }\n    },\n    &quot;required&quot;: [\n      &quot;expression&quot;\n    ],\n    &quot;additionalProperties&quot;: false\n  }\n}\nRegistered tools: calculator, get_time, save_note, list_notes<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span class=\"sp\"><\/span><span>Ln 6, Col 1<\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Click the <strong>show_schema.py<\/strong> tab, then <strong>\u25b6 Run<\/strong> to see the JSON Schema the decorator built for <code>calculator<\/code>.<\/p>\n<p>Look at three important ideas in this file:<\/p>\n<ul>\n<li><strong>The docstring is the tool description.<\/strong> The model reads it to decide <em>when<\/em> to use the tool, so write it like a short instruction: &#8220;Use it for ANY arithmetic.&#8221;<\/li>\n<li><strong><code>run_tool()<\/code> never crashes.<\/strong> Bad JSON, wrong argument names or a maths error all become an <code>\"Error: ...\"<\/code> string. The model can read that string and try again.<\/li>\n<li><strong>The calculator uses a locked-down <code>eval<\/code>.<\/strong> Builtins are removed, so the model cannot call <code>open()<\/code> or <code>__import__<\/code>. For real projects, use a proper maths parser; we keep it short here.<\/li>\n<\/ul>\n\n<h2 id=\"brain\">Step 2: Add a brain (a fake model you can run offline)<\/h2>\n<p>A real LLM costs money and needs an API key, which makes learning slow. So we start with a <strong>fake model<\/strong>: a few <code>if<\/code> rules that return exactly the same shapes as the OpenAI Responses API. It either returns a <code>function_call<\/code> (asking for a tool) or a <code>message<\/code> (the final answer). Because the shapes match, the rest of our agent will work unchanged with a real model later.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: fake_model.py\">\n<input type=\"radio\" name=\"v2\" id=\"v2f1\" class=\"f1\" checked>\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">fake_model.py \u2014 agentic-ai-part4 \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v2f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>fake_model.py<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">agentic-ai-part4 \u203a fake_model.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># fake_model.py - a tiny rule-based \"LLM\" so you can run the agent offline.<\/span><\/span>\n<span class=\"l\"><span class=\"c\"># It returns the SAME shapes as the OpenAI Responses API: function_call or message.<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">json<\/span>, <span class=\"n\">re<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">class<\/span> <span class=\"nc\">FakeModel<\/span>:<\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">respond<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">instructions<\/span>, <span class=\"n\">history<\/span>, <span class=\"n\">tools<\/span>):<\/span>\n<span class=\"l\">        <span class=\"n\">last<\/span> = <span class=\"n\">history<\/span>[-<span class=\"m\">1<\/span>]<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"n\">last<\/span>[<span class=\"s\">\"type\"<\/span>] == <span class=\"s\">\"function_call_output\"<\/span>:           <span class=\"c\"># a tool just finished<\/span><\/span>\n<span class=\"l\">            <span class=\"n\">out<\/span> = <span class=\"n\">last<\/span>[<span class=\"s\">\"output\"<\/span>]<\/span>\n<span class=\"l\">            <span class=\"k\">if<\/span> <span class=\"n\">out<\/span>.<span class=\"n\">startswith<\/span>(<span class=\"s\">\"Error\"<\/span>):<\/span>\n<span class=\"l\">                <span class=\"k\">return<\/span> [{<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"message\"<\/span>, <span class=\"s\">\"text\"<\/span>: <span class=\"s\">\"Sorry, that failed. \"<\/span> + <span class=\"n\">out<\/span>[<span class=\"m\">7<\/span>:]}]<\/span>\n<span class=\"l\">            <span class=\"k\">return<\/span> [{<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"message\"<\/span>, <span class=\"s\">\"text\"<\/span>: <span class=\"s\">f\"Done! {<\/span><span class=\"n\">out<\/span><span class=\"s\">}\"<\/span>}]<\/span>\n<span class=\"l\">        <span class=\"n\">text<\/span> = <span class=\"n\">last<\/span>[<span class=\"s\">\"content\"<\/span>].<span class=\"n\">lower<\/span>()<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"n\">m<\/span> := <span class=\"n\">re<\/span>.<span class=\"n\">search<\/span>(<span class=\"s\">r\"([\\d.]+\\s*[-+*\/]\\s*[\\d.]+(?:\\s*[-+*\/]\\s*[\\d.]+)*)\"<\/span>, <span class=\"n\">text<\/span>):<\/span>\n<span class=\"l\">            <span class=\"k\">return<\/span> [<span class=\"n\">call<\/span>(<span class=\"s\">\"calculator\"<\/span>, <span class=\"n\">expression<\/span>=<span class=\"n\">m<\/span>.<span class=\"n\">group<\/span>(<span class=\"m\">1<\/span>))]<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"n\">m<\/span> := <span class=\"n\">re<\/span>.<span class=\"n\">search<\/span>(<span class=\"s\">r\"time in ([a-z ]+)\"<\/span>, <span class=\"n\">text<\/span>):<\/span>\n<span class=\"l\">            <span class=\"k\">return<\/span> [<span class=\"n\">call<\/span>(<span class=\"s\">\"get_time\"<\/span>, <span class=\"n\">city<\/span>=<span class=\"n\">m<\/span>.<span class=\"n\">group<\/span>(<span class=\"m\">1<\/span>).<span class=\"n\">strip<\/span>())]<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"n\">text<\/span>.<span class=\"n\">startswith<\/span>(<span class=\"s\">\"remember\"<\/span>):<\/span>\n<span class=\"l\">            <span class=\"k\">return<\/span> [<span class=\"n\">call<\/span>(<span class=\"s\">\"save_note\"<\/span>, <span class=\"n\">text<\/span>=<span class=\"n\">last<\/span>[<span class=\"s\">\"content\"<\/span>][<span class=\"m\">9<\/span>:].<span class=\"n\">strip<\/span>())]<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"s\">\"notes\"<\/span> <span class=\"k\">in<\/span> <span class=\"n\">text<\/span>:<\/span>\n<span class=\"l\">            <span class=\"k\">return<\/span> [<span class=\"n\">call<\/span>(<span class=\"s\">\"list_notes\"<\/span>)]<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> [{<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"message\"<\/span>, <span class=\"s\">\"text\"<\/span>: <span class=\"s\">\"I can do maths, tell the time and keep notes.\"<\/span>}]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">_count<\/span> = <span class=\"m\">0<\/span><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">call<\/span>(<span class=\"n\">name<\/span>, **<span class=\"n\">args<\/span>):<\/span>\n<span class=\"l\">    <span class=\"k\">global<\/span> <span class=\"n\">_count<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">_count<\/span> += <span class=\"m\">1<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> {<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"function_call\"<\/span>, <span class=\"s\">\"call_id\"<\/span>: <span class=\"s\">f\"call_{<\/span><span class=\"n\">_count<\/span><span class=\"s\">}\"<\/span>,<\/span>\n<span class=\"l\">            <span class=\"s\">\"name\"<\/span>: <span class=\"n\">name<\/span>, <span class=\"s\">\"arguments\"<\/span>: <span class=\"n\">json<\/span>.<span class=\"n\">dumps<\/span>(<span class=\"n\">args<\/span>)}<\/span><\/code><\/pre>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span class=\"sp\"><\/span><span>Ln 29, Col 1<\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<div class=\"dd-note\"><strong>Why a fake model is a good habit:<\/strong> professional teams test agents this way too. A scripted model makes tests fast, free and repeatable, because a real LLM can give a slightly different answer every time.<\/div>\n\n<h2 id=\"loop\">Step 3: Write the agent loop<\/h2>\n<p>This is the heart of the post. The <code>Agent<\/code> class holds the instructions, the memory (<code>self.history<\/code>) and the model. Its <code>ask()<\/code> method runs the <strong>agent loop<\/strong>: send everything to the model, run any tools it asks for, add the results to memory, and repeat until the model answers with plain text.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: agent.py\">\n<input type=\"radio\" name=\"v3\" id=\"v3f1\" class=\"f1\" checked>\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">agent.py \u2014 agentic-ai-part4 \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v3f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>agent.py<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">agentic-ai-part4 \u203a agent.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># agent.py - a complete AI agent in ~40 lines: model + tools + instructions + memory.<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">tools<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">TOOLS<\/span>, <span class=\"n\">run_tool<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">INSTRUCTIONS<\/span> = <span class=\"s\">\"\"\"You are DevDojo Helper, a friendly assistant for developers.<\/span><\/span>\n<span class=\"l\"><span class=\"s\">Use the calculator for every sum. Use tools instead of guessing.<\/span><\/span>\n<span class=\"l\"><span class=\"s\">Keep answers short. If a tool returns an error, explain it simply.\"\"\"<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">class<\/span> <span class=\"nc\">Agent<\/span>:<\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">__init__<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">model<\/span>, <span class=\"n\">max_steps<\/span>=<span class=\"m\">5<\/span>, <span class=\"n\">max_history<\/span>=<span class=\"m\">20<\/span>):<\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">model<\/span> = <span class=\"n\">model<\/span><\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span> = []              <span class=\"c\"># short-term memory (the conversation)<\/span><\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">max_steps<\/span> = <span class=\"n\">max_steps<\/span>     <span class=\"c\"># safety limit for one request<\/span><\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">max_history<\/span> = <span class=\"n\">max_history<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">ask<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">user_text<\/span>):<\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span>.<span class=\"n\">append<\/span>({<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"message\"<\/span>, <span class=\"s\">\"role\"<\/span>: <span class=\"s\">\"user\"<\/span>, <span class=\"s\">\"content\"<\/span>: <span class=\"n\">user_text<\/span>})<\/span>\n<span class=\"l\">        <span class=\"n\">schemas<\/span> = [<span class=\"n\">t<\/span>[<span class=\"s\">\"schema\"<\/span>] <span class=\"k\">for<\/span> <span class=\"n\">t<\/span> <span class=\"k\">in<\/span> <span class=\"n\">TOOLS<\/span>.<span class=\"n\">values<\/span>()]<\/span>\n<span class=\"l\">        <span class=\"k\">for<\/span> <span class=\"n\">step<\/span> <span class=\"k\">in<\/span> <span class=\"nb\">range<\/span>(<span class=\"m\">1<\/span>, <span class=\"kc\">self<\/span>.<span class=\"n\">max_steps<\/span> + <span class=\"m\">1<\/span>):<\/span>\n<span class=\"l\">            <span class=\"n\">items<\/span> = <span class=\"kc\">self<\/span>.<span class=\"n\">model<\/span>.<span class=\"n\">respond<\/span>(<span class=\"n\">INSTRUCTIONS<\/span>, <span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span>, <span class=\"n\">schemas<\/span>)<\/span>\n<span class=\"l\">            <span class=\"n\">calls<\/span> = [<span class=\"n\">i<\/span> <span class=\"k\">for<\/span> <span class=\"n\">i<\/span> <span class=\"k\">in<\/span> <span class=\"n\">items<\/span> <span class=\"k\">if<\/span> <span class=\"n\">i<\/span>[<span class=\"s\">\"type\"<\/span>] == <span class=\"s\">\"function_call\"<\/span>]<\/span>\n<span class=\"l\">            <span class=\"k\">if<\/span> <span class=\"k\">not<\/span> <span class=\"n\">calls<\/span>:                                   <span class=\"c\"># no tool needed: final answer<\/span><\/span>\n<span class=\"l\">                <span class=\"n\">answer<\/span> = <span class=\"n\">items<\/span>[<span class=\"m\">0<\/span>][<span class=\"s\">\"text\"<\/span>]<\/span>\n<span class=\"l\">                <span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span>.<span class=\"n\">append<\/span>({<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"message\"<\/span>, <span class=\"s\">\"role\"<\/span>: <span class=\"s\">\"assistant\"<\/span>, <span class=\"s\">\"content\"<\/span>: <span class=\"n\">answer<\/span>})<\/span>\n<span class=\"l\">                <span class=\"kc\">self<\/span>.<span class=\"n\">trim_memory<\/span>()<\/span>\n<span class=\"l\">                <span class=\"k\">return<\/span> <span class=\"n\">answer<\/span><\/span>\n<span class=\"l\">            <span class=\"k\">for<\/span> <span class=\"n\">c<\/span> <span class=\"k\">in<\/span> <span class=\"n\">calls<\/span>:                                 <span class=\"c\"># act, then observe<\/span><\/span>\n<span class=\"l\">                <span class=\"n\">result<\/span> = <span class=\"n\">run_tool<\/span>(<span class=\"n\">c<\/span>[<span class=\"s\">\"name\"<\/span>], <span class=\"n\">c<\/span>[<span class=\"s\">\"arguments\"<\/span>])<\/span>\n<span class=\"l\">                <span class=\"nb\">print<\/span>(<span class=\"s\">f\"  [step {<\/span><span class=\"n\">step<\/span><span class=\"s\">}] {<\/span><span class=\"n\">c<\/span>[<span class=\"s\">'name'<\/span>]<span class=\"s\">}({<\/span><span class=\"n\">c<\/span>[<span class=\"s\">'arguments'<\/span>]<span class=\"s\">}) -&gt; {<\/span><span class=\"n\">result<\/span><span class=\"s\">}\"<\/span>)<\/span>\n<span class=\"l\">                <span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span>.<span class=\"n\">append<\/span>(<span class=\"n\">c<\/span>)<\/span>\n<span class=\"l\">                <span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span>.<span class=\"n\">append<\/span>({<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"function_call_output\"<\/span>,<\/span>\n<span class=\"l\">                                     <span class=\"s\">\"call_id\"<\/span>: <span class=\"n\">c<\/span>[<span class=\"s\">\"call_id\"<\/span>], <span class=\"s\">\"output\"<\/span>: <span class=\"n\">result<\/span>})<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> <span class=\"s\">\"Sorry, I hit my step limit. Try a simpler request.\"<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">trim_memory<\/span>(<span class=\"kc\">self<\/span>):<\/span>\n<span class=\"l\">        <span class=\"s\">\"\"\"Keep only the newest messages so the context window never overflows.\"\"\"<\/span><\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"nb\">len<\/span>(<span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span>) &gt; <span class=\"kc\">self<\/span>.<span class=\"n\">max_history<\/span>:<\/span>\n<span class=\"l\">            <span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span> = <span class=\"kc\">self<\/span>.<span class=\"n\">history<\/span>[-<span class=\"kc\">self<\/span>.<span class=\"n\">max_history<\/span>:]<\/span><\/code><\/pre>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span class=\"sp\"><\/span><span>Ln 37, Col 1<\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n\n<figure>\n<svg viewBox=\"0 0 1000 420\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"Flowchart of the agent loop: user message added to memory, model responds, if it asks for a tool the tool runs and the result is added to memory and the loop repeats, otherwise the final answer is returned; the loop stops after max_steps\">\n<rect width=\"1000\" height=\"420\" rx=\"16\" fill=\"#f8f9fc\" stroke=\"#e3e6ef\"\/>\n<defs><marker id=\"ar2\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"8\" markerHeight=\"8\" orient=\"auto\"><path d=\"M0 0L10 5L0 10z\" fill=\"#3a2fa0\"\/><\/marker><\/defs>\n<g font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"16\" text-anchor=\"middle\">\n<rect x=\"30\" y=\"60\" width=\"170\" height=\"64\" rx=\"12\" fill=\"#fff\" stroke=\"#3178c6\" stroke-width=\"2\"\/><text x=\"115\" y=\"88\" font-weight=\"700\" fill=\"#1f2433\">User message<\/text><text x=\"115\" y=\"110\" font-size=\"13\" fill=\"#5b6275\">added to history<\/text>\n<rect x=\"270\" y=\"60\" width=\"190\" height=\"64\" rx=\"12\" fill=\"#fff\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"365\" y=\"88\" font-weight=\"700\" fill=\"#1f2433\">model.respond()<\/text><text x=\"365\" y=\"110\" font-size=\"13\" fill=\"#5b6275\">instructions + history + tools<\/text>\n<polygon points=\"620,40 730,92 620,144 510,92\" fill=\"#eef1fb\" stroke=\"#3a2fa0\" stroke-width=\"2\"\/><text x=\"620\" y=\"88\" font-weight=\"700\" fill=\"#1f2433\">Tool call?<\/text><text x=\"620\" y=\"108\" font-size=\"13\" fill=\"#5b6275\">function_call<\/text>\n<rect x=\"790\" y=\"60\" width=\"180\" height=\"64\" rx=\"12\" fill=\"#ecfbf3\" stroke=\"#1f9d61\" stroke-width=\"2\"\/><text x=\"880\" y=\"88\" font-weight=\"700\" fill=\"#1f2433\">Final answer<\/text><text x=\"880\" y=\"110\" font-size=\"13\" fill=\"#5b6275\">save + trim memory<\/text>\n<rect x=\"520\" y=\"230\" width=\"200\" height=\"64\" rx=\"12\" fill=\"#fff\" stroke=\"#3178c6\" stroke-width=\"2\"\/><text x=\"620\" y=\"258\" font-weight=\"700\" fill=\"#1f2433\">run_tool()<\/text><text x=\"620\" y=\"280\" font-size=\"13\" fill=\"#5b6275\">errors become text<\/text>\n<rect x=\"250\" y=\"230\" width=\"210\" height=\"64\" rx=\"12\" fill=\"#fff\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"355\" y=\"258\" font-weight=\"700\" fill=\"#1f2433\">Add call + output<\/text><text x=\"355\" y=\"280\" font-size=\"13\" fill=\"#5b6275\">to history (same call_id)<\/text>\n<rect x=\"250\" y=\"340\" width=\"420\" height=\"50\" rx=\"12\" fill=\"#fff6e8\" stroke=\"#e08a00\" stroke-width=\"2\"\/><text x=\"460\" y=\"371\" font-weight=\"700\" fill=\"#1f2433\">step &gt; max_steps? Stop safely with a message<\/text>\n<\/g>\n<g stroke=\"#3a2fa0\" stroke-width=\"2.2\" fill=\"none\" marker-end=\"url(#ar2)\">\n<path d=\"M200 92H262\"\/><path d=\"M460 92H502\"\/><path d=\"M730 92H782\"\/><path d=\"M620 144V222\"\/><path d=\"M520 262H468\"\/><path d=\"M355 230V132\"\/>\n<\/g>\n<g font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"14\" font-weight=\"700\" fill=\"#3a2fa0\"><text x=\"742\" y=\"82\">no<\/text><text x=\"632\" y=\"190\">yes<\/text><text x=\"300\" y=\"185\">repeat<\/text><\/g>\n<\/svg>\n<figcaption>Figure 2: One call to <code>agent.ask()<\/code>. The loop repeats until the model answers in plain text or the step limit is reached.<\/figcaption>\n<\/figure>\n\n<p>Click through the four stages of one request to see what happens inside <code>ask()<\/code>:<\/p>\n<div class=\"dd-tabs\" role=\"group\" aria-label=\"Agent loop step explorer\">\n<input type=\"radio\" name=\"ddsteps\" id=\"ti1\" checked>\n<input type=\"radio\" name=\"ddsteps\" id=\"ti2\">\n<input type=\"radio\" name=\"ddsteps\" id=\"ti3\">\n<input type=\"radio\" name=\"ddsteps\" id=\"ti4\">\n<div class=\"labels\"><label for=\"ti1\">1. Remember<\/label><label for=\"ti2\">2. Think<\/label><label for=\"ti3\">3. Act and observe<\/label><label for=\"ti4\">4. Answer<\/label><\/div>\n<div class=\"panel p1\"><p>The user&#8217;s message is added to <code>self.history<\/code>. This list is the agent&#8217;s short-term memory. It holds every user message, every tool call, every tool result and every answer, in order.<\/p><\/div>\n<div class=\"panel p2\"><p>The agent sends the <strong>instructions<\/strong>, the full <strong>history<\/strong> and the list of <strong>tool schemas<\/strong> to <code>model.respond()<\/code>. The model returns a list of items. If any item is a <code>function_call<\/code>, the model wants to use a tool.<\/p><\/div>\n<div class=\"panel p3\"><p>For each tool call, <code>run_tool()<\/code> runs the matching Python function. The agent appends the tool call <em>and<\/em> a <code>function_call_output<\/code> with the same <code>call_id<\/code> to memory, then goes back to step 2. The counter <code>step<\/code> goes up by one each time.<\/p><\/div>\n<div class=\"panel p4\"><p>When the model returns a normal message with no tool calls, that text is the final answer. It is saved to memory (so the next question has context), old messages are trimmed, and the answer is returned to the user.<\/p><\/div>\n<\/div>\n\n<h2 id=\"chat\">Step 4: Chat with your agent in the terminal<\/h2>\n<p>Now we need a way to talk to the agent. <code>chat.py<\/code> reads lines from the terminal, sends each one to <code>agent.ask()<\/code> and prints the answer. The <code>[step N]<\/code> lines are printed by the agent loop, so you can see every tool call as it happens. Click <strong>\u25b6 Run<\/strong> to see a real run.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: chat.py\">\n<input type=\"radio\" name=\"v4\" id=\"v4f1\" class=\"f1\" checked>\n<input type=\"checkbox\" id=\"v4r1\" class=\"r1\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">chat.py \u2014 agentic-ai-part4 \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v4f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>chat.py<\/label>\n<label for=\"v4r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">agentic-ai-part4 \u203a chat.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># chat.py - talk to your agent in the terminal.<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">sys<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">agent<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Agent<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">fake_model<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">FakeModel<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">agent<\/span> = <span class=\"n\">Agent<\/span>(<span class=\"n\">FakeModel<\/span>())<\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"s\">\"DevDojo Helper is ready. Type 'quit' to exit.\"<\/span>)<\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"k\">in<\/span> <span class=\"n\">sys<\/span>.<span class=\"n\">stdin<\/span>:<\/span>\n<span class=\"l\">    <span class=\"n\">text<\/span> = <span class=\"n\">line<\/span>.<span class=\"n\">strip<\/span>()<\/span>\n<span class=\"l\">    <span class=\"k\">if<\/span> <span class=\"n\">text<\/span> <span class=\"k\">in<\/span> (<span class=\"s\">\"quit\"<\/span>, <span class=\"s\">\"exit\"<\/span>):<\/span>\n<span class=\"l\">        <span class=\"k\">break<\/span><\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">f\"You: {<\/span><span class=\"n\">text<\/span><span class=\"s\">}\"<\/span>)<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">f\"Agent: {<\/span><span class=\"n\">agent<\/span>.<span class=\"n\">ask<\/span>(<span class=\"n\">text<\/span>)<span class=\"s\">}\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code>$ python chat.py &lt; demo.txt\nDevDojo Helper is ready. Type &#x27;quit&#x27; to exit.\nYou: what is 18 * 4.5 + 2\n  [step 1] calculator({&quot;expression&quot;: &quot;18 * 4.5 + 2&quot;}) -&gt; 83.0\nAgent: Done! 83.0\nYou: remember buy milk after standup\n  [step 1] save_note({&quot;text&quot;: &quot;buy milk after standup&quot;}) -&gt; Saved note #1.\nAgent: Done! Saved note #1.\nYou: remember review PR 42\n  [step 1] save_note({&quot;text&quot;: &quot;review PR 42&quot;}) -&gt; Saved note #2.\nAgent: Done! Saved note #2.\nYou: show my notes\n  [step 1] list_notes({}) -&gt; [&quot;buy milk after standup&quot;, &quot;review PR 42&quot;]\nAgent: Done! [&quot;buy milk after standup&quot;, &quot;review PR 42&quot;]\nYou: what is the time in paris\n  [step 1] get_time({&quot;city&quot;: &quot;paris&quot;}) -&gt; Error: unknown city &#x27;paris&#x27;. Try Mumbai, London or New York.\nAgent: Sorry, that failed. unknown city &#x27;paris&#x27;. Try Mumbai, London or New York.<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span class=\"sp\"><\/span><span>Ln 13, Col 1<\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Click <strong>\u25b6 Run<\/strong> to see a real run. For a repeatable demo we fed five messages from a file, <code>demo.txt<\/code>; you can also just run <code>python chat.py<\/code> and type.<\/p>\n<p>Notice two things in the output. First, the agent kept <strong>state between messages<\/strong>: the notes saved in turns 2 and 3 came back in turn 4. Second, when the user asked about Paris, the tool returned an error, and the agent explained it politely instead of crashing. That is exactly the behaviour we designed in Step 1.<\/p>\n\n<h2 id=\"safety\">Step 5: Make it safe with error handling and step limits<\/h2>\n<p>Real models make mistakes. They sometimes use the wrong argument name, ask for a tool that does not exist, or get stuck calling the same tool again and again. A good agent must survive all of these. Let&#8217;s prove ours does with a small test script, including a broken model that loops forever.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: test_safety.py\">\n<input type=\"radio\" name=\"v5\" id=\"v5f1\" class=\"f1\" checked>\n<input type=\"checkbox\" id=\"v5r1\" class=\"r1\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">test_safety.py \u2014 agentic-ai-part4 \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v5f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>test_safety.py<\/label>\n<label for=\"v5r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">agentic-ai-part4 \u203a test_safety.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># test_safety.py - prove the agent survives bad tool calls and endless loops.<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">agent<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Agent<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">tools<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">run_tool<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"n\">run_tool<\/span>(<span class=\"s\">\"calculator\"<\/span>, <span class=\"s\">'{\"expression\": \"10 \/ 0\"}'<\/span>))   <span class=\"c\"># maths error<\/span><\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"n\">run_tool<\/span>(<span class=\"s\">\"calculator\"<\/span>, <span class=\"s\">'{\"expr\": \"2+2\"}'<\/span>))            <span class=\"c\"># wrong argument name<\/span><\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"n\">run_tool<\/span>(<span class=\"s\">\"send_email\"<\/span>, <span class=\"s\">'{}'<\/span>))                         <span class=\"c\"># tool does not exist<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">class<\/span> <span class=\"nc\">LoopyModel<\/span>:<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"A broken model that asks for a tool forever.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">respond<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">instructions<\/span>, <span class=\"n\">history<\/span>, <span class=\"n\">tools<\/span>):<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> [{<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"function_call\"<\/span>, <span class=\"s\">\"call_id\"<\/span>: <span class=\"s\">f\"c{<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">history<\/span>)<span class=\"s\">}\"<\/span>,<\/span>\n<span class=\"l\">                 <span class=\"s\">\"name\"<\/span>: <span class=\"s\">\"list_notes\"<\/span>, <span class=\"s\">\"arguments\"<\/span>: <span class=\"s\">\"{}\"<\/span>}]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"n\">Agent<\/span>(<span class=\"n\">LoopyModel<\/span>(), <span class=\"n\">max_steps<\/span>=<span class=\"m\">3<\/span>).<span class=\"n\">ask<\/span>(<span class=\"s\">\"hello\"<\/span>))<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code>$ python test_safety.py\nError: ZeroDivisionError: division by zero\nError: TypeError: calculator() got an unexpected keyword argument &#x27;expr&#x27;\nError: no tool named &#x27;send_email&#x27;.\n  [step 1] list_notes({}) -&gt; No notes yet.\n  [step 2] list_notes({}) -&gt; No notes yet.\n  [step 3] list_notes({}) -&gt; No notes yet.\nSorry, I hit my step limit. Try a simpler request.<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span class=\"sp\"><\/span><span>Ln 15, Col 1<\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Click <strong>\u25b6 Run<\/strong>: every error comes back as text, and the looping model is stopped after 3 steps.<\/p>\n<div class=\"dd-warn\"><strong>Never remove the step limit.<\/strong> Without <code>max_steps<\/code>, a confused model with a real API key can call tools in a loop and quietly spend a lot of money. Five to ten steps is a sensible default for a simple helper agent.<\/div>\n\n<h2 id=\"real\">Step 6: Connect a real LLM in one line<\/h2>\n<p>Our agent only talks to the model through one method: <code>respond(instructions, history, tools)<\/code>. So connecting a real LLM means writing one small adapter class. Here is one for the <a href=\"https:\/\/developers.openai.com\/api\/docs\/guides\/function-calling\" rel=\"noopener\" target=\"_blank\">OpenAI Responses API function calling guide<\/a> format. Install the SDK and set your key first:<\/p>\n<div class=\"dd-vsc dd-vsc-termonly\" role=\"group\" aria-label=\"Terminal: Terminal \u2014 agentic-ai-part4\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">Terminal \u2014 agentic-ai-part4<\/span><\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"gp\">$<\/span> pip install openai<\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> export OPENAI_API_KEY=&quot;sk-...&quot;      # Windows PowerShell: $env:OPENAI_API_KEY=&quot;sk-...&quot;<\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> python chat_real.py<\/span><\/code><\/pre>\n<\/div>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: openai_model.py, chat_real.py\">\n<input type=\"radio\" name=\"v6\" id=\"v6f1\" class=\"f1\" checked>\n<input type=\"radio\" name=\"v6\" id=\"v6f2\" class=\"f2\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">2 files \u2014 agentic-ai-part4 \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v6f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>openai_model.py<\/label>\n<label for=\"v6f2\" class=\"t2\"><b class=\"ic py\">PY<\/b>chat_real.py<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">agentic-ai-part4 \u203a openai_model.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># openai_model.py - swap the fake brain for a real LLM (OpenAI Responses API).<\/span><\/span>\n<span class=\"l\"><span class=\"c\"># pip install openai   and set OPENAI_API_KEY in your environment.<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">openai<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">OpenAI<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">MODEL<\/span> = <span class=\"s\">\"gpt-6-luna\"<\/span>  <span class=\"c\"># any tool-capable model from your provider's models page<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">class<\/span> <span class=\"nc\">OpenAIModel<\/span>:<\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">__init__<\/span>(<span class=\"kc\">self<\/span>):<\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">client<\/span> = <span class=\"n\">OpenAI<\/span>()<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">respond<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">instructions<\/span>, <span class=\"n\">history<\/span>, <span class=\"n\">tools<\/span>):<\/span>\n<span class=\"l\">        <span class=\"n\">resp<\/span> = <span class=\"kc\">self<\/span>.<span class=\"n\">client<\/span>.<span class=\"n\">responses<\/span>.<span class=\"n\">create<\/span>(<\/span>\n<span class=\"l\">            <span class=\"n\">model<\/span>=<span class=\"n\">MODEL<\/span>, <span class=\"n\">instructions<\/span>=<span class=\"n\">instructions<\/span>, <span class=\"nb\">input<\/span>=<span class=\"n\">to_input<\/span>(<span class=\"n\">history<\/span>), <span class=\"n\">tools<\/span>=<span class=\"n\">tools<\/span>)<\/span>\n<span class=\"l\">        <span class=\"n\">items<\/span> = []<\/span>\n<span class=\"l\">        <span class=\"k\">for<\/span> <span class=\"n\">item<\/span> <span class=\"k\">in<\/span> <span class=\"n\">resp<\/span>.<span class=\"n\">output<\/span>:<\/span>\n<span class=\"l\">            <span class=\"k\">if<\/span> <span class=\"n\">item<\/span>.<span class=\"n\">type<\/span> == <span class=\"s\">\"function_call\"<\/span>:<\/span>\n<span class=\"l\">                <span class=\"n\">items<\/span>.<span class=\"n\">append<\/span>({<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"function_call\"<\/span>, <span class=\"s\">\"call_id\"<\/span>: <span class=\"n\">item<\/span>.<span class=\"n\">call_id<\/span>,<\/span>\n<span class=\"l\">                              <span class=\"s\">\"name\"<\/span>: <span class=\"n\">item<\/span>.<span class=\"n\">name<\/span>, <span class=\"s\">\"arguments\"<\/span>: <span class=\"n\">item<\/span>.<span class=\"n\">arguments<\/span>})<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"k\">not<\/span> <span class=\"n\">items<\/span>:<\/span>\n<span class=\"l\">            <span class=\"n\">items<\/span>.<span class=\"n\">append<\/span>({<span class=\"s\">\"type\"<\/span>: <span class=\"s\">\"message\"<\/span>, <span class=\"s\">\"text\"<\/span>: <span class=\"n\">resp<\/span>.<span class=\"n\">output_text<\/span>})<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> <span class=\"n\">items<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">to_input<\/span>(<span class=\"n\">history<\/span>):<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"Convert our memory format into Responses API input items.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">out<\/span> = []<\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">h<\/span> <span class=\"k\">in<\/span> <span class=\"n\">history<\/span>:<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"n\">h<\/span>[<span class=\"s\">\"type\"<\/span>] == <span class=\"s\">\"message\"<\/span>:<\/span>\n<span class=\"l\">            <span class=\"n\">out<\/span>.<span class=\"n\">append<\/span>({<span class=\"s\">\"role\"<\/span>: <span class=\"n\">h<\/span>[<span class=\"s\">\"role\"<\/span>], <span class=\"s\">\"content\"<\/span>: <span class=\"n\">h<\/span>[<span class=\"s\">\"content\"<\/span>]})<\/span>\n<span class=\"l\">        <span class=\"k\">else<\/span>:<\/span>\n<span class=\"l\">            <span class=\"n\">out<\/span>.<span class=\"n\">append<\/span>({<span class=\"n\">k<\/span>: <span class=\"n\">v<\/span> <span class=\"k\">for<\/span> <span class=\"n\">k<\/span>, <span class=\"n\">v<\/span> <span class=\"k\">in<\/span> <span class=\"n\">h<\/span>.<span class=\"n\">items<\/span>()})<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">out<\/span><\/span><\/code><\/pre>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span class=\"sp\"><\/span><span>Ln 31, Col 1<\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<div class=\"dd-vsc-pane p2\">\n<div class=\"dd-vsc-crumbs\">agentic-ai-part4 \u203a chat_real.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># chat_real.py - same chat loop, real LLM brain. Only ONE line changed.<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">sys<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">agent<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Agent<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">openai_model<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">OpenAIModel<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">agent<\/span> = <span class=\"n\">Agent<\/span>(<span class=\"n\">OpenAIModel<\/span>())<\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"s\">\"DevDojo Helper (real LLM) is ready. Type 'quit' to exit.\"<\/span>)<\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"k\">in<\/span> <span class=\"n\">sys<\/span>.<span class=\"n\">stdin<\/span>:<\/span>\n<span class=\"l\">    <span class=\"n\">text<\/span> = <span class=\"n\">line<\/span>.<span class=\"n\">strip<\/span>()<\/span>\n<span class=\"l\">    <span class=\"k\">if<\/span> <span class=\"n\">text<\/span> <span class=\"k\">in<\/span> (<span class=\"s\">\"quit\"<\/span>, <span class=\"s\">\"exit\"<\/span>):<\/span>\n<span class=\"l\">        <span class=\"k\">break<\/span><\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">f\"Agent: {<\/span><span class=\"n\">agent<\/span>.<span class=\"n\">ask<\/span>(<span class=\"n\">text<\/span>)<span class=\"s\">}\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span class=\"sp\"><\/span><span>Ln 12, Col 1<\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Switch between the tabs: <strong>openai_model.py<\/strong> is the adapter, <strong>chat_real.py<\/strong> is <code>chat.py<\/code> with one import changed.<\/p>\n<p>The adapter converts the API&#8217;s output into the same small dictionaries our fake model returns, so <code>agent.py<\/code> does not change at all. With a real model, the answers become natural sentences, the model can call several tools in one turn, and it can chain steps on its own (for example, look up the time in two cities and then work out the difference with the calculator). The same pattern works for Claude, Gemini or a local model running in Ollama: write a new adapter with the same <code>respond()<\/code> method.<\/p>\n<div class=\"dd-tip\"><strong>Tip:<\/strong> Keep the fake model around after you switch. Use the fake one in your automated tests and the real one in the app. This is called <em>dependency injection<\/em>: the agent receives its model from outside instead of creating it.<\/div>\n\n<h2 id=\"memory\">How the agent&#8217;s memory works<\/h2>\n<p>Our agent has <strong>short-term memory<\/strong> only: the <code>self.history<\/code> list. Every model call receives the whole list, which is why the agent &#8220;remembers&#8221; your earlier notes. But a model&#8217;s context window is limited (see <a href=\"https:\/\/devdojo.co.in\/index.php\/2026\/10\/18\/genai-series-part-2-tokens-context-window-parameters\/\">Generative AI Part 2<\/a> on tokens), so <code>trim_memory()<\/code> keeps only the newest 20 items.<\/p>\n<div class=\"dd-tablewrap\"><table>\n<thead><tr><th>Memory type<\/th><th>Where it lives in our agent<\/th><th>Lasts for<\/th><th>Covered in<\/th><\/tr><\/thead>\n<tbody>\n<tr><td>Short-term (conversation)<\/td><td><code>self.history<\/code><\/td><td>This chat session<\/td><td>This post<\/td><\/tr>\n<tr><td>Tool state<\/td><td><code>NOTES<\/code> list in <code>tools.py<\/code><\/td><td>Until the program stops<\/td><td>This post<\/td><\/tr>\n<tr><td>Long-term (facts, preferences)<\/td><td>Not yet: a file or vector database<\/td><td>Across sessions<\/td><td>Part 7<\/td><\/tr>\n<tr><td>Scratchpad (working notes)<\/td><td>Not yet<\/td><td>One task<\/td><td>Parts 5 and 7<\/td><\/tr>\n<\/tbody><\/table><\/div>\n<div class=\"dd-note\"><strong>Careful when trimming:<\/strong> a <code>function_call_output<\/code> without its matching <code>function_call<\/code> confuses real APIs and can cause an error. In production, trim whole &#8220;turns&#8221; (a user message plus everything after it) instead of cutting at a fixed number of items. This is a great improvement to try in the practice task.<\/div>\n\n<h2 id=\"fixes\">Common errors and fixes<\/h2>\n<div class=\"dd-tablewrap\"><table>\n<thead><tr><th>Error or symptom<\/th><th>Why it happens<\/th><th>Fix<\/th><\/tr><\/thead>\n<tbody>\n<tr><td><code>KeyError<\/code> inside the <code>@tool<\/code> decorator<\/td><td>A tool parameter has no type hint, or uses a type like <code>list<\/code> that is not in <code>PY_TO_JSON<\/code><\/td><td>Add a type hint (<code>str<\/code>, <code>int<\/code>, <code>float<\/code>, <code>bool<\/code>) or extend the mapping<\/td><\/tr>\n<tr><td>Agent says &#8220;I hit my step limit&#8221;<\/td><td>The model keeps calling tools, often because a tool result is unclear<\/td><td>Return clear results such as <code>\"Saved note #2.\"<\/code>, improve tool descriptions, or raise <code>max_steps<\/code> a little<\/td><\/tr>\n<tr><td>The model never uses a tool<\/td><td>The description does not say when to use it<\/td><td>Write action-focused docstrings: &#8220;Use it for ANY arithmetic&#8221;<\/td><\/tr>\n<tr><td><code>No tool call found for function call output<\/code> (real API)<\/td><td>Memory trimming removed the <code>function_call<\/code> but kept its output<\/td><td>Trim whole turns, always keeping call and output together<\/td><\/tr>\n<tr><td><code>json.decoder.JSONDecodeError<\/code><\/td><td>The model sent arguments that are not valid JSON<\/td><td>Already handled: <code>run_tool()<\/code> returns it as an error string so the model can retry<\/td><\/tr>\n<tr><td><code>ZoneInfoNotFoundError<\/code><\/td><td>No time zone data on Windows<\/td><td><code>pip install tzdata<\/code><\/td><\/tr>\n<\/tbody><\/table><\/div>\n\n<h2 id=\"best\">Best practices for your first agent<\/h2>\n<ul>\n<li><strong>Start small.<\/strong> Three or four focused tools beat twenty vague ones. Each new tool is another choice the model can get wrong.<\/li>\n<li><strong>Log every step.<\/strong> Our <code>[step N]<\/code> print is the simplest form of tracing. You cannot fix an agent you cannot see.<\/li>\n<li><strong>Return errors as text<\/strong> and keep them helpful: say what went wrong and what to try instead.<\/li>\n<li><strong>Always set a step limit<\/strong> and, for real APIs, a timeout and a budget.<\/li>\n<li><strong>Keep the model behind an interface<\/strong> (<code>respond()<\/code>) so you can test with a fake model and switch providers easily.<\/li>\n<li><strong>Never give a tool more power than it needs.<\/strong> A note-taking agent does not need shell access. We cover this deeply in Part 22 (Agent Security).<\/li>\n<\/ul>\n\n<h2 id=\"practice\">Practice task<\/h2>\n<p>Extend DevDojo Helper with these three small upgrades. Each one takes 5\u201315 minutes:<\/p>\n<ol>\n<li>Add a new tool <code>delete_note(number: int)<\/code> that removes a note by its number, and a rule in <code>FakeModel<\/code> for messages starting with &#8220;delete note&#8221;.<\/li>\n<li>Save <code>NOTES<\/code> to a <code>notes.json<\/code> file so notes survive a restart. This is your first taste of long-term memory.<\/li>\n<li>Change <code>trim_memory()<\/code> so it never separates a <code>function_call<\/code> from its <code>function_call_output<\/code>.<\/li>\n<\/ol>\n<p>Bonus: if you have an API key, switch to <code>chat_real.py<\/code> and ask &#8220;What time is it in London and New York, and how many hours apart are they?&#8221; Watch how many steps the real model takes.<\/p>\n\n<h2 id=\"faq\">FAQ<\/h2>\n<details><summary>Do I need LangChain or another framework to build an AI agent in Python?<\/summary><p>No. As you saw, a working agent is a loop, a list of messages and a few functions. Frameworks add useful extras (tracing, retries, multi-agent handoffs, durable state), and we compare them in Part 11. Learning the loop first makes those frameworks much easier to use.<\/p><\/details>\n<details><summary>What is the difference between this agent and the tool-calling loop in Part 3?<\/summary><p>Part 3 showed one request and one round trip. Today&#8217;s agent adds instructions, memory that lasts across many messages, a reusable tool registry, safety limits and a chat interface. It is the full structure from Part 2, working.<\/p><\/details>\n<details><summary>Is using eval() in the calculator safe?<\/summary><p>Our version removes all builtins, which blocks the obvious attacks, but <code>eval<\/code> is still risky with untrusted input. For production, use a safe expression parser library or Python&#8217;s <code>ast<\/code> module to allow only numbers and operators.<\/p><\/details>\n<details><summary>Which LLM should I use with this agent?<\/summary><p>Any model that supports tool (function) calling: OpenAI, Anthropic Claude, Google Gemini, or open models served through Ollama. Smaller, cheaper models are fine for simple tools like these. Write one adapter class per provider with the same <code>respond()<\/code> method.<\/p><\/details>\n<details><summary>Why does my agent forget everything when I restart it?<\/summary><p>Because <code>self.history<\/code> and <code>NOTES<\/code> live in memory (RAM). When the program stops, they are gone. Saving them to a file or database gives the agent long-term memory, which is the topic of Part 7.<\/p><\/details>\n\n<details class=\"dd-roadmap\">\n<summary>Full Agentic AI roadmap (30 parts)<\/summary>\n<h4>Beginner<\/h4>\n<ol start=\"1\">\n<li><a href=\"https:\/\/devdojo.co.in\/index.php\/2026\/10\/20\/agentic-ai-series-part-1-what-is-agentic-ai\/\">What Is Agentic AI and How Do AI Agents Work?<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/index.php\/2026\/10\/27\/agentic-ai-series-part-2-anatomy-of-an-ai-agent\/\">Anatomy of an AI Agent: Models, Tools, Instructions and Memory<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/index.php\/2026\/11\/03\/agentic-ai-series-part-3-tool-calling\/\">Tool Calling for Agents: Letting an LLM Use Your Functions<\/a><\/li>\n<li>Build Your First AI Agent from Scratch in Python (No Framework) <span class=\"here\">You are here<\/span><\/li>\n<li>The ReAct Pattern: Reason, Act, Observe in Practice <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Writing Good Agent Instructions and Tool Descriptions <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Agent Memory: Short-Term, Long-Term and Scratchpads <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Planning Agents: Breaking Big Goals into Steps <span class=\"soon\">Coming soon<\/span><\/li>\n<\/ol>\n<h4>Intermediate<\/h4>\n<ol start=\"9\">\n<li>Workflow Patterns: Chaining, Routing and Parallel Steps <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Model Context Protocol (MCP): Connecting Agents to Tools and Data <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Agent Frameworks Compared: OpenAI Agents SDK, LangGraph, Claude Agent SDK and More <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Building Stateful Agents with LangGraph <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Agentic RAG: Agents That Search, Read and Cite <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Browser and Computer-Use Agents <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Coding Agents: How AI Writes, Runs and Fixes Code <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Human-in-the-Loop: Approvals, Interrupts and Checkpoints <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Multi-Agent Systems: Handoffs, Supervisors and Teams <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Agent-to-Agent Communication with the A2A Protocol <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Guardrails and Structured Outputs for Agents <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Tracing and Debugging Agents <span class=\"soon\">Coming soon<\/span><\/li>\n<\/ol>\n<h4>Advanced<\/h4>\n<ol start=\"21\">\n<li>Evaluating Agents: Task Success, Trajectories and Test Suites <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Agent Security: Prompt Injection, Permissions and Sandboxing <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Controlling Agent Cost and Latency <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Long-Running Agents: Queues, Retries and Durable Execution <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Deep Research Agents: Search, Synthesise and Report <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Reflection and Self-Correcting Agents <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Voice and Real-Time Agents <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Deploying Agents to Production: APIs, Serverless and Containers <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Monitoring and Improving Agents in Production <span class=\"soon\">Coming soon<\/span><\/li>\n<li>Final Project: Build a Multi-Agent Developer Assistant <span class=\"soon\">Coming soon<\/span><\/li>\n<\/ol>\n<\/details>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>You just built a real AI agent in Python from scratch. It has a model that decides, tools that act, instructions that guide it and memory that keeps the conversation together, all joined by one loop with a safety limit. You tested it offline with a fake model and saw how to plug in a real LLM without touching the agent code. Read more about the <a href=\"https:\/\/docs.python.org\/3\/library\/inspect.html\" rel=\"noopener\" target=\"_blank\">Python inspect module<\/a> if you want to make the <code>@tool<\/code> decorator even smarter (for example, reading default values and enums).<\/p>\n\n<div class=\"dd-next\"><strong>Next part \u2013 Agentic AI Part 5: The ReAct Pattern: Reason, Act, Observe in Practice.<\/strong> We will teach the agent to &#8220;think out loud&#8221; before each action, so it can solve multi-step problems and you can see its reasoning.<\/div>\n\n<div class=\"dd-cta\">\n<h3>New posts every day on DevDojo<\/h3>\n<p>Follow the full <strong>Agentic AI series<\/strong> \u2013 30 parts from &#8220;what is an agent&#8221; to a multi-agent developer assistant. Bookmark <a href=\"https:\/\/devdojo.co.in\/\">devdojo.co.in<\/a> and tell us in the comments which tool you added to your agent first.<\/p>\n<\/div>\n<\/div>\n\n","protected":false},"excerpt":{"rendered":"<p>Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.<\/p>\n","protected":false},"author":1,"featured_media":321,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[38],"tags":[180,136,119,42,52,118,120],"class_list":["post-322","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ai","tag-agent-loop","tag-agent-memory","tag-agentic-ai","tag-ai-agents","tag-python","tag-series-agentic-ai","tag-tool-calling"],"aioseo_notices":[],"aioseo_head":"\n\t\t<!-- All in One SEO 5.0.4 - aioseo.com -->\n\t<meta name=\"description\" content=\"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.\" \/>\n\t<meta name=\"robots\" content=\"max-image-preview:large\" \/>\n\t<meta name=\"author\" content=\"Lokendra\"\/>\n\t<link rel=\"canonical\" href=\"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/\" \/>\n\t\t<meta name=\"generator\" content=\"All in One SEO (AIOSEO) 5.0.4\" \/>\n\t\t<meta property=\"og:locale\" content=\"en_US\" \/>\n\t\t<meta property=\"og:site_name\" content=\"DevDojo - Empowering Developers\" \/>\n\t\t<meta property=\"og:type\" content=\"article\" \/>\n\t\t<meta property=\"og:title\" content=\"Agentic AI Part 4: Build Your First AI Agent in Python\" \/>\n\t\t<meta property=\"og:description\" content=\"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.\" \/>\n\t\t<meta property=\"og:url\" content=\"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/\" \/>\n\t\t<meta property=\"article:published_time\" content=\"2026-12-01T14:38:11+00:00\" \/>\n\t\t<meta property=\"article:modified_time\" content=\"2026-12-01T14:38:11+00:00\" \/>\n\t\t<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n\t\t<meta name=\"twitter:title\" content=\"Agentic AI Part 4: Build Your First AI Agent in Python\" \/>\n\t\t<meta name=\"twitter:description\" content=\"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.\" \/>\n\t\t<script type=\"application\/ld+json\" class=\"aioseo-schema\">\n\t\t\t{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"BlogPosting\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#blogposting\",\"name\":\"Build an AI Agent in Python from Scratch (No Framework)\",\"headline\":\"Agentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)\",\"author\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"publisher\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\"},\"image\":{\"@type\":\"ImageObject\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/wp-content\\\/uploads\\\/2026\\\/12\\\/agentic-ai-series-part-4-build-ai-agent-python.jpg\",\"width\":1200,\"height\":630,\"caption\":\"Agentic AI Part 4 banner: build your first AI agent in Python with a think, act, observe and memory loop\"},\"datePublished\":\"2026-12-01T14:38:11+00:00\",\"dateModified\":\"2026-12-01T14:38:11+00:00\",\"inLanguage\":\"en-US\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#webpage\"},\"isPartOf\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#webpage\"},\"articleSection\":\"AI, Agent Loop, Agent Memory, Agentic AI, AI Agents, Python, Series: Agentic AI, Tool Calling\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#breadcrumblist\",\"itemListElement\":[{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#listItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/devdojo.co.in\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"name\":\"AI\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"position\":2,\"name\":\"AI\",\"item\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#listItem\",\"name\":\"Agentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)\"},\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#listItem\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#listItem\",\"position\":3,\"name\":\"Agentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)\",\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"name\":\"AI\"}}]},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\",\"name\":\"DevDojo\",\"description\":\"Empowering Developers\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/\",\"name\":\"Lokendra\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#authorImage\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/99f102f0cc9080237ce54b91304fd1b3b6fa29925cbaeba93cd796872e58b45c?s=96&d=mm&r=g\",\"width\":96,\"height\":96,\"caption\":\"Lokendra\"}},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#webpage\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/\",\"name\":\"Build an AI Agent in Python from Scratch (No Framework)\",\"description\":\"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.\",\"inLanguage\":\"en-US\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#website\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#breadcrumblist\"},\"author\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"creator\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"image\":{\"@type\":\"ImageObject\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/wp-content\\\/uploads\\\/2026\\\/12\\\/agentic-ai-series-part-4-build-ai-agent-python.jpg\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#mainImage\",\"width\":1200,\"height\":630,\"caption\":\"Agentic AI Part 4 banner: build your first AI agent in Python with a think, act, observe and memory loop\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/agentic-ai-series-part-4-build-ai-agent-python\\\/#mainImage\"},\"datePublished\":\"2026-12-01T14:38:11+00:00\",\"dateModified\":\"2026-12-01T14:38:11+00:00\"},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#website\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/\",\"name\":\"DevDojo\",\"description\":\"Empowering Developers\",\"inLanguage\":\"en-US\",\"publisher\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\"}}]}\n\t\t<\/script>\n\t\t<!-- All in One SEO -->\n\n","aioseo_head_json":{"title":"Build an AI Agent in Python from Scratch (No Framework)","description":"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.","canonical_url":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/","robots":"max-image-preview:large","keywords":"","webmasterTools":{"miscellaneous":""},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"BlogPosting","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#blogposting","name":"Build an AI Agent in Python from Scratch (No Framework)","headline":"Agentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)","author":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"publisher":{"@id":"https:\/\/devdojo.co.in\/#organization"},"image":{"@type":"ImageObject","url":"https:\/\/devdojo.co.in\/wp-content\/uploads\/2026\/12\/agentic-ai-series-part-4-build-ai-agent-python.jpg","width":1200,"height":630,"caption":"Agentic AI Part 4 banner: build your first AI agent in Python with a think, act, observe and memory loop"},"datePublished":"2026-12-01T14:38:11+00:00","dateModified":"2026-12-01T14:38:11+00:00","inLanguage":"en-US","mainEntityOfPage":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#webpage"},"isPartOf":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#webpage"},"articleSection":"AI, Agent Loop, Agent Memory, Agentic AI, AI Agents, Python, Series: Agentic AI, Tool Calling"},{"@type":"BreadcrumbList","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#breadcrumblist","itemListElement":[{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/#listItem","position":1,"name":"Home","item":"https:\/\/devdojo.co.in\/","nextItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","name":"AI"}},{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","position":2,"name":"AI","item":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/","nextItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#listItem","name":"Agentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)"},"previousItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/#listItem","name":"Home"}},{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#listItem","position":3,"name":"Agentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)","previousItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","name":"AI"}}]},{"@type":"Organization","@id":"https:\/\/devdojo.co.in\/#organization","name":"DevDojo","description":"Empowering Developers","url":"https:\/\/devdojo.co.in\/"},{"@type":"Person","@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author","url":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/","name":"Lokendra","image":{"@type":"ImageObject","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#authorImage","url":"https:\/\/secure.gravatar.com\/avatar\/99f102f0cc9080237ce54b91304fd1b3b6fa29925cbaeba93cd796872e58b45c?s=96&d=mm&r=g","width":96,"height":96,"caption":"Lokendra"}},{"@type":"WebPage","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#webpage","url":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/","name":"Build an AI Agent in Python from Scratch (No Framework)","description":"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.","inLanguage":"en-US","isPartOf":{"@id":"https:\/\/devdojo.co.in\/#website"},"breadcrumb":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#breadcrumblist"},"author":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"creator":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"image":{"@type":"ImageObject","url":"https:\/\/devdojo.co.in\/wp-content\/uploads\/2026\/12\/agentic-ai-series-part-4-build-ai-agent-python.jpg","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#mainImage","width":1200,"height":630,"caption":"Agentic AI Part 4 banner: build your first AI agent in Python with a think, act, observe and memory loop"},"primaryImageOfPage":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/#mainImage"},"datePublished":"2026-12-01T14:38:11+00:00","dateModified":"2026-12-01T14:38:11+00:00"},{"@type":"WebSite","@id":"https:\/\/devdojo.co.in\/#website","url":"https:\/\/devdojo.co.in\/","name":"DevDojo","description":"Empowering Developers","inLanguage":"en-US","publisher":{"@id":"https:\/\/devdojo.co.in\/#organization"}}]},"og:locale":"en_US","og:site_name":"DevDojo - Empowering Developers","og:type":"article","og:title":"Agentic AI Part 4: Build Your First AI Agent in Python","og:description":"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.","og:url":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/","article:published_time":"2026-12-01T14:38:11+00:00","article:modified_time":"2026-12-01T14:38:11+00:00","twitter:card":"summary_large_image","twitter:title":"Agentic AI Part 4: Build Your First AI Agent in Python","twitter:description":"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo."},"aioseo_meta_data":{"post_id":"322","title":"Build an AI Agent in Python from Scratch (No Framework)","description":"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.","keywords":null,"keyphrases":{"focus":{"keyphrase":"build an AI agent in Python","score":69},"additional":[]},"primary_term":null,"canonical_url":null,"og_title":"Agentic AI Part 4: Build Your First AI Agent in Python","og_description":"Build an AI agent in Python from scratch with no framework: tools, instructions, memory and a safe agent loop, with runnable code and a terminal chat demo.","og_object_type":"default","og_image_type":"default","og_image_url":null,"og_image_width":null,"og_image_height":null,"og_image_custom_url":null,"og_image_custom_fields":null,"og_video":"","og_custom_url":null,"og_article_section":null,"og_article_tags":null,"twitter_use_og":false,"twitter_card":"default","twitter_image_type":"default","twitter_image_url":null,"twitter_image_custom_url":null,"twitter_image_custom_fields":null,"twitter_title":null,"twitter_description":null,"schema":{"blockGraphs":[],"customGraphs":[],"default":{"data":{"Article":[],"Course":[],"Dataset":[],"FAQPage":[],"Movie":[],"Person":[],"Product":[],"ProductReview":[],"Car":[],"Recipe":[],"Service":[],"SoftwareApplication":[],"WebPage":[]},"graphName":"BlogPosting","isEnabled":true},"graphs":[]},"schema_type":"default","schema_type_options":null,"pillar_content":false,"robots_default":true,"robots_noindex":false,"robots_noarchive":false,"robots_nosnippet":false,"robots_nofollow":false,"robots_noimageindex":false,"robots_noodp":false,"robots_notranslate":false,"robots_max_snippet":"-1","robots_max_videopreview":"-1","robots_max_imagepreview":"large","priority":0,"frequency":"default","local_seo":null,"breadcrumb_settings":null,"limit_modified_date":false,"ai":{"faqs":[],"keyPoints":[],"schemas":[],"titles":[],"descriptions":[],"socialPosts":{"email":{"subject":"","preview":"","content":""},"linkedin":[],"twitter":[],"facebook":[],"instagram":[]}},"created":"2026-12-01 14:30:25","updated":"2026-12-01 14:38:11","focus_keyword":"build an AI agent in Python","additional_keywords":null,"truseo_locale":null,"seo_analyzer_scan_date":null},"aioseo_breadcrumb":"<div class=\"aioseo-breadcrumbs\"><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/devdojo.co.in\/\" title=\"Home\">Home<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">\u00bb<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/devdojo.co.in\/index.php\/category\/ai\/\" title=\"AI\">AI<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">\u00bb<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\tAgentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)\n\t\t<\/span><\/div>","aioseo_breadcrumb_json":[{"label":"Home","link":"https:\/\/devdojo.co.in\/"},{"label":"AI","link":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/"},{"label":"Agentic AI Part 4: Build Your First AI Agent from Scratch in Python (No Framework)","link":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/agentic-ai-series-part-4-build-ai-agent-python\/"}],"_links":{"self":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/322","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/comments?post=322"}],"version-history":[{"count":1,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/322\/revisions"}],"predecessor-version":[{"id":323,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/322\/revisions\/323"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/media\/321"}],"wp:attachment":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/media?parent=322"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/categories?post=322"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/tags?post=322"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}