Is Building an AI Agent in Pure Python Actually Practical?
In real projects, an AI agent does not have to start with an off-the-shelf framework. This article explains the model-decide, tool-execute, result-return loop, a five-part minimal architecture, an illustrative Python control loop, and the governance needed for errors, safety, cost, and evaluation—plus when hand-written code is enough and when a framework makes sense.
In real engineering projects, implementing an AI agent manually with Python and a general large-model interface—without relying on a ready-made agent framework—is entirely practical. In many cases it is also more controllable and easier to maintain. The key point is that an agent is not mysterious. It is usually a loop of model decision, tool execution, result feedback, and continued decision-making, plus state management, error handling, permission control, and observability. Frameworks offer convenience, but they are not required. What actually determines engineering quality is protocol design, boundary constraints, and operational governance—not the number of abstraction layers.
1. Start with the essence: an agent is a loop and a protocol, not a framework
A minimally usable agent usually does four things: receive a goal, let the model decide the next step from the current context, call a tool when needed, and feed the tool result back to the model so the loop can continue until a final answer is produced or a stop condition is reached. The “decision” can be structured output or text in an agreed format. The “tool” can be a general capability such as querying a database, reading a file, calling an internal service, or running a calculation.
A framework’s value is mainly in wrapping the loop, tool registration, message format, state persistence, and observability interfaces. But when the task is small, the number of tools is limited, and the call chain is short, those abstraction layers can increase debugging cost instead. Developers then have to understand the framework’s message model, callbacks, state graph, and upgrade compatibility. When something fails, the investigation path gets longer. A hand-written implementation exposes every line of control flow: when the model is called, how context is trimmed, how tool arguments are validated, how failures are retried, and how cost is limited are all decided by application code.
“Hand-building in pure Python” is therefore not an argument against frameworks. It means learning the minimum principles of an agent first. With a clear protocol, tens to a few hundred lines of code can produce a working agent. As complexity grows, add abstractions only as needed, rather than handing over control to a framework at the start.
2. A minimal workable architecture: five modules are enough to start
First, the model-call layer. It assembles the system prompt, user goal, message history, and tool descriptions into a request, then parses the model response. This layer should handle timeouts, retries, rate limits, error codes, and token budgets in one place so the loop logic is not coupled directly to interface details.
Second, the tool registry. Each tool should have a name, a description, argument constraints, and an execution function. The registry checks the allowlist and parses arguments. Tool descriptions should be clear enough, but sensitive information should not be written into the prompt. Execution functions should be idempotent, or their side effects should be stated explicitly.
Third, the decision loop. At each step, the model must output either a final answer or a tool call. Set a maximum number of steps, a maximum number of tool calls, and a total token budget so the model cannot fall into a useless loop. Stop conditions should be explicit: the goal is reached, a budget is exceeded, failures repeat, human confirmation is required, and so on.
Fourth, state and memory. Short-term state is the message list and intermediate results. Longer-term memory can be stored in files or a general database category. Memory should not grow without limit. Trim it by relevance, freshness, and summarization so context and cost do not run away.
Fifth, observability and safety. Logs should at least record the step number, a summary of the model input, the tool name, a summary of the arguments, the result status, elapsed time, and a cost estimate. High-risk tools should require human confirmation, permission checks, sandbox isolation, and an audit record. An agent without observability is hard to diagnose in production.
3. An illustrative core loop
def run_agent(goal, max_steps=8, max_tool_calls=5):messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": goal},]tool_calls = 0for step in range(max_steps):decision = llm_generate(messages=messages,tools=TOOL_SPECS,temperature=0,)if decision.type == "final":return decision.contentif decision.type == "tool":tool_calls += 1if tool_calls > max_tool_calls:return "Stopped: tool-call budget exceeded"tool = TOOLS.get(decision.name)if tool is None:result = {"error": "Tool does not exist or is not authorized"}else:try:args = validate_args(tool.schema, decision.arguments)result = tool.run(**args)except Exception as exc:result = {"error": str(exc)}messages.append({"role": "assistant","content": decision.raw_content,})messages.append({"role": "tool","name": decision.name,"content": serialize(result),})continuereturn "Stopped: unrecognized decision type"return "Stopped: maximum step count reached"
This pseudocode is intentionally simple, but it covers the core constraints of an agent: model decisions, a tool allowlist, argument validation, exception handling, budget limits, and stop conditions. In a real system, retry backoff, idempotency keys, human approval, result redaction, and trace identifiers can be added on top.
4. What makes it production-ready: feasibility depends on governance
The part most often underestimated in a hand-written agent is engineering governance. Error handling cannot rely on try-catch alone. The model may return malformed output, a tool may time out, and a downstream service may rate-limit the call. Retryable and non-retryable errors need to be distinguished, and the failure trace should be recorded. Tools with side effects also need idempotency and rollback. A write, for example, should carry a request identifier so a retry does not write the same data twice. Safety boundaries should come first: a tool allowlist, argument type checks, redaction of sensitive fields, human confirmation for high-risk actions, and an isolated execution environment are all necessary.
Cost control matters just as much. At the loop level, set limits on steps, tool calls, and tokens, and summarize or retrieval-trim long context. For evaluation, build a regression task set. Measure not only whether the final answer is correct, but also trajectory quality: whether the necessary tools were called, whether useless loops appeared, whether permissions were exceeded, and whether the run finished within budget. Only by combining answer evaluation with process evaluation does an agent have a basis for continuous improvement.
5. When to write it yourself, and when to use a framework
Hand-written code fits when there are few tools and clear boundaries, the call chain is short, audit, permission, and cost controls are strict, the team wants fewer external dependencies, or the goal is to validate a business loop quickly. The code is more transparent, debugging is more direct, and upgrade risk is smaller.
A mature framework or an internal platform is more reasonable when you need multi-agent collaboration, a complex state machine, dynamic orchestration of many tools, integration with a shared observability platform, or reuse across teams. Even then, keep your own implementation of the core protocol, budget control, and safety checks so business logic is not locked inside an abstraction layer.
The conclusion is straightforward: building an AI agent in pure Python is fully practical, and it is a worthwhile starting point for understanding agent engineering. The real investment is not “whether to use a framework,” but making the loop, tools, state, safety, cost, and evaluation solid. A framework can speed things up, but it cannot replace engineering discipline.
