How to learn AI agents, from scratch
A staged path for learning AI agents: concepts, a loop you write yourself, tools, memory, and safety, with one thing to build at every stage.
The path in six stages
To learn AI agents from scratch, work through six stages in order: the concepts, your first loop, tools, memory, loop design, and safety. Each stage has one thing you build with your own hands. Skipping ahead is the most common reason people stall, because a framework hides exactly the part you needed to see.
An AI agent is a loop around a language model that is allowed to call tools. That sentence is the entire subject. Everything after it is detail about what goes into the loop, what the tools may touch, and how you stop the loop when it goes wrong. If you can explain the loop to someone else, you have learned the thing. If you can only name frameworks, you have not.
The plan below assumes you learn by building. Read a stage, build the small thing, break it on purpose, then move on. A stage you have only read is a stage you have not done.
What you actually need before stage 1
The honest prerequisite list is short, and shorter than most course pages suggest.
- You can read and write Python or TypeScript at the level of a fifty line script.
- You are comfortable in a Linux shell: install a package, edit a file, read a log.
- You have an API key for a hosted model, or a machine that can run a local one.
That is the whole list. You do not need machine learning theory, and you do not need to have trained a model. Nothing in agent work involves gradients or training data. A graphics card only matters if you decide to run the model yourself, which is a separate skill you can pick up later from hosting Ollama on a VPS to self host an LLM.
What people underestimate is the shell half. Agents fail on permissions, paths, environment variables, and processes that die quietly. If a stack trace about PATH or a file mode makes you close the terminal, spend a weekend on Linux basics first. It will save you a month later.
Stage 1: what an agent is, and what it is not
Start with one API call and no loop. Send a prompt, print the reply, look at the token counts in the response. You now understand the unit of cost and the unit of latency.
Then learn tool use, which is the only genuinely new idea in the whole field. You describe a function to the model as a name, a description, and a JSON (JavaScript object notation) schema for its inputs. The model does not run anything. It replies with a structured request: call run_command with these arguments. Your code runs the function, sends the output back as a message, and asks the model again. The model is a planner that reads text and writes text. Your code is the thing with hands.
A chatbot ends after one reply. An agent repeats that exchange until the model stops asking for tools. That repetition is the whole difference, and it is why the failure modes differ too. A chatbot gives a wrong answer once. An agent acts on a wrong answer several times before anyone notices.
Stage 2: write the loop yourself, once
Do not start with a framework. Write about thirty lines of Python so the shape of the thing is yours.
sudo apt update && sudo apt install -y python3-venv
python3 -m venv ~/agent
source ~/agent/bin/activate
pip install anthropic
export ANTHROPIC_API_KEY=your-key-hereimport subprocess
import anthropic
client = anthropic.Anthropic()
tools = [{
"name": "run_command",
"description": "Run a read only shell command and return its output.",
"input_schema": {
"type": "object",
"properties": {"command": {"type": "string"}},
"required": ["command"],
},
}]
messages = [{"role": "user", "content": "How much disk space is free here?"}]
while True:
response = client.messages.create(
model="claude-opus-5",
max_tokens=4096,
tools=tools,
messages=messages,
)
if response.stop_reason != "tool_use":
break
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
done = subprocess.run(
block.input["command"], shell=True,
capture_output=True, text=True, timeout=10,
)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": done.stdout or done.stderr,
})
messages.append({"role": "user", "content": results})
print(next(b.text for b in response.content if b.type == "text"))Run it with python3 agent.py. A healthy run prints one paragraph naming your filesystems and their free space, because the model asked for df -h, your code ran it, and the second pass turned that table into a sentence. If it prints nothing, the loop ended before a text block arrived. Add print(response.stop_reason) inside the loop and watch the values change.
Now break it deliberately. Delete the tool_use_id line and read the error, because a tool result with no matching id is rejected by the API and it is the most common beginner bug there is. Ask a question that needs two commands and watch the loop run twice. Ask something impossible and watch it either give up or spin forever.
One warning about this example. It passes model output straight into a shell with shell=True, which is acceptable on a scratch machine you can rebuild and wrong everywhere else. Stage 6 fixes that. The concepts under the loop are covered at more length in building your own AI agent on a VPS.
Stage 3: tools the agent did not already have
Your run_command tool works, but a real agent needs tools that reach outside the box: a ticket system, a database, a repository. Writing a bespoke wrapper for each service, for each agent, does not scale.
The Model Context Protocol (MCP) is the answer the industry settled on. An MCP server exposes a set of tools over a standard transport, and any MCP aware agent can use it with no custom glue. The reference filesystem server is one command:
npx -y @modelcontextprotocol/server-filesystem /home/you/projectsThat needs Node installed, and the directory argument is the only path the server will touch. This is the security model in miniature: the server decides the boundary, not the model. Point a client at it and your agent gains file reading and writing that you did not write. Running these properly, under a service account and with the transport choices explained, is covered in running MCP servers on a VPS for AI coding agents.
The lesson of this stage is that tool design is the real work. A vague description makes the model guess. A tool that returns forty thousand characters poisons the context window. A tool that can delete things will eventually delete things.
Stage 4: memory, which is mostly just files
Beginners reach for a vector database here. Do not, at least not yet.
An agent has no memory between calls. You resend the whole conversation every time, which is why a long session costs more per turn than a short one. So memory splits into two problems. The first is what fits in the context window right now, which you manage by summarising, by trimming old tool output, and by caching the stable prefix of your prompt so you pay a fraction of the price for it. The second is what survives a restart, which is storage.
For the second problem, a plain markdown file the agent can read and write beats a vector database for almost every first project. Give it one file, tell it the format, tell it to read that file before starting and update it when it learns something. You get most of the benefit, and you can open the file and see what your agent believes. Reach for embeddings and retrieval when the notes stop fitting in the context window, and not before.
Stage 5: the loop is the product
By now you can make an agent that works while you watch it. Stage 5 is making it work when you do not.
Four questions decide whether an unattended agent is safe to leave alone. What triggers it, so it does not run on nothing. What boundary does it operate inside, so a mistake stays small. How is the result verified, because an agent that grades its own homework always passes. What budget stops it, in tokens or in wall clock time. Designing those four deliberately is the discipline described in loop engineering, and what that definition covers.
The exercise: take your stage 2 agent, give it a task that needs four or five steps, and add a hard iteration cap. Then remove the cap and watch what an unbounded loop does to your token bill. Do that once on a small budget so you never do it by accident on a large one.
Stage 6: safety, secrets, and cost
This stage is not optional, and it is last only because you cannot feel the risk until you have built something that works.
Run the agent as its own unprivileged user, never as root and never as your own account, so the blast radius is a directory rather than a machine. Keep credentials out of the model's reach, because anything sitting in the context window can be quoted back out through a tool call, and the fix is scoped short lived tokens behind a helper as described in keeping secrets out of your AI agents. Put a hard ceiling on spend, since an unattended loop bills every iteration with nobody watching, and the caps and batching that keep it sane are in AI agent cost control on an always on VPS.
Cost deserves one concrete number. As of July 2026, Claude Opus 5 bills $5 per million input tokens and $25 per million output tokens, and a chatty agent resending a growing conversation can push a few hundred thousand tokens through a single task. Prompt caching, and a smaller model for routine steps, change that arithmetic far more than any prompt tweak will.
Prompt injection belongs here too. If your agent reads a web page, an issue tracker, or an inbox, then whoever wrote that text is also writing instructions to your agent. The defence is not a cleverer system prompt. It is the boundary, because an agent that cannot delete a repository cannot be talked into deleting one.
Which map should you follow?
Pick one curriculum and finish it instead of sampling six. The Microsoft ai-agents-for-beginners repository is the most complete free one, an eighteen lesson course that has passed 70,000 stars as of July 2026, and it maps cleanly onto the stages above. Roundups of trending agent repositories are useful for seeing what exists and much less useful as a syllabus, because a list sorted by stars is sorted by popularity rather than by teaching order.
When you want a real project to practise on, a coding agent is the best first target: the feedback is immediate, the tools are obvious, and mistakes are cheap to undo. Running a coding AI agent on a VPS walks through one end to end. If you would rather study working systems than build from zero, the comparison in the best self hosted AI agents shows how several projects solve the same loop differently.
How long does this take?
For someone who already programs, stages 1 and 2 are an evening. Stage 3 is a weekend, most of it spent on tool descriptions rather than on protocol. Stages 4 and 5 take a few weeks of real use, because you only learn what your agent forgets by watching it forget. Stage 6 never quite finishes, in the sense that every new capability you grant reopens it.
Two months of consistent evenings gets most people to a working, bounded, useful agent. The ones who take a year are usually the ones who kept reading instead of building.
FAQ
Do I need to know machine learning to build an AI agent?
No. Building an agent means calling a model over an API and wiring its tool requests to real functions, which is ordinary application programming. You never touch training, gradients, or datasets. The skills that decide whether your agent works are schema design for tools, error handling, and Linux permissions. Machine learning theory becomes relevant only if you go on to fine tune a model, which is a different job with different prerequisites.
Should I start with a framework like LangChain or CrewAI?
Write one raw loop first, then adopt a framework. A framework replaces the thirty lines in stage 2 with a configuration object, which is convenient once you know what it replaced and confusing before that. When your agent misbehaves you have to reason about the message list and the tool results directly, and that is much harder if you have never seen them. After one loop of your own, a framework saves you time rather than hiding the mechanism.
How much does it cost to learn AI agents?
Less than most people expect, if you cap it. A hosted API key and a small VPS cover everything in these six stages. The real risk is not the hourly rate, it is an unbounded loop billing every iteration while you sleep. Set a hard spend limit on your API account on day one, add an iteration cap to every loop you write, and use a cheaper model for routine steps. Running the model locally removes the token bill and replaces it with a hardware requirement.
What is the difference between an AI agent and a chatbot?
A chatbot answers once. An agent repeats a cycle: the model asks for a tool, your code runs it, the result goes back, and the model decides what to do next. That repetition is what lets an agent finish a task with several steps, and it is also why agents need boundaries that chatbots do not. A wrong answer from a chatbot is a bad paragraph. A wrong answer from an agent is a bad paragraph plus whatever it did about it.