Strip away the hype and an AI agent is three things: a model, a set of tools, and a loop- reason, act, observe, repeat until done. A working one is about 50 lines of code, and you’ll write them in this guide. Then we’ll cover the part the tutorials skip: why agents break in production, and what actually fixes them.
The word “agent” gets stuck on everything now, so let’s draw the lines precisely. A chatbot maps one message to one response - all it can do is talk. A workflow chains model calls in an order your code decides: summarise, then classify, then draft. Useful, predictable, and still not an agent. An agent is the third thing: you give the model a goal and a set of tools, and the modeldecides the steps - which tool to call, what to do with the result, whether it’s done or needs to keep going.
That distinction - who decides the next step, your code or the model - is the entire definition. It’s also the practical engineering advice most tutorials bury: if you can specify the steps in advance, build a workflow, not an agent.Workflows are cheaper, faster, and predictable. Agents earn their cost only when the path genuinely can’t be known upfront - debugging, research, multi-step tasks over messy real-world data. This is the same advice Anthropic gives its own customers, and ignoring it is the number-one source of overengineered AI products.
The systems you already know fit this frame exactly. Claude Code and Cursor are agents whose tools are “read file, edit file, run command.” Deep-research features are agents whose tools are “search, fetch, read.” The always-on assistants people run on frameworks like Hermes are agents whose tools are “everything on your machine, reachable from Telegram.” Different products, same three parts underneath.
The anatomy: four parts, no magic
Every agent you’ve heard of - Claude Code, Hermes, the research agents - is these four parts, arranged with taste.
The model
The reasoning engine - Claude, GPT, or an open model. It decides what to do next based on the goal and everything observed so far. You don’t train it; you rent its judgement per token.
The tools
Functions the model is allowed to call: search the web, read a file, query a database, send an email. Each is described to the model with a name, a description, and a typed schema. Tools are where an agent touches the real world - and where you enforce what it can’t touch.
The loop
The while-loop around the model: reason → act → observe, repeated until the task is done. The model requests a tool, your code runs it, the result goes back in, and the model reasons again. This loop IS the agent - everything else is configuration.
The context
Everything the model can see this turn: the goal, the conversation, the tool results so far. Context is finite and degrades as it fills - managing what enters and leaves it is most of the real engineering in production agents.
The walkthrough: a working agent in ~50 lines
We’ll build a small but genuinely agentic example: a price-comparison agent that decides for itself which lookups to make. TypeScript and the official Anthropic SDK, no framework. The same shape works in Python almost line for line.
Step 1 - define a tool. A tool is a function you describe to the model: a name, a plain-English description, and a JSON schema for its inputs. Two things matter more than beginners expect. The descriptionis read by the model every turn - it’s prompt engineering, so write it the way you’d brief a junior colleague. And the model never executes anything itself - it only ever requests a call; your code runs it, which is exactly where you enforce permissions, limits, and sanity checks.
agent.ts - the tool
import Anthropic from '@anthropic-ai/sdk'
const client = new Anthropic() // reads ANTHROPIC_API_KEY
// A tool = a name, a description the model reads, and a typed schema.
// The description is prompt engineering - write it for the model.
const tools: Anthropic.Tool[] = [
{
name: 'get_price',
description:
'Get the current price in MYR for a grocery item at a named store.',
input_schema: {
type: 'object',
properties: {
item: { type: 'string', description: 'e.g. "eggs (10 pack)"' },
store: { type: 'string', description: 'e.g. "Lotus\'s", "Jaya Grocer"' },
},
required: ['item', 'store'],
},
},
]
// Your implementation - the model never sees this code, only the results.
async function getPrice(item: string, store: string): Promise<string> {
const res = await fetch(`https://your-api.example/prices?item=${item}&store=${store}`)
return await res.text()
}
Step 2 - write the loop.This is the part with an undeserved reputation for complexity. Send the conversation to the model. If it responds with tool calls, run them, append the results, and send everything again. If it responds with plain text, it has decided the job is done. That’s the whole secret:
agent.ts - the loop
// The agent loop: reason -> act -> observe, until done.
async function runAgent(goal: string) {
const messages: Anthropic.MessageParam[] = [{ role: 'user', content: goal }]
while (true) {
const response = await client.messages.create({
model: 'claude-opus-5',
max_tokens: 16000,
system: 'You are a price-comparison agent. Compare stores, then answer.',
tools,
messages,
})
// Always append the full assistant turn back into history.
messages.push({ role: 'assistant', content: response.content })
// No more tool calls? The agent has decided it's done.
if (response.stop_reason !== 'tool_use') {
return response.content.find((b) => b.type === 'text')?.text
}
// Act: run every tool the model requested, return every result.
const results: Anthropic.ToolResultBlockParam[] = []
for (const block of response.content) {
if (block.type === 'tool_use' && block.name === 'get_price') {
const { item, store } = block.input as { item: string; store: string }
results.push({
type: 'tool_result',
tool_use_id: block.id,
content: await getPrice(item, store),
})
}
}
messages.push({ role: 'user', content: results })
// ...and loop: the model observes the results and reasons again.
}
}
console.log(await runAgent(
'Where are eggs, milk and rice cheapest this week - Lotus\'s or Jaya Grocer?'
))
Run it, and watch what makes it an agent: nobody told it to make six price lookups. It reads the goal, decides it needs eggs, milk and rice at two stores each, requests those calls - current models will batch several in one turn - reads the results, and writes a comparison. Change the goal to one item and it makes two calls instead. The model is deciding the control flow.That’s the property everything else in agent-land is built on.
Three production notes before you ship anything real. Return everytool result, including failures - pass errors back as results with an error flag and let the model react; it’s surprisingly good at rerouting around a failed call. Add a step budget - a loop cap (say, 15 iterations) so a confused agent burns a bounded number of tokens, not your monthly budget. And log every turn - when an agent misbehaves, the transcript of what it saw and chose is the only way to debug it.
Where agents actually break
The demo above works. Production is where honesty is owed, because the gap between a demo agent and a dependable one is nearly all of the work - practitioners who’ve dissected production coding agents report that only a tiny fraction of the code is “AI logic”; the rest is context management, tool routing, and recovery.
Context rot. Every tool result lands in the context window, and long tasks fill it with stale noise until the model loses the plot - repeating steps, forgetting constraints from twenty turns ago. Fixes: summarise or clear old tool results, keep durable facts in an external store rather than the transcript, and split long jobs into fresh-context stages.
Error compounding.A workflow that’s wrong at step two fails visibly. An agent that’s wrong at step two keeps going, building on the mistake with perfect confidence. The fix is verification the agent can’t skip: tests it must run, checks against source data, or a second model pass whose only job is to find fault with the first.
Unbounded cost. Loops multiply tokens - a 50-step run rereads its growing history 50 times. Step budgets, token budgets, and prompt caching (cache the stable prefix; pay pennies to reread it) are the difference between an agent that costs cents and one that surprises you on the invoice.
None of this is a reason not to build - it’s the map of where the craft actually lives. Designing the loop itself - stop conditions, budgets, triggers, recovery - has grown into a named discipline this year: loop engineering. And wiring many agents and feedback loops into one reliable system is its own layer again - graph engineering. We cover both in companion guides to this one.
Do you need a framework?
Later, maybe. First, no - and the order matters. Build your first agent with the raw SDK loop, the way we just did. It’s 50 lines, you understand every one of them, and afterwards every framework’s documentation reads as “ah, they automated that part” instead of mysterious vocabulary.
Then reach for infrastructure when you need what it genuinely provides. The SDK’s built-in tool runners remove the loop boilerplate for custom tools. The Claude Agent SDK gives you the full Claude Code harness - file tools, bash, permissions - as a library. Graph frameworks like LangGraph coordinate multiple agents with explicit state. And Hermes - the open-source framework that’s dominated 2026 - turns an agent into an always-on service with chat gateways and persistent, self-improving skills. They’re deployment and orchestration upgrades, not intelligence upgrades: the reason-act-observe core is the same 50 lines everywhere.
One more honest note, because we teach this for a living: the hard part of agent-building isn’t the loop - it’s the judgement around it. Which tasks deserve an agent, how to verify output you didn’t write, when to kill a run. That judgement comes from shipping real software, which is why our 12-week programme makes students build and evaluate a real AI product feature, then direct an AI coding agent through a full spec → plan → review → deploy cycle before they graduate. If you’re earlier than that - still getting comfortable with code itself - learning to code with AI is the right on-ramp, and the free 6 Projects in 6 Days gets you shipping this week.
FAQ
What is an AI agent?
An AI agent is a language model given tools and a loop: it reasons about a goal, takes an action (calls a tool - search, read a file, run code), observes the result, and repeats until the task is done. That loop - reason, act, observe - is what separates an agent from a chatbot, which only ever responds once, and from a workflow, where your code decides every step in a fixed order. In an agent, the model decides the steps.
How do I build an AI agent from scratch?
Four pieces: pick a model with strong tool use (e.g. Claude via the Anthropic SDK), define your tools as functions with a name, description, and typed input schema, then write the loop - send the conversation to the model, and while it responds with tool calls, execute them, append the results, and call the model again. A working single-purpose agent is roughly 50 lines of TypeScript or Python. Frameworks are optional; the loop is not.
Do I need a framework like LangChain or Hermes to build an AI agent?
Not to start - and building your first agent without one teaches you what frameworks actually do. The raw SDK loop is ~50 lines and fully under your control. Reach for infrastructure when you need what it genuinely provides: an always-on service, chat-platform gateways, persistent memory, or multi-agent coordination. Rule of thumb: frameworks are deployment and orchestration conveniences, not intelligence upgrades.
What is the difference between an AI agent and a chatbot?
A chatbot maps one message to one response - all it can do is talk. An agent can act: it has tools, and it loops - calling a tool, reading the result, deciding the next step - until the goal is reached, potentially across dozens of steps with no human in between. Same underlying model, completely different system around it. The chatbot answers "what flights are cheap?"; the agent searches, compares, and books one.
What are AI agents actually used for in 2026?
The proven production categories: coding agents (Claude Code, Cursor - the most mature use case by far), research and data-gathering agents, customer-support triage, back-office automation (invoices, reconciliation, reporting), and personal always-on assistants running on frameworks like Hermes. The pattern across all of them: high-volume knowledge work with a verifiable result. Agents still do badly at open-ended tasks where nobody can check the output.
Stop reading about agents. Ship one. The loop is 50 lines. The judgement is the course.
In Phase 3 of the AI-Native Software Development Programme you build a real AI product feature, evaluate it properly, and direct an AI coding agent through a full spec-to-deploy cycle - mentor-reviewed. Beginners welcome; the free crash course is the on-ramp.