Can You Build an AI Agent in Pure Python Without a Framework?
Yes—and in many production scenarios it is the better choice. This article explains what an AI agent actually is at its core: a stateful loop that reads input, calls a model, invokes tools, and writes results back into context. It walks through the five modules you cannot skip (context management, planning strategy, tool calling, memory, and termination conditions), why a hand-written implementation often wins on control, dependency risk, cost transparency, and testability, and the key engineering capabilities required for production: observability, fault tolerance, security boundaries, evaluation, and deployment shape.
1. Define the Problem First: What an Agent Actually Is
In real engineering projects, building an AI agent with nothing but Python and a model API—no heavy orchestration framework—is not only feasible, it is often the better option in a surprising number of scenarios. To see why, you have to strip away the marketing language and go back to what an agent fundamentally is.
A deliverable agent is essentially a stateful loop program: it reads external input, calls the model to reason, invokes external tools when it needs real data or needs to produce side effects, writes the results back into the context, and then decides whether to continue. In pseudocode:
def run_agent(goal, max_steps=12):ctx = Context(goal=goal, history=[])for step in range(max_steps):decision = llm.decide(ctx) # perception and planningif decision.type == "tool":result = TOOLS[decision.name](**decision.args) # tool executionctx.append(tool_result=result)elif decision.type == "final":return decision.answerelse:ctx.append(note=decision.thought)return fallback(ctx) # termination fallback
This roughly twenty-line snippet already covers the entire skeleton of an agent. What frameworks do is package these pieces into something more convenient, while adding incremental capabilities such as memory management, multi-agent collaboration, and visual orchestration. Incremental capability is not the same as necessary capability—that is the first principle for deciding whether you need a framework at all.
2. Five Core Modules You Cannot Skip
2.1 Context Management: The Real Bottleneck
The model itself is stateless; what we call “memory” depends entirely on the context you carry with every request. In engineering terms you need to explicitly design three layers: a system layer (role, boundaries, output specification), a task layer (goal, constraints, current plan), and a history layer (tool calls and results). The history layer must be compressed and trimmed. Common strategies include sliding windows, summary merging, and moving large blocks of raw data to object storage while keeping only a reference identifier. The context budget should be calculated at design time, not patched after you hit an error.
2.2 Planning Strategy: Start Simple, Upgrade as Needed
Planning does not have to begin with a complex approach. The recommended path is incremental: single-turn direct calls → fixed workflow orchestration → plan decomposition with step-by-step execution → multi-turn reflection and correction. The vast majority of business scenarios (classification, extraction, query rewriting, report generation) can be delivered reliably with just the first two levels. Dynamic planning is only worth introducing when the task has long dependency chains or needs to change course midway based on results.
2.3 Tool Calling: Structured Output Is the Foundation of Stability
The tool layer is where the agent meets real systems, and stability depends entirely on how strictly parameters are constrained. The practical points are: define a clear name, purpose description, and parameter schema for every tool; use structured output to constrain what the model returns; retry once with the error message attached when parsing fails; and apply timeout and idempotency design to all tool executions. Example:
TOOLS = {"query_order": {"schema": {"id": "string", "date": "string"},"fn": query_order, # handles timeout, retry, and permission checks internally"timeout": 3,}}
2.4 Memory: Separate In-Session from Cross-Session
In-session memory lives in the context. Cross-session memory needs an external store: the common approach is a relational database for structured facts, object storage for original documents, and a retrieval service for semantic recall. Writes need a filtering standard so that noise does not settle into long-term memory.
2.5 Termination Conditions: The Most Overlooked Safety Valve
You must set three kinds of termination at the same time: a step limit, a time or cost limit, and repeated-action detection (interrupt when the same tool is called consecutively with identical arguments). Missing termination conditions is the most common source of production incidents in hand-written agents.
3. Why Hand-Writing Is Often the Better Fit
Maximum control. Every prompt, every retry, and every branch is visible and editable. When something goes wrong you can pinpoint the exact stage, instead of guessing at behavior inside a framework’s abstraction layer.
Low dependency and upgrade risk. Adopting a framework means accepting its abstraction conventions and its release cadence; interface changes ripple into your business code. A hand-written implementation depends only on the language runtime and the model API, so the upgrade path stays smooth.
More transparent cost. How the context is assembled, how many rounds of history are kept, and which results are cached are all your own decisions, which makes fine-grained cost control straightforward.
More direct testing. The tool layer can be covered by ordinary unit tests, and the model layer can be regression-tested with fixed input/output samples—no need to adapt to a framework’s testing paradigm.
The price is that you implement orchestration, retries, and tracing yourself, so the initial investment is slightly higher. But when the business boundaries are clear, that work is usually on the order of a few days—far less than the long-term cost of adapting to a framework.
4. Key Engineering Capabilities for Production
- Observability: generate a unique trace ID for every run, and log structured records of the input summary, model calls, tool arguments, and latency, closing the loop with a logging service and monitoring alerts.
- Fault tolerance: both model calls and tool calls need timeouts, limited retries, and fallback answers; permission-sensitive operations require a second confirmation.
- Security boundaries: enforce least privilege and input validation on the tool side, and state prohibited overreach explicitly in the prompt—but never rely on the prompt alone for security.
- Evaluation: build a fixed evaluation set and track three metrics: task success rate, average number of steps, and cost per run. Run a regression for any prompt or model change.
- Deployment shape: let a stateless service carry the loop logic and keep session state external, so the container platform can scale elastically.
5. The Verdict
If the goal is to quickly validate a multi-agent collaboration pattern, or you need a ready-made visual orchestration interface, mature frameworks still have value. But if you want production control, a lean dependency tree, and measurable cost, pure Python hand-written is the more pragmatic choice. If you want to reduce infrastructure work, you can build the runtime foundation on general-purpose capabilities such as model services, object storage, container platforms, and log monitoring from Baidu AI Cloud, and focus your energy on the business logic itself. The decision rule is simple: frameworks solve the general orchestration problem, while your competitive edge lies in the loop you define yourself.
