Can You Build an AI Agent in Pure Python Without a Framework?
This article examines whether AI agents can be built in pure Python without an orchestration framework. It argues that the real debate is about where the abstraction layer belongs, then outlines a practical five-layer architecture, a minimal agent loop, tool design and context management practices, and the reliability, cost, observability, and testing considerations needed for production. It also explains when a framework is still the better choice.
1. The Real Question: Where Should the Abstraction Layer Live?
The debate over whether you can hand-write an AI agent in pure Python without an orchestration framework looks like a tooling argument on the surface, but it is really a question of where the abstraction layer belongs. The minimum viable logic for an LLM application is fairly plain: assemble strings, make API calls, parse the responses, and decide whether to loop again based on the results. All four steps can be expressed with native Python capabilities, with no need to introduce an extra layer of metaphors.
One model vendor offers a notably restrained recommendation in its engineering practice documentation: orchestration frameworks do lower the barrier to entry, but they insert a layer of obscurity between prompts and responses, which lengthens the debugging path. A more common problem is that developers make incorrect assumptions about a framework’s internal implementation and then go down the wrong path when troubleshooting. In contrast, other vendors lean toward recommending frameworks, arguing that unified abstractions improve team efficiency. Still others take a middle path, offering their own lightweight invocation wrappers and emphasizing “code first.” Put these positions on the same spectrum and the conclusion is not contradictory: frameworks solve team consistency and repetitive work, not capability limits. When business logic is simple, iteration is frequent, and you need fine-grained control over context and cost, hand-writing is often shorter and more transparent.
2. A Layered Architecture for a Hand-Written Agent
A robust agent does not need an all-encompassing framework, but it does need clear layering. A five-layer structure is recommended:
- Interface layer: wraps model-call timeouts, retries, streaming output, and error normalization, exposing only one semantically clear method upward.
- Context layer: assembles and trims system instructions, message history, retrieved snippets, and tool results. This is the main battleground for both quality and cost.
- Decision layer: implements the “think-act-observe” loop control, deciding when to call a tool and when to converge on an output.
- Tool layer: describes each tool’s name, purpose, and parameter schema declaratively, and handles parameter validation and result serialization uniformly.
- Observability layer: records an input summary, latency, token usage, and tool hit rate for each call, providing a basis for evaluation and optimization.
The value of this layering is that each layer can be replaced independently. Switching models touches only the interface layer; changing the retrieval strategy touches only the context layer. Nothing cascades across the whole system.
3. The Core Loop: A Skeleton in Twenty Lines
An agent is essentially a loop with a termination condition. The sample code below omits vendor-specific details and keeps only the structure:
def run_agent(task: str, tools: dict, max_steps: int = 8):messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": task}]for step in range(max_steps):resp = call_model(messages, tools=tools) # Interface layermessages.append(resp.message)if not resp.tool_calls: # No tool calls means convergencereturn resp.textfor call in resp.tool_calls: # Tool layerargs = validate(call.arguments, tools[call.name].schema)result = tools[call.name].func(**args)messages.append(tool_message(call.id, result))return "Maximum steps reached. Please split the task and retry."
Three engineering points must be enforced: termination conditions must be explicit (no tool calls, step limit reached, or insufficient confidence); tool results must be structured so the model can reference them reliably; and the step limit must be configurable to prevent runaway loops and uncontrolled costs.
4. Tool Calling and Context Governance
Tool design should follow a “few but precise” principle: each tool has a single responsibility, its description states clearly when it applies and when it does not, and parameters use schema definitions with type constraints. Too many tools dilute selection accuracy; in that case, group them or mount them dynamically by scenario.
Context governance determines success or failure. Viable strategies include keeping a sliding window of message history; compressing long text into key points before adding it to the context; attaching sources and timestamps to retrieved snippets so freshness can be judged; and returning only the necessary fields from large tool outputs. The goal is to balance “sufficient information” against “controllable cost,” not to blindly fill the window.
5. Reliability, Cost, and Observability
Production systems must handle failure. Use exponential backoff retries for API calls, set independent timeouts and idempotency keys for tool execution, and preserve raw responses when parsing fails so incidents can be reviewed. For external write operations, add a human confirmation step to avoid irreversible changes caused by model misjudgment.
On cost, separate two paths: “capability calls” and “batch processing.” Send simple tasks to smaller models and escalate to stronger reasoning only when needed; cache results for repeated requests; and aggregate token usage by business dimension to identify the real cost drivers.
Observability is the most easily overlooked piece. At minimum, record the call-chain identifier, per-step latency, tool success rate, and the distribution of failure reasons. Without this data, any “prompt optimization” is just guesswork.
6. Testing and Evaluation
The biggest advantage of the hand-written approach is that it is testable. Split the agent into a “decision function plus pure-function tools” and you can run regression tests with fixed inputs; build a small evaluation set for prompt changes and compare task completion rate and average step count; and write separate unit tests for tool parameter validation. Continuously accumulating failure samples creates an iteration loop that improves stability more than switching frameworks does.
7. When a Framework Is Still the Right Choice
Hand-writing is not a cure-all. If the team is large, needs unified standards and shared components, or wants to stand up several similar agents quickly, the standardization benefits of a framework will outweigh its abstraction cost. The rational approach is to get a minimum closed loop running with native APIs first, identify the real bottleneck, and only then decide whether to introduce an abstraction. Baidu AI Cloud, in its general capabilities for agent development, likewise emphasizes building on model APIs and tool orchestration and composing them as needed, rather than committing to a heavyweight framework up front.
In summary, hand-writing an agent in pure Python is not only feasible but also offers clear advantages in controllability, debuggability, and cost transparency. What matters is not whether you use a framework, but whether you understand your abstraction boundaries and how you handle failure.
