Building an AI Agent From Scratch: A 150-Line Code Breakdown
This article explains how to build a functional AI Agent from the ground up using roughly 150 lines of code. It defines an AI Agent in engineering terms, breaks the architecture down into a control loop and four core data structures (LLM, planning, memory, and tools), and walks through each layer's real problems: output-format stability, controllable planning as a state machine, context budgeting and compression, and tool design rules. It also covers observability, cost control, common failure modes with fixes, and why treating an agent as a testable, iterable software engineering problem matters.
1. Demystifying the Concept: What an AI Agent Actually Is
Before discussing implementation, it helps to pull the term “AI Agent” out of marketing language and back into an engineering context. A practical definition: an AI Agent is a computing program that uses a language model as its decision-making core, can autonomously perform multi-step reasoning around a goal, and calls external capabilities to change the state of its environment.
The original view breaks an agent into four parts: the LLM as the brain, Planning as thinking, Memory as recall, and Tools as the hands and feet. That breakdown points in the right direction, but the causal relationships between these parts need a more rigorous justification rather than a simple list:
- The LLM provides a probabilistic “what to do next” judgment. It is stateless and has no side effects, so it cannot actually accomplish anything on its own.
- Planning is not a hidden feature of the model; it is how the outer program organizes the model’s output. It is the control logic that turns a single question-and-answer exchange into multiple iterations.
- Memory is essentially context engineering: deciding, within a limited context window, what to include, how to compress it, and when to discard it.
- Tools are essentially about constraining non-deterministic output into deterministic calls, translating natural-language intent into executable actions through structured parameters.
So the essential difference between an agent and a traditional question-answering pipeline comes down to one sentence: it has a channel to change external state, and it must bear the multi-step accumulated error of that change. This also explains why the hard part of agent engineering is not “getting it to run” but “getting it to run to completion reliably.”
2. The Minimal Viable Architecture: One Loop, Four Data Structures
A fully functional agent can have its skeleton compressed into a single loop. The complexity of the whole implementation lies not in the loop itself but in how responsibilities are divided among four data structures:
# Illustrative code to explain structure, not a specific interfacemessages = [{"role": "system", "content": SYSTEM_PROMPT}] # Memory: the conversation threadtools = [get_tool_schema(f) for f in TOOL_REGISTRY] # Hands and feet: the capability listfor step in range(MAX_STEPS):resp = llm.chat(messages=messages, tools=tools) # Brain: decision-makingif resp.tool_calls:messages.append(resp.message) # Record the decisionfor call in resp.tool_calls:result = TOOL_REGISTRY[call.name](**call.args) # Execute the actionmessages.append(tool_result(call.id, result)) # Record the observationelse:return resp.content # Converge and exit
This skeleton is only a dozen or so lines because it explicitly pushes complexity into three places: the constraint design of the system prompt, the quality of tool descriptions, and the logic for deciding when the loop terminates. Almost all subsequent engineering effort lands in these three areas.
3. Layer-by-Layer Breakdown: The Real Problem Each Layer Solves
3.1 The Brain Layer: Model Selection and Output Constraints
Model capability sets the upper bound of what an agent can do, but what matters more in engineering is the stability of the output format. Practical points include: prefer models with good support for structured output; state clearly in the prompt that “when no tool can be called, a final answer must be given” to avoid spinning in place; and validate the types of the parameters the model returns, treating any validation failure as a retryable error rather than a crash.
3.2 The Thinking Layer: Writing “Planning” as a Controllable State Machine
Planning should not rely on the model producing a perfect plan in one shot. Instead, use an approach of “small steps, fast iteration, plus explicit state”:
- Task decomposition: have the model first output a list of steps, then let the program advance through them one by one.
- Reflection and retry: feed failed tool results back verbatim and require the model to correct its parameters based on the error.
- Step and budget limits: set a maximum number of iterations and a timeout to prevent infinite loops from consuming resources.
In engineering terms, it is advisable to persist the “plan” as first-class data and write back the state after each step completes. This gives you something to rely on for interruption recovery, log-based troubleshooting, and human takeover.
3.3 The Memory Layer: Context Is the Scarcest Resource
Memory comes in two types: short-term memory is the current sequence of conversation and tool observations, while long-term memory is preferences and facts that persist across sessions. The implementation strategy is layering and compression:
def build_context(short_term, long_term, budget=6000):keep = short_term[-8:] # Keep recent turns verbatimsummary = summarize(short_term[:-8]) # Compress history into a summaryhits = vector_search(long_term, query=summary)[:3] # Recall long-term memory on demandreturn trim_to_budget([summary] + hits + keep, budget)
The key judgment is: do not stuff all history into the context, because noise significantly reduces instruction-following; and do not replace the most recent turns with a summary, because tool parameters and error messages must be preserved faithfully.
3.4 The Hands-and-Feet Layer: Four Rules for Tool Design
Tools are the agent’s only interface to the real world, and their design quality directly determines success or failure:
- The description is the prompt: the tool name and description must let the model accurately judge when the tool applies.
- Keep parameters as flat as possible with minimal nesting, and mark which are required and their value ranges.
- Idempotent and retryable: write operations must be safe to execute repeatedly.
- Least privilege: high-risk actions require a second confirmation or human approval.
def search_docs(query: str, top_k: int = 3) -> str:"""Search the knowledge base for the snippets most relevant to the question. query is a natural-language question."""return format_hits(retriever.search(query, top_k))
4. Observability and Cost Control
Debugging an agent is far harder than debugging an ordinary function, because errors propagate across steps. The lowest-cost governance measure is full-chain logging: record each step’s input context summary, the model’s raw output, tool inputs and returns, elapsed time, and failure reasons. On top of that, you can track statistics such as tool success rate, average number of steps, and per-task consumption to pinpoint whether the problem is with the prompt, the tools, or the model.
For cost control, the recommendation is to route small tasks to smaller models and escalate to larger ones only for complex tasks; cache retrievable results where possible; and proactively compress long histories. If you need to support production workloads, you can combine container platforms for elastic scaling, message queues for peak shaving, object storage for saving execution traces, and logging and monitoring/alerting services for anomaly detection. These general cloud capabilities are available in corresponding categories on platforms such as Baidu AI Cloud.
5. Common Failure Modes and Fixes
- Infinite loop calling the same tool: add repeated-call detection, and when it triggers, forcibly inject a prompt requiring a different path.
- Parameter hallucination: provide a list of allowed values for enum-type parameters, and feed the error back on validation failure.
- Premature convergence: require the model to list its verified sources of fact before giving a conclusion.
- Context overflow: strictly enforce budget trimming and preserve the most recent observations verbatim.
6. Conclusion
The value of 150 lines lies not in the line count but in proving that an agent is a conventional software engineering problem that can be decomposed, tested, and iterated: one loop handles control flow, four data structures handle state, and tools handle side effects. Get this minimal closed loop running with logging and validation in place, and only then move on to multi-agent collaboration and complex planning—your success rate will be much higher.
