Building an AI Agent from Scratch: The Architecture Behind the Magic
This article breaks down what an AI agent really is—a large language model wrapped in software engineering components—and shows how to build a usable agent without any framework. It covers the core reasoning-acting loop with minimal Python code, the four engineering pillars of production-ready agents (planning, context and memory management, tool design, and safety/observability), and common failure modes with practical countermeasures. Readers will learn that agent development is less about prompt tricks and more about assembling reliable systems around an LLM.
Agents Have No Magic: They’re Layered Wrappers Around an LLM
Discussions about AI agents today are often shrouded in mystique, as if they represented an entirely new form of intelligence. But once you’ve actually built one, you discover a plain truth: the only “intelligent organ” in an agent is the large language model itself. Everything else is traditional software engineering.
Think of an LLM as a brain with an extremely high IQ and vast knowledge, but with no hands, prone to hallucination, and incapable of acting on its own. It can only do one thing: predict output text based on input text. To turn this “brain in a vat” into something that produces real value, you must equip it with:
- Hands and feet: tool-calling capabilities that let it read and write files, call APIs, and execute commands;
- Eyes and ears: multimodal input and environment perception so it can “see” the results of its actions;
- Memory: a way to remember past decisions and intermediate states;
- Rules and safeguards: constraints, validation, fallbacks, and rollback mechanisms that prevent hallucinations from causing damage.
Collectively, these are the “software engineering framework.” Without it, an LLM is just a text generator that chats; with it, it becomes what we call an agent.
The Core Agent Loop: One While Loop Is Enough
Strip away all the fancy wrapper frameworks, and any agent’s core reduces to an extremely simple loop—the industry commonly calls it the ReAct pattern (Reasoning + Acting):
- Perceive: assemble the user’s goal, conversation history, and available tools into a context and feed it to the LLM;
- Reason: the LLM outputs a decision—either “call this tool with these arguments” or “the task is done, here’s the answer”;
- Act: the program parses that decision and actually executes the corresponding tool;
- Observe: append the execution result to the context;
- Loop: return to step 1 until the LLM judges the task complete or a termination condition triggers.
Below is a minimal, runnable skeleton that depends on no framework (shown using a generic SDK interface style):
import jsonTOOLS = {"run_code": lambda code: exec_sandbox(code), # sandboxed execution"read_file": lambda path: open(path).read(),"write_file": lambda path, content: write(path, content),"search": lambda query: web_search(query),}def agent(goal: str, max_steps: int = 20):messages = [{"role": "system", "content": SYSTEM_PROMPT}, # declare role and tool protocol{"role": "user", "content": goal},]for _ in range(max_steps):# 1. Reason: the LLM decides the next stepresp = llm.chat(messages,tools=[{"name": k, "schema": TOOL_SCHEMA[k]} for k in TOOLS],)# 2. Termination: the model gives its final answerif not resp.tool_calls:return resp.content# 3. Act: execute each tool callfor call in resp.tool_calls:try:result = TOOLS[call.name](**call.args)result = str(result)[:4000] # truncate to prevent context explosionexcept Exception as e:result = f"Execution failed: {e}" # feed failures back so the model can self-correct# 4. Observe: write the result back into the conversation historymessages.append(tool_result(call.id, result))return "Maximum steps reached; task not completed"
This code is the “cell” from which all agent frameworks are built. Every framework on the market is essentially more engineering capability wrapped around this loop: task decomposition, multi-agent collaboration, state persistence, human-in-the-loop approvals, and so on.
The Four Engineering Pillars That Make an Agent Actually Usable
A bare loop only runs demos. Production systems must add the following designs.
1. Planning and Task Decomposition
Throwing a complex goal directly at the model often causes it to get “lost” along a long chain of steps. Common approaches:
- Plan first, execute later: have the LLM produce an explicit task list (a plan) first, then execute items one by one, dynamically revising the plan after each step;
- Subtask isolation: give each subtask its own clean context, avoiding interference from irrelevant history;
- Reflection: after a failure, explicitly have the model analyze what went wrong and revise its strategy before retrying, rather than blindly running it again.
2. Context and Memory Management
The context window is limited, and the agent loop keeps inflating the history with every step, so it must be managed actively:
def compact(messages, token_budget):"""Keep system prompt + the most recent turns, compress older history into a summary"""if count_tokens(messages) <= token_budget:return messageshead = [messages[0]] # system prompt must be preservedtail = messages[-6:] # keep recent interactionssummary = llm.chat([{"role": "system","content": "Compress the following history into key decisions and conclusions, within 500 words."}]+ messages[1:-6])return head + [{"role": "user", "content": f"History summary: {summary}"}] + tail
Additionally, long-term cross-session memory typically relies on vector retrieval: store key facts in a vector store and, on each turn, retrieve the relevant ones by similarity and inject them into the context.
3. Tool Design Quality Determines the Agent’s Ceiling
How accurately the model selects tools depends heavily on the quality of tool descriptions. Practical guidelines:
- Write descriptions for humans: tool names and parameter descriptions should use clear business language and explain “when to use / when not to use”;
- Fewer parameters are better: if a single simple parameter solves it, avoid nested objects;
- Readable results: error messages should be specific (which parameter was wrong, how to fix it) so the model can self-correct;
- Idempotency and sandboxing: all operations with side effects (writing files, executing code) must run in a sandbox and support rollback.
4. Safety Guardrails and Observability
LLMs hallucinate and can make dangerous decisions; engineering must provide a “babysitter”:
- Tiered permissions: read-only operations execute automatically; write operations and money-related operations require human approval or whitelisting;
- Output validation: validate tool parameters against a schema first; reject invalid input and feed the error back;
- Step and budget caps: hard limits on maximum loop iterations and token consumption to prevent runaway loops burning money;
- End-to-end logging: record the complete prompts, model outputs, and tool results for every turn—this is the only way to troubleshoot abnormal agent behavior.
Common Failure Modes and Countermeasures
| Failure Mode | Symptoms | Countermeasures |
|---|---|---|
| Hallucinated calls | Invents nonexistent tools or parameters | Strict schema validation + explicit tool inventory |
| Looping in circles | Repeatedly executes the same failing step | Detect repeated actions, inject reflection prompts or force a strategy change |
| Context pollution | Irrelevant history interferes with current judgment | Isolate context per subtask, compact history promptly |
| Giving up midway | Loses the goal during long tasks | Fix the goal in the system prompt, check progress every turn |
Conclusion
The underlying principles of agents are not mysterious: the LLM handles thinking, the loop handles orchestration, tools handle action, and engineering handles the guardrails. The real barrier isn’t “prompt-writing” tricks but the software engineering ability to assemble these plain components into a reliable system. Once you understand the few dozen lines of core loop above, you hold the key to this field. What remains—like every engineering problem—is iterating, analyzing logs, and hardening boundaries to turn a demo into a product.
