Can You Build an AI Agent in Pure Python Without a Framework?

    This article examines whether a practical AI agent can be built in pure Python without relying on a general-purpose agent framework. It defines what an agent actually is, presents a minimal skeleton built around a control loop and three data tables, and walks through the four real challenges: context management, tool-call reliability, planning and reflection, and evaluation with observability. It also covers hidden costs, security requirements, and clear criteria for when self-building is the better choice and when a managed cloud approach makes more sense.

    1. First, Define What “Building It Yourself” Means

    Before discussing feasibility, we need to pull the term “agent” out of marketing language and back into engineering language. The widely accepted definition is that an agent is a system with a large model as its decision-making core, capable of maintaining state, autonomously planning steps, and interacting with the external environment through tools. It must contain at least four elements: a control loop, context, a tool layer, and termination conditions. Miss any one of them, and what you have is just a single-turn question-and-answer session with format constraints.

    One notable pattern in the original observations: today’s mainstream AI coding tools almost all emphasize in their technical talks that they use a “custom architecture” rather than directly adopting a general-purpose agent framework. The engineering meaning of this is not that frameworks are useless, but that when the business has hard requirements on latency, cost, and controllability, the abstraction layer of a general framework becomes a burden. Frameworks excel at standardizing common patterns, at the cost of requiring you to accept their state model, message format, and extension points. Once requirements go beyond those boundaries, the cost of reading the framework’s source code is often higher than writing three hundred lines of loop yourself.

    So the real prerequisite for “pure Python, built by hand” to be viable is: your scenario boundaries are clear, the number of tools is limited, and failure modes are enumerable. Conversely, if you need multi-agent collaboration, complex human-in-the-loop approval, or long-term memory across sessions, the marginal cost of building it yourself rises quickly.

    2. The Minimal Viable Skeleton: One Loop and Three Tables

    The core of a hand-built agent is just one loop; everything else is data structures built around it.

    1. def run_agent(goal, tools, model, max_steps=12):
    2. ctx = [{"role": "system", "content": SYSTEM_PROMPT}]
    3. for step in range(max_steps):
    4. ctx.append({"role": "user", "content": goal if step == 0 else "continue"})
    5. msg = model.chat(ctx, tools=tools) # returns text or a tool call
    6. ctx.append(msg)
    7. if not msg.tool_calls:
    8. return msg.content # termination condition 1: the model gives a conclusion
    9. for call in msg.tool_calls:
    10. result = tools[call.name](**call.args)
    11. ctx.append({"role": "tool", "content": result})
    12. return "Step limit reached, escalating to a human" # termination condition 2: fallback

    This code is under twenty lines, yet it already exposes three key design points: termination conditions must be designed explicitly (the model states it is done, a step limit, a timeout, a budget cap); context is the only “memory”; and tool return values are the only “perception.” The so-called three tables refer to the tool registry, the session state table, and the call audit table; they determine whether the system can be observed and reviewed after the fact.

    3. The Real Difficulty Is Not the Loop, but These Four Areas

    Context management. This is where a self-built solution breaks first. Raw tool output can easily run to thousands of tokens, and it will blow up the window in three to five rounds. The common engineering practice is layering: keep recent content verbatim, produce structured summaries for the middle range, and keep only conclusions and file paths for the distant past. At the same time, set a length cap and a truncation marker on tool return values, so the model does not treat truncated content as complete fact and keep reasoning on top of it.

    Tool-call reliability. The tool description is the model’s “eyesight,” and a vague description directly leads to choosing the wrong tool. Parameters should use strong type constraints and be validated a second time on the server side, because model-generated parameters are untrustworthy. All tool calls must be idempotent or retryable, and write operations should introduce a confirmation step. In addition, tool error messages must be written for the model to read—throw a raw stack trace back, and the model will usually repeat the same erroneous call.

    Planning and reflection. A pure loop easily falls into “one step at a time.” A feasible lightweight improvement is to explicitly maintain a task checklist state and require the model to update the checked items each round; after two failures, force a strategy switch or fall back to asking a question. This is more cost-effective than introducing complex multi-agent orchestration.

    Evaluation and observability. A self-built agent without evaluation cannot be iterated on. At a minimum, you should accumulate a task set with ground-truth answers, record the tool-call trace, token consumption, and elapsed time for each step, and use two metrics—success rate and average number of steps—for regression. Logs, metrics, and alerts can directly use the general-purpose logging and monitoring/alerting capabilities available on the cloud, avoiding the need to maintain your own storage and dashboards.

    4. Cost, Security, and When to Stop Building It Yourself

    The hidden costs of self-building are often underestimated: prompt iteration, tool adaptation, concurrency and rate limiting, failure retries, and permission isolation. On security, you must follow the principle of least privilege; tool credentials should be injected by the server rather than written into the context; all external content must be treated as untrusted input to prevent prompt injection; and destructive operations require human confirmation and an audit trail.

    The decision criteria can be simple: if you have fewer than ten tools, the flow is basically linear, and you need deep customization of output format and latency, pure Python self-building is the better choice; if you need complex orchestration, long-running tasks, or multi-role collaboration, or if the team lacks the manpower to maintain infrastructure, adopting general-purpose model services, container platforms, message queues, and object storage on the cloud to carry the workload is the more rational choice. The value of building it by hand is not to replace frameworks, but to make you truly understand what the framework was doing for you.