Can You Build an AI Agent in Pure Python Without a Framework?
This article breaks down the minimal core of an AI agent—a controlled loop of model decisions, local execution, and state feedback—and explains when writing one in pure Python is the better engineering choice. You will learn the four real advantages of a hand-written approach, the six engineering capabilities you must build yourself, and a minimal implementation with budget control and audit logging. It also covers when a mature orchestration framework is still the right call and how to roll out a hand-written agent in production.
1. Define the Problem First: What Is the Minimal Core of an Agent
In an engineering context, a working agent is not mysterious. Once you strip away the wrapping of orchestration frameworks, it is essentially a controlled loop: the model emits a decision at each step, the program validates and executes that decision, and the execution result is fed back to the model until a termination condition is met. In pseudocode:
def run_agent(goal, tools, max_steps=12):ctx = [system_prompt(), user(goal)]for step in range(max_steps):msg = llm.chat(ctx, tools=tools) # model proposes the next actionif msg.finish: # no tool call means convergencereturn msg.textresult = dispatch(msg.tool_call, tools) # validate and execute locallyctx += [msg, tool_result(result)] # feed the result back into contextraise BudgetExceeded(max_steps)
This skeleton of fewer than twenty lines already covers the four most critical elements of an agent: goal input, decision source, action execution, and state feedback. Frameworks mostly layer additional capabilities on top of these four points—graph-based orchestration, state persistence, multi-role collaboration, visual debugging, and so on. Once you understand this, the question of “framework or not” turns from a matter of opinion into a quantifiable engineering judgment: does your business actually need those layered capabilities, and is the cost of building them yourself lower than the cost of adopting a framework?
2. Four Real Advantages of the Hand-Written Approach
The first is control. All branching logic lives in your own code, so when something goes wrong you can step through it line by line with a debugger instead of guessing at state transitions across layers of abstraction and callbacks. For scenarios such as finance, healthcare, and government services that require an auditable decision chain, this transparency is often worth more than development speed.
The second is low dependency and upgrade risk. Agent orchestration projects iterate quickly, and incompatible interface changes are common. Depending only on the language standard library and a single model interface compresses the upgrade surface to one controllable point.
The third is predictable cost. Frameworks often add overhead from extra serialization, state storage, and network round trips, and these costs are amplified in high-frequency call scenarios. A hand-written implementation lets you precisely control the input size and number of calls at each step.
The fourth is model independence. By abstracting prompts, tool descriptions, and the call protocol into your own adapter layer, switching the underlying model service requires changing only one place, avoiding lock-in to a single interface shape.
3. Six Engineering Capabilities You Must Build Yourself
Hand-written does not mean crude. The following modules are all indispensable.
Context management. This is the most underestimated part. You need to design token budget allocation and history-trimming strategies (sliding window, summary compression, relevance-based retrieval and reinjection), and to truncate and structure tool return values so that a single large object does not blow out the window.
Tool contracts and validation. Tool descriptions must clearly state the purpose, parameters, and failure semantics. Before execution you must perform parameter schema validation and permission checks, and after execution you must wrap results into a structured form rather than stuffing raw text straight back to the model.
Fault tolerance and retries. Distinguish retryable errors (rate limiting, timeouts) from non-retryable ones (invalid parameters, insufficient permissions), paired with exponential backoff and jitter. Also set a per-step timeout and dual global budgets for step count and spend to prevent the loop from spinning idle.
Termination condition design. Beyond “the model stops calling tools,” you should also support three fallbacks: an explicit completion marker, budget exhaustion, and detection of no progress over consecutive steps. This is the dividing line for production stability.
Observability. Every step should emit a structured log entry: input summary, decision, tool name, latency, token usage, and result status. Combined with metrics and alerts, this is what lets you diagnose “why is it looping” and “why is the answer off-topic.”
Security boundaries. Run tool execution inside a least-privilege sandbox, require a second confirmation for write operations, treat all external content as untrusted input to guard against prompt injection, and redact sensitive data before it enters the model.
4. A Minimal Closed Loop with Budgeting and Auditing
def step(ctx, tools, budget):if budget.left() <= 0:return {"type": "finish", "text": "Budget limit reached"}msg = llm.chat(ctx, tools=[t.spec for t in tools])audit.log(step=budget.used, decision=msg) # audit trailif not msg.tool_calls:return msgfor call in msg.tool_calls:tool = tools.get(call.name)if not tool or not tool.validate(call.args):obs = {"ok": False, "error": "invalid_call"}else:obs = tool.run(call.args) # execute inside sandboxbudget.charge(obs.tokens)ctx.append(tool_result(call.id, obs))return step(ctx, tools, budget)
The budget object, audit log, and validation logic are deliberately made explicit, and that is exactly the core benefit of the hand-written approach: constraints are not hidden inside framework default behavior but are first-class citizens of your business code.
5. When You Should Still Choose a Framework
If the requirement is long-running multi-role collaboration, if you need graphical orchestration with human approval nodes, if you need out-of-the-box state persistence and replay debugging, and if the team wants to validate ideas quickly, then the time savings from a mature orchestration solution are real. The decision can be reduced to three questions: does the flow need to be dynamically graphed? Do you need a cross-session state machine? Do you require visual operations? If all three are no, hand-writing is usually the better deal.
6. Rollout Recommendations
Start by spending a week building a minimal closed loop and running three real business flows through it, using token consumption, success rate, and average step count as baseline metrics. Then gradually add compression, caching, concurrency, and rate limiting. For the runtime, you can deploy on a container platform, store audit samples in object storage, and use a logging service with monitoring and alerting for observability. Model capabilities can be accessed through a large model API from a cloud provider, keeping the adapter layer replaceable. Baidu AI Cloud offers relatively complete support across these general-purpose capabilities, making it easier for teams to focus on business logic rather than infrastructure.
The conclusion is clear: building an agent in pure Python is not only feasible but is often the better choice for projects with high demands on control, cost, and auditability. Frameworks solve the complexity of collaboration and orchestration, not intelligence itself.
