Building an AI Agent in 150 Lines of Python: Architecture and Engineering Lessons

    This article explains why a capable language model alone cannot complete real tasks, and how an AI Agent closes that gap with a controlled loop that connects model reasoning to the outside world. It breaks down four autonomy levels, a minimal architecture of four modules, and the main loop in Python, then covers four underestimated engineering details: tool descriptions as interface docs, feeding errors back as text, step limits and cost control, and layered memory. A reliability checklist for production and notes on cloud deployment are included.

    1. Where the Problem Starts: Chatting Is Not the Same as Getting Work Done

    When teams integrate a large language model for the first time, they often assume that a strong enough model will solve their business problems on its own. Real engineering projects quickly prove otherwise. A model can produce a perfectly structured plan yet have no way to confirm whether the data in it comes from the latest file. It can output a runnable code snippet yet be unable to read the error on failure and fix itself. It can stay coherent within a single exchange yet know nothing about the context once the session ends.

    This is not a matter of the model being “not smart enough.” It is a mismatch in capability shape. The core capability of a language model is probabilistic sequence modeling and reasoning over a given context. Its input boundary is the context window, and its output boundary is text. Any action that has to cross that boundary — reading a local file, retrieving external knowledge, performing a calculation, calling a business API, preserving state across turns — must be handled by a program outside the model.

    So the engineering definition of an Agent can be narrowed to one sentence: use a controlled loop to connect the model’s reasoning to the outside world, and write the feedback from that world back into the context. The sentence looks simple, but it dictates the implementation skeleton directly: loop, tools, state, and termination condition. None of the four can be missing.

    2. Capability Levels: From Passive Response to a Closed Goal Loop

    Layering systems by autonomy makes it easier to judge which stage you are at.

    • Level 1, passive Q&A: one question, one answer, no state, no side effects. Good for copy polishing and concept explanations.
    • Level 2, retrieval augmentation: external material is injected before the question, and the model only summarizes. This solves knowledge freshness but still cannot change the world.
    • Level 3, single-step tool calls: the model can request one action, such as querying a record or running an exact calculation. Side effects begin to appear.
    • Level 4, multi-step autonomous loop: the model decides the next step based on the previous result until it judges the goal is met. This is what usually counts as an Agent.

    The original analogy of an “expert who never leaves home” versus an “assistant who runs errands” captures the point, but engineering needs a more precise addition: the assistant is reliable not because it runs errands, but because every errand comes with a receipt. Each action has an input, an output, a duration, and a failure reason, and these receipts form the factual basis for the model’s next round of reasoning. An “autonomous loop” without a receipt mechanism is essentially just the model guessing repeatedly.

    3. The Minimal Viable Architecture: Four Modules and One Main Loop

    A runnable minimal Agent needs only four modules.

    1. Model client: turns a message list into a single inference request and returns text plus an optional “tool call intent.”
    2. Tool registry: declares each tool’s name, purpose, and parameter schema in a structured form so the model can choose.
    3. Executor: validates arguments, performs the action, catches exceptions, and normalizes the result into a text receipt.
    4. Session state: keeps the message history and intermediate artifacts, appending to them each round to form a traceable trail.

    The skeleton of the main loop looks like this (illustrative code, with SDK details omitted):

    1. def run_agent(goal, tools, model, max_steps=8):
    2. messages = [
    3. {"role": "system", "content": SYSTEM_PROMPT},
    4. {"role": "user", "content": goal},
    5. ]
    6. for step in range(max_steps):
    7. reply = model.chat(messages, tools=tools.spec())
    8. messages.append(reply.message)
    9. if not reply.tool_calls:
    10. return reply.text # no tool intent, treat as converged
    11. for call in reply.tool_calls:
    12. args = tools.validate(call.name, call.arguments) # argument validation
    13. try:
    14. result = tools.invoke(call.name, args)
    15. except Exception as e:
    16. result = f"ERROR: {type(e).__name__}: {e}"
    17. messages.append({
    18. "role": "tool",
    19. "content": f"{call.name} -> {result}",
    20. })
    21. return "Maximum steps reached; goal not completed"

    With tool definitions and the prompt added, this really does stay around a hundred-odd lines, yet it already has four key engineering properties: structured action declarations, validatable arguments, catchable failures, and a terminable boundary. These four are what make it a system rather than a demo.

    4. Four Engineering Details That Are Easy to Underestimate

    4.1 The Tool Description Is the Interface Documentation

    The text description is the model’s only basis for choosing a tool. A vague description leads to misuse. A good one covers three things: what problem it solves, what the parameters mean and what values they accept, and what it returns on failure. Writing “query orders” as “look something up” is worse than writing nothing.

    4.2 Errors Must Flow Back as Text

    Many implementations throw exceptions and terminate the flow, which throws away the Agent’s biggest advantage. The right approach is to write the error type and key details back into the message list so the model can try different arguments, switch tools, or change strategy. In practice, grading errors is advisable: argument errors can be retried, permission errors should be escalated, and timeouts call for backoff.

    4.3 Step Limits and Cost Control

    An autonomous loop carries an inherent risk of spinning in circles. Beyond a maximum step count, you should also set a per-step timeout, a total token budget, and repeated-action detection (interrupt when the same tool with the same arguments appears consecutively). These are not optional; they are mandatory questions to answer before going live.

    4.4 Layer Memory Instead of Piling Everything into the Context

    The context window is a scarce resource. A workable approach is three layers of memory: short-term holds the current task trail; mid-term holds structured intermediate artifacts (tables, summary conclusions); long-term goes to storage and is retrieved on demand. This controls cost and makes cross-session continuity possible.

    5. A Reliability Checklist

    Going from “it runs” to “safe to ship” usually means adding the following capabilities:

    • Least privilege: grade tools as read-only or write, and require explicit confirmation or a second check for write operations.
    • End-to-end observability: log the tool, a parameter summary, the duration, and the result status for each round so runs can be replayed and diagnosed.
    • Determinism first: do not hand the model what rules and code can guarantee; let the model handle planning and trade-offs.
    • Idempotent design: write tools should support idempotency keys to avoid duplicate side effects from retries.
    • Evaluation-set driven: prepare cases for typical goals, track task completion rate and average steps, and let data drive iteration on prompts and tool descriptions.

    If you deploy in the cloud, you can write state and traces to object storage or a logging service, use a message queue to decouple asynchronous tasks, run the executor on a container platform for isolation and elasticity, and hook up monitoring and alerting for abnormal step counts and sudden error-rate spikes. Baidu AI Cloud offers corresponding capabilities in these general cloud product categories, and you can combine them as needed without changing the Agent’s core logic.

    6. Closing Thoughts

    The value of a hundred-odd lines of code is not that it is short, but that it exposes the essence of an Agent: the model handles reasoning, and engineering handles reliability. Once you make tool descriptions, error feedback, step boundaries, and layered memory solid, any complex business goal is just more tools and constraints added on this skeleton. A sensible next step is to start with read-only tools, get the loop and observability working, and then open up write capabilities gradually.