What you should know first: read Agentic AI Part 3: Tool Calling for Agents (the tool-calling round trip) and Part 2: Anatomy of an AI Agent (model, tools, instructions and memory). Basic Python is enough.
Today you will build an AI agent in Python from scratch, without LangChain, CrewAI or any other framework. In Part 2 we learned that every agent has four parts: a model (the brain), tools (the hands), instructions (the rules) and memory (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.
The finished agent, called DevDojo Helper, 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 offline 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.
- An AI agent is a loop: 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.
- Four files are enough:
tools.py(hands),fake_model.py(brain),agent.py(the loop + instructions + memory) andchat.py(the chat window). - A small
@tooldecorator turns normal Python functions into tools by building the JSON Schema from type hints. - Two safety rules keep agents from breaking: turn every tool error into text, and stop after a maximum number of steps.
- Because the model sits behind one
respond()method, you can swap the fake brain for a real LLM (OpenAI, Claude, a local model) in one line.
What we are building: an AI agent in Python with no framework
Frameworks are useful, but they hide the most important idea. When you build the loop yourself once, every framework you meet later (the OpenAI Agents SDK, 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:
calculator, get_time, save_note and list_notes.agent.py knows about both the brain and the hands.Project setup
You only need Python 3.10 or newer (we use the := operator and zoneinfo, which are built in). Create a folder and a virtual environment. No packages are needed for the offline version.
# create the project folder and a virtual environment
$ mkdir agentic-ai-part4 && cd agentic-ai-part4
$ python -m venv .venv
$ source .venv/bin/activate # Windows: .venv\Scripts\activate
# check your Python version (3.10+)
$ python --version
zoneinfo needs time zone data. If get_time raises ZoneInfoNotFoundError, run pip install tzdata.Step 1: Give the agent tools
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 name, a description and a JSON Schema 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 @tool decorator that builds it automatically from the function’s type hints and docstring.
# tools.py - the agent's "hands": plain Python functions + auto-built JSON Schemas.
import inspect, json, math
from datetime import datetime
from zoneinfo import ZoneInfo
TOOLS = {} # name -> {"fn": function, "schema": JSON tool definition}
PY_TO_JSON = {str: "string", int: "integer", float: "number", bool: "boolean"}
def tool(fn):
"""Decorator: register a function as a tool and build its schema from type hints."""
sig = inspect.signature(fn)
props = {name: {"type": PY_TO_JSON[p.annotation]} for name, p in sig.parameters.items()}
required = [n for n, p in sig.parameters.items() if p.default is inspect.Parameter.empty]
TOOLS[fn.__name__] = {"fn": fn, "schema": {
"type": "function", "name": fn.__name__,
"description": inspect.getdoc(fn),
"parameters": {"type": "object", "properties": props,
"required": required, "additionalProperties": False},
}}
return fn
@tool
def calculator(expression: str) -> str:
"""Evaluate a maths expression like '18 * 4.5 + 2'. Use it for ANY arithmetic."""
allowed = {k: getattr(math, k) for k in ("sqrt", "pi", "ceil", "floor")}
return str(eval(expression, {"__builtins__": {}}, allowed))
@tool
def get_time(city: str) -> str:
"""Get the current local time in a city. Supported: Mumbai, London, New York."""
zones = {"mumbai": "Asia/Kolkata", "london": "Europe/London", "new york": "America/New_York"}
zone = zones.get(city.lower())
if zone is None:
return f"Error: unknown city '{city}'. Try Mumbai, London or New York."
return datetime.now(ZoneInfo(zone)).strftime("%H:%M on %A")
NOTES = []
@tool
def save_note(text: str) -> str:
"""Save a short note for the user (todo items, reminders, facts to remember)."""
NOTES.append(text)
return f"Saved note #{len(NOTES)}."
@tool
def list_notes() -> str:
"""List all notes the user has saved so far."""
return json.dumps(NOTES) if NOTES else "No notes yet."
def run_tool(name: str, arguments: str) -> str:
"""Run a tool safely. Errors become text so the model can recover."""
if name not in TOOLS:
return f"Error: no tool named '{name}'."
try:
args = json.loads(arguments or "{}")
return str(TOOLS[name]["fn"](**args))
except Exception as exc: # bad JSON, wrong args, maths error...
return f"Error: {type(exc).__name__}: {exc}"
# show_schema.py - see the JSON Schema the @tool decorator built for you.
import json
from tools import TOOLS
print(json.dumps(TOOLS["calculator"]["schema"], indent=2))
print("Registered tools:", ", ".join(TOOLS))
$ python show_schema.py
{
"type": "function",
"name": "calculator",
"description": "Evaluate a maths expression like '18 * 4.5 + 2'. Use it for ANY arithmetic.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string"
}
},
"required": [
"expression"
],
"additionalProperties": false
}
}
Registered tools: calculator, get_time, save_note, list_notesClick the show_schema.py tab, then ▶ Run to see the JSON Schema the decorator built for calculator.
Look at three important ideas in this file:
- The docstring is the tool description. The model reads it to decide when to use the tool, so write it like a short instruction: “Use it for ANY arithmetic.”
run_tool()never crashes. Bad JSON, wrong argument names or a maths error all become an"Error: ..."string. The model can read that string and try again.- The calculator uses a locked-down
eval. Builtins are removed, so the model cannot callopen()or__import__. For real projects, use a proper maths parser; we keep it short here.
Step 2: Add a brain (a fake model you can run offline)
A real LLM costs money and needs an API key, which makes learning slow. So we start with a fake model: a few if rules that return exactly the same shapes as the OpenAI Responses API. It either returns a function_call (asking for a tool) or a message (the final answer). Because the shapes match, the rest of our agent will work unchanged with a real model later.
# fake_model.py - a tiny rule-based "LLM" so you can run the agent offline.
# It returns the SAME shapes as the OpenAI Responses API: function_call or message.
import json, re
class FakeModel:
def respond(self, instructions, history, tools):
last = history[-1]
if last["type"] == "function_call_output": # a tool just finished
out = last["output"]
if out.startswith("Error"):
return [{"type": "message", "text": "Sorry, that failed. " + out[7:]}]
return [{"type": "message", "text": f"Done! {out}"}]
text = last["content"].lower()
if m := re.search(r"([\d.]+\s*[-+*/]\s*[\d.]+(?:\s*[-+*/]\s*[\d.]+)*)", text):
return [call("calculator", expression=m.group(1))]
if m := re.search(r"time in ([a-z ]+)", text):
return [call("get_time", city=m.group(1).strip())]
if text.startswith("remember"):
return [call("save_note", text=last["content"][9:].strip())]
if "notes" in text:
return [call("list_notes")]
return [{"type": "message", "text": "I can do maths, tell the time and keep notes."}]
_count = 0
def call(name, **args):
global _count
_count += 1
return {"type": "function_call", "call_id": f"call_{_count}",
"name": name, "arguments": json.dumps(args)}
Step 3: Write the agent loop
This is the heart of the post. The Agent class holds the instructions, the memory (self.history) and the model. Its ask() method runs the agent loop: 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.
# agent.py - a complete AI agent in ~40 lines: model + tools + instructions + memory.
from tools import TOOLS, run_tool
INSTRUCTIONS = """You are DevDojo Helper, a friendly assistant for developers.
Use the calculator for every sum. Use tools instead of guessing.
Keep answers short. If a tool returns an error, explain it simply."""
class Agent:
def __init__(self, model, max_steps=5, max_history=20):
self.model = model
self.history = [] # short-term memory (the conversation)
self.max_steps = max_steps # safety limit for one request
self.max_history = max_history
def ask(self, user_text):
self.history.append({"type": "message", "role": "user", "content": user_text})
schemas = [t["schema"] for t in TOOLS.values()]
for step in range(1, self.max_steps + 1):
items = self.model.respond(INSTRUCTIONS, self.history, schemas)
calls = [i for i in items if i["type"] == "function_call"]
if not calls: # no tool needed: final answer
answer = items[0]["text"]
self.history.append({"type": "message", "role": "assistant", "content": answer})
self.trim_memory()
return answer
for c in calls: # act, then observe
result = run_tool(c["name"], c["arguments"])
print(f" [step {step}] {c['name']}({c['arguments']}) -> {result}")
self.history.append(c)
self.history.append({"type": "function_call_output",
"call_id": c["call_id"], "output": result})
return "Sorry, I hit my step limit. Try a simpler request."
def trim_memory(self):
"""Keep only the newest messages so the context window never overflows."""
if len(self.history) > self.max_history:
self.history = self.history[-self.max_history:]
agent.ask(). The loop repeats until the model answers in plain text or the step limit is reached.Click through the four stages of one request to see what happens inside ask():
The user’s message is added to self.history. This list is the agent’s short-term memory. It holds every user message, every tool call, every tool result and every answer, in order.
The agent sends the instructions, the full history and the list of tool schemas to model.respond(). The model returns a list of items. If any item is a function_call, the model wants to use a tool.
For each tool call, run_tool() runs the matching Python function. The agent appends the tool call and a function_call_output with the same call_id to memory, then goes back to step 2. The counter step goes up by one each time.
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.
Step 4: Chat with your agent in the terminal
Now we need a way to talk to the agent. chat.py reads lines from the terminal, sends each one to agent.ask() and prints the answer. The [step N] lines are printed by the agent loop, so you can see every tool call as it happens. Click ▶ Run to see a real run.
# chat.py - talk to your agent in the terminal.
import sys
from agent import Agent
from fake_model import FakeModel
agent = Agent(FakeModel())
print("DevDojo Helper is ready. Type 'quit' to exit.")
for line in sys.stdin:
text = line.strip()
if text in ("quit", "exit"):
break
print(f"You: {text}")
print(f"Agent: {agent.ask(text)}")
$ python chat.py < demo.txt
DevDojo Helper is ready. Type 'quit' to exit.
You: what is 18 * 4.5 + 2
[step 1] calculator({"expression": "18 * 4.5 + 2"}) -> 83.0
Agent: Done! 83.0
You: remember buy milk after standup
[step 1] save_note({"text": "buy milk after standup"}) -> Saved note #1.
Agent: Done! Saved note #1.
You: remember review PR 42
[step 1] save_note({"text": "review PR 42"}) -> Saved note #2.
Agent: Done! Saved note #2.
You: show my notes
[step 1] list_notes({}) -> ["buy milk after standup", "review PR 42"]
Agent: Done! ["buy milk after standup", "review PR 42"]
You: what is the time in paris
[step 1] get_time({"city": "paris"}) -> Error: unknown city 'paris'. Try Mumbai, London or New York.
Agent: Sorry, that failed. unknown city 'paris'. Try Mumbai, London or New York.Click ▶ Run to see a real run. For a repeatable demo we fed five messages from a file, demo.txt; you can also just run python chat.py and type.
Notice two things in the output. First, the agent kept state between messages: 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.
Step 5: Make it safe with error handling and step limits
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’s prove ours does with a small test script, including a broken model that loops forever.
# test_safety.py - prove the agent survives bad tool calls and endless loops.
from agent import Agent
from tools import run_tool
print(run_tool("calculator", '{"expression": "10 / 0"}')) # maths error
print(run_tool("calculator", '{"expr": "2+2"}')) # wrong argument name
print(run_tool("send_email", '{}')) # tool does not exist
class LoopyModel:
"""A broken model that asks for a tool forever."""
def respond(self, instructions, history, tools):
return [{"type": "function_call", "call_id": f"c{len(history)}",
"name": "list_notes", "arguments": "{}"}]
print(Agent(LoopyModel(), max_steps=3).ask("hello"))
$ python test_safety.py
Error: ZeroDivisionError: division by zero
Error: TypeError: calculator() got an unexpected keyword argument 'expr'
Error: no tool named 'send_email'.
[step 1] list_notes({}) -> No notes yet.
[step 2] list_notes({}) -> No notes yet.
[step 3] list_notes({}) -> No notes yet.
Sorry, I hit my step limit. Try a simpler request.Click ▶ Run: every error comes back as text, and the looping model is stopped after 3 steps.
max_steps, 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.Step 6: Connect a real LLM in one line
Our agent only talks to the model through one method: respond(instructions, history, tools). So connecting a real LLM means writing one small adapter class. Here is one for the OpenAI Responses API function calling guide format. Install the SDK and set your key first:
$ pip install openai
$ export OPENAI_API_KEY="sk-..." # Windows PowerShell: $env:OPENAI_API_KEY="sk-..."
$ python chat_real.py
# openai_model.py - swap the fake brain for a real LLM (OpenAI Responses API).
# pip install openai and set OPENAI_API_KEY in your environment.
from openai import OpenAI
MODEL = "gpt-6-luna" # any tool-capable model from your provider's models page
class OpenAIModel:
def __init__(self):
self.client = OpenAI()
def respond(self, instructions, history, tools):
resp = self.client.responses.create(
model=MODEL, instructions=instructions, input=to_input(history), tools=tools)
items = []
for item in resp.output:
if item.type == "function_call":
items.append({"type": "function_call", "call_id": item.call_id,
"name": item.name, "arguments": item.arguments})
if not items:
items.append({"type": "message", "text": resp.output_text})
return items
def to_input(history):
"""Convert our memory format into Responses API input items."""
out = []
for h in history:
if h["type"] == "message":
out.append({"role": h["role"], "content": h["content"]})
else:
out.append({k: v for k, v in h.items()})
return out
# chat_real.py - same chat loop, real LLM brain. Only ONE line changed.
import sys
from agent import Agent
from openai_model import OpenAIModel
agent = Agent(OpenAIModel())
print("DevDojo Helper (real LLM) is ready. Type 'quit' to exit.")
for line in sys.stdin:
text = line.strip()
if text in ("quit", "exit"):
break
print(f"Agent: {agent.ask(text)}")
Switch between the tabs: openai_model.py is the adapter, chat_real.py is chat.py with one import changed.
The adapter converts the API’s output into the same small dictionaries our fake model returns, so agent.py 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 respond() method.
How the agent’s memory works
Our agent has short-term memory only: the self.history list. Every model call receives the whole list, which is why the agent “remembers” your earlier notes. But a model’s context window is limited (see Generative AI Part 2 on tokens), so trim_memory() keeps only the newest 20 items.
| Memory type | Where it lives in our agent | Lasts for | Covered in |
|---|---|---|---|
| Short-term (conversation) | self.history | This chat session | This post |
| Tool state | NOTES list in tools.py | Until the program stops | This post |
| Long-term (facts, preferences) | Not yet: a file or vector database | Across sessions | Part 7 |
| Scratchpad (working notes) | Not yet | One task | Parts 5 and 7 |
function_call_output without its matching function_call confuses real APIs and can cause an error. In production, trim whole “turns” (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.Common errors and fixes
| Error or symptom | Why it happens | Fix |
|---|---|---|
KeyError inside the @tool decorator | A tool parameter has no type hint, or uses a type like list that is not in PY_TO_JSON | Add a type hint (str, int, float, bool) or extend the mapping |
| Agent says “I hit my step limit” | The model keeps calling tools, often because a tool result is unclear | Return clear results such as "Saved note #2.", improve tool descriptions, or raise max_steps a little |
| The model never uses a tool | The description does not say when to use it | Write action-focused docstrings: “Use it for ANY arithmetic” |
No tool call found for function call output (real API) | Memory trimming removed the function_call but kept its output | Trim whole turns, always keeping call and output together |
json.decoder.JSONDecodeError | The model sent arguments that are not valid JSON | Already handled: run_tool() returns it as an error string so the model can retry |
ZoneInfoNotFoundError | No time zone data on Windows | pip install tzdata |
Best practices for your first agent
- Start small. Three or four focused tools beat twenty vague ones. Each new tool is another choice the model can get wrong.
- Log every step. Our
[step N]print is the simplest form of tracing. You cannot fix an agent you cannot see. - Return errors as text and keep them helpful: say what went wrong and what to try instead.
- Always set a step limit and, for real APIs, a timeout and a budget.
- Keep the model behind an interface (
respond()) so you can test with a fake model and switch providers easily. - Never give a tool more power than it needs. A note-taking agent does not need shell access. We cover this deeply in Part 22 (Agent Security).
Practice task
Extend DevDojo Helper with these three small upgrades. Each one takes 5–15 minutes:
- Add a new tool
delete_note(number: int)that removes a note by its number, and a rule inFakeModelfor messages starting with “delete note”. - Save
NOTESto anotes.jsonfile so notes survive a restart. This is your first taste of long-term memory. - Change
trim_memory()so it never separates afunction_callfrom itsfunction_call_output.
Bonus: if you have an API key, switch to chat_real.py and ask “What time is it in London and New York, and how many hours apart are they?” Watch how many steps the real model takes.
FAQ
Do I need LangChain or another framework to build an AI agent in Python?
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.
What is the difference between this agent and the tool-calling loop in Part 3?
Part 3 showed one request and one round trip. Today’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.
Is using eval() in the calculator safe?
Our version removes all builtins, which blocks the obvious attacks, but eval is still risky with untrusted input. For production, use a safe expression parser library or Python’s ast module to allow only numbers and operators.
Which LLM should I use with this agent?
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 respond() method.
Why does my agent forget everything when I restart it?
Because self.history and NOTES 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.
Full Agentic AI roadmap (30 parts)
Beginner
- What Is Agentic AI and How Do AI Agents Work?
- Anatomy of an AI Agent: Models, Tools, Instructions and Memory
- Tool Calling for Agents: Letting an LLM Use Your Functions
- Build Your First AI Agent from Scratch in Python (No Framework) You are here
- The ReAct Pattern: Reason, Act, Observe in Practice Coming soon
- Writing Good Agent Instructions and Tool Descriptions Coming soon
- Agent Memory: Short-Term, Long-Term and Scratchpads Coming soon
- Planning Agents: Breaking Big Goals into Steps Coming soon
Intermediate
- Workflow Patterns: Chaining, Routing and Parallel Steps Coming soon
- Model Context Protocol (MCP): Connecting Agents to Tools and Data Coming soon
- Agent Frameworks Compared: OpenAI Agents SDK, LangGraph, Claude Agent SDK and More Coming soon
- Building Stateful Agents with LangGraph Coming soon
- Agentic RAG: Agents That Search, Read and Cite Coming soon
- Browser and Computer-Use Agents Coming soon
- Coding Agents: How AI Writes, Runs and Fixes Code Coming soon
- Human-in-the-Loop: Approvals, Interrupts and Checkpoints Coming soon
- Multi-Agent Systems: Handoffs, Supervisors and Teams Coming soon
- Agent-to-Agent Communication with the A2A Protocol Coming soon
- Guardrails and Structured Outputs for Agents Coming soon
- Tracing and Debugging Agents Coming soon
Advanced
- Evaluating Agents: Task Success, Trajectories and Test Suites Coming soon
- Agent Security: Prompt Injection, Permissions and Sandboxing Coming soon
- Controlling Agent Cost and Latency Coming soon
- Long-Running Agents: Queues, Retries and Durable Execution Coming soon
- Deep Research Agents: Search, Synthesise and Report Coming soon
- Reflection and Self-Correcting Agents Coming soon
- Voice and Real-Time Agents Coming soon
- Deploying Agents to Production: APIs, Serverless and Containers Coming soon
- Monitoring and Improving Agents in Production Coming soon
- Final Project: Build a Multi-Agent Developer Assistant Coming soon
Conclusion
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 Python inspect module if you want to make the @tool decorator even smarter (for example, reading default values and enums).
New posts every day on DevDojo
Follow the full Agentic AI series – 30 parts from “what is an agent” to a multi-agent developer assistant. Bookmark devdojo.co.in and tell us in the comments which tool you added to your agent first.