Building a Minimal AI Agent in Python: A 150-Line Implementation Walkthrough

    This article walks through building a minimal, working AI Agent in Python using only the standard library, with about 150 lines of core code. It explains what a hand-written agent reveals that frameworks hide, where the boundary between an LLM and an agent lies, and how the four essential parts fit together: a tool registry, a control loop, a context strategy, and a termination condition. You will find working code for tool registration, the agent loop, context and memory layering, and practical guidance on reliability, security, observability, and common tuning pitfalls.

    1. Why Write Your Own Agent

    With no shortage of agent frameworks today, the value of hand-writing a minimal, working agent is not to reinvent the wheel. It is to re-expose the key decisions that frameworks tend to hide: when the model should stop, how tool output should be trimmed, whether to retry or switch paths after a failure, and what to discard first when the context grows too long. Only after writing one yourself can you quickly locate problems when a framework behaves unexpectedly.

    From an engineering perspective, the minimal skeleton of an agent contains just four things: an executable list of tools, a driving loop, a context assembly strategy, and a termination condition. These four are tightly coupled, and a flaw in any one of them surfaces as the model “making things up,” an infinite loop, progressively slower runs, or answers that miss the point.

    2. Where the Boundary Between an LLM and an Agent Lies

    An analogy helps divide responsibilities: a large language model is like an expert who never leaves home, knowledgeable but unable to run errands in person. An agent puts that expert’s brain into an assistant’s body that can run errands, keep notes, and review its own work.

    More precisely, the model’s essential capability is “given an input sequence, output the next fragment over a probability distribution.” It is reactive by nature: it will not proactively read files, perform calculations, or access external systems, and it loses context once the session ends. What an agent does is fill in three missing capabilities around the model:

    • Action: use tool calls to translate natural-language intent into deterministic operations on external systems;
    • Memory: use external storage to re-inject information across turns and sessions back into the context;
    • Control: use a loop and termination checks to turn a single question-and-answer exchange into a step-by-step task-solving process.

    The relationship can be summarized with a formula: Agent = model inference + tool set + context management + control loop. Miss any one of the four, and the system degrades into a chatbot or a one-off script.

    3. Overall Architecture and Code Skeleton

    The sample code below keeps zero third-party dependencies and uses only the standard library. The core logic is about 150 lines, and the focus is on structure rather than feature completeness.

    1. import json, os, subprocess, re
    2. # 1. Tool registry: name -> (description, callable)
    3. TOOLS = {}
    4. def tool(name, desc):
    5. def deco(fn):
    6. TOOLS[name] = {"desc": desc, "fn": fn}
    7. return fn
    8. return deco
    9. @tool("read_file", "Read the text content of the file at the given path")
    10. def read_file(path: str, limit: int = 4000) -> str:
    11. with open(path, "r", encoding="utf-8", errors="ignore") as f:
    12. return f.read()[:limit]
    13. @tool("list_dir", "List the first-level entries under a directory")
    14. def list_dir(path: str = ".") -> str:
    15. return "\n".join(sorted(os.listdir(path))[:200])
    16. @tool("run_shell", "Run a read-only shell command and return its output")
    17. def run_shell(cmd: str) -> str:
    18. out = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=20)
    19. return (out.stdout or out.stderr)[:4000]
    20. # 2. Inject the tool list into the system prompt
    21. def tool_spec() -> str:
    22. return "\n".join(f"- {k}: {v['desc']}" for k, v in TOOLS.items())

    The key to the skeleton is “registration is documentation”: a tool’s description and its calling logic live in the same place, avoiding drift between docs and implementation. Tool descriptions must state the applicable scenarios and the meaning of parameters clearly, because the model relies entirely on this text to make its choice.

    4. The Control Loop: The Heart of an Agent

    The loop body needs to handle four situations: the model gives a final answer, the model requests a tool call, the model’s output cannot be parsed, or the step limit is reached.

    1. def run_agent(llm, task: str, max_steps: int = 8):
    2. history = [{"role": "system", "content": f"You are an assistant that can call tools.\nAvailable tools:\n{tool_spec()}\n"
    3. "Output JSON: {\"thought\":..., \"tool\":..., \"args\":{...}}; set tool to null when no tool is needed."}]
    4. history.append({"role": "user", "content": task})
    5. for step in range(max_steps):
    6. raw = llm(history)
    7. history.append({"role": "assistant", "content": raw})
    8. try:
    9. plan = json.loads(re.search(r"\{.*\}", raw, re.S).group())
    10. except Exception:
    11. return raw # Treat a parse failure as the final answer and let the upper layer validate it
    12. if not plan.get("tool"):
    13. return plan.get("thought", raw)
    14. entry = TOOLS.get(plan["tool"])
    15. if entry is None:
    16. obs = f"Error: tool {plan['tool']} does not exist, available: {list(TOOLS)}"
    17. else:
    18. try:
    19. obs = str(entry["fn"](**plan.get("args", {})))
    20. except Exception as e:
    21. obs = f"Error: {type(e).__name__}: {e}"
    22. history.append({"role": "user", "content": f"Tool returned: {obs}"})
    23. return "Maximum steps reached; task not completed."

    There are three engineering details here that are easy to overlook. First, tool output must be fed back as a “user message” so the model treats it as new evidence rather than its own prior statement. Second, do not throw exceptions to terminate the whole process; instead, convert them into readable text and hand them back to the model so it has a chance to change parameters or switch tools, which is more effective than blind retries. Third, you must set a step limit and a timeout; otherwise the model may bounce back and forth between two tools, forming a resource drain that is hard to notice.

    5. Layered Design of Context and Memory

    Context is a limited and expensive resource. A mature approach usually splits it into three layers:

    • Working memory: the current task’s system prompt, tool list, and the most recent few turns of interaction, kept concise;
    • Session memory: summarize and compress the conversation history, keeping only conclusions, constraints, and confirmed facts;
    • Long-term memory: write information that needs to be reused across sessions into external storage, such as object storage, a database, or a vector retrieval service, and fetch a small number of fragments by similarity when needed.

    For trimming strategy, prioritize keeping system constraints and the most recent tool output, and prioritize discarding lengthy intermediate reasoning; for overly long tool results, produce a structured summary before putting them into the context rather than inserting them as-is.

    6. Reliability, Security, and Observability

    Production hardening usually advances along three lines. For reliability, add idempotency checks and a limited number of backoff retries to each tool call, and set an overall timeout and budget cap for the task. For security, the tool layer should perform parameter whitelist validation, block path traversal, and enforce least-privilege constraints on commands; write and delete operations should be disabled by default or require human confirmation. For observability, write a structured record of each step’s input summary, tool name, elapsed time, and output length to a logging service, and pair it with monitoring and alerting to locate anomalies such as “a surge in steps” or “a rising tool failure rate.”

    In terms of deployment, a stateless control loop is well suited to horizontal scaling on a container platform, while memory and artifacts land in object storage or a managed database, forming an architecture that separates compute from state.

    7. Common Pitfalls and a Tuning Checklist

    • Tools that are too coarse-grained: one tool handles too many responsibilities, making it hard for the model to choose parameters correctly; split them so that “one action maps to one tool”;
    • Vague descriptions: tool descriptions that lack usage timing and constraints significantly raise the mis-call rate;
    • Missing termination semantics: without a clear definition of “when it counts as done,” the loop will keep advancing endlessly;
    • Unbounded context growth: without compression and trimming, cost and latency degrade linearly with the number of steps;
    • Relying only on retries as a fallback: retrying without analyzing the cause of the error just amplifies the failure.

    For implementation, it is recommended to proceed in the order “get the loop working end to end, then add tools, then add governance.” Once the minimal version can reliably complete two or three kinds of real tasks, gradually introduce retrieval augmentation, multi-agent collaboration, and evaluation-set regression, avoiding premature complexity. If managed support is needed, consider general-purpose capability categories offered by cloud providers, such as a container platform to host the runtime, object storage to hold artifacts, and logging and monitoring services for tracing, so you can focus your energy on tool design and the evaluation system.