Can You Build an AI Agent in Pure Python Without a Framework?
This article explains why building an AI agent in pure Python without a framework is often the better engineering choice. It breaks down what an agent actually adds beyond a model call, outlines the hidden costs of abstraction layers, and presents a minimal five-layer architecture implemented with native code. It also covers six critical engineering details—context budgeting, tool contracts, error recovery, state persistence, evaluation, and security—plus guidance on when a framework still makes sense and how to roll out a hand-written agent step by step.
1. First, Define the Problem: What Does an Agent Actually Add?
Before deciding whether you need a framework, narrow down the concept. At the system level, a usable agent adds only three things: a controlled loop, callable tools, and persistent state. Everything else—intent understanding, text generation, structured extraction—is fundamentally just one or more calls to a model interface.
In engineering terms, the main trunk of an agent is an “observe–decide–act” loop:
while not done and step < MAX_STEPS:resp = call_llm(messages, tools=tool_schemas) # decideif resp.tool_calls:results = [run_tool(c) for c in resp.tool_calls] # actmessages.append(tool_results(results)) # feed observations backelse:done = True
This pseudocode is almost the whole secret. String concatenation, JSON parsing, HTTP requests, loops, and exception handling are all capabilities that are mature enough in Python’s standard library and ecosystem that they need no further abstraction. When the core logic is only a few dozen lines, introducing a framework layer quickly throws the cost-to-benefit ratio out of balance.
2. The Real Cost of Abstraction: Not Unusable, Just Not Worth It
There is fairly authoritative engineering guidance urging restraint here: a model vendor’s public agent-building guide states that frameworks lower the barrier to entry by wrapping common low-level tasks, but they add an extra abstraction layer that obscures the actual prompts and responses, makes debugging harder, and tends to lead developers to introduce unnecessary complexity when a simpler approach is sufficient. Its recommendation is to start by calling the model interface directly, because many common patterns require only a small amount of code. Some engineering teams have also removed frameworks entirely after about a year of production use, reporting improvements in both team efficiency and mental overhead.
Abstracting these lessons, the costs of a framework fall into four categories:
- Observability decay. Behind a single failed request, the real system prompt, the assembled context, the truncation strategy, and the retry count are wrapped layer upon layer. You have to learn the framework’s debugging entry points to see what should be directly visible.
- Version and semantic drift. Abstraction layers often use a “unified interface” to smooth over capability differences between models, so behavior may change silently on upgrade, making regression costs higher than maintaining your own explicit code.
- Flexibility constraints. Wanting to change one context-trimming strategy, insert a human review step, or switch a tool to asynchronous concurrent execution all requires working around the framework’s “recommended usage.”
- Cognitive load and team coupling. New members must first understand the framework’s mental model before they can understand the business logic, lengthening the debugging path.
The conclusion is not that “frameworks are useless,” but rather: when requirements are not yet settled and logic is still changing frequently, the thinner the implementation, the better for fast trial-and-error and precise attribution.
3. Minimal Viable Architecture: Five Layers, All Native
Writing an agent by hand does not mean producing a pile of scattered scripts. It is best to divide responsibilities into five layers, each independently testable:
- Interface layer: only parameter validation and protocol conversion, no business judgment.
- Orchestration layer: maintains the loop, termination conditions, and step and budget limits.
- Context layer: handles prompt templates, history trimming, summary compression, and injecting retrieval results.
- Tool layer: unified registration, parameter schema validation, timeout and idempotency control.
- State and observability layer: session storage, structured logs, metrics, and trace identifiers.
A runnable skeleton looks like this (illustrative, with fault-tolerance details omitted):
import json, httpxdef call_llm(messages, tools=None, model="chat-model"):r = httpx.post(LLM_ENDPOINT,json={"model": model, "messages": messages, "tools": tools or []},timeout=30)r.raise_for_status()return r.json()["choices"][0]["message"]def run_tool(name, args):fn = TOOLS[name]return {"name": name, "content": json.dumps(fn(**args), ensure_ascii=False)}def agent_loop(user_input, max_steps=8):messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": user_input}]for _ in range(max_steps):msg = call_llm(messages, list(TOOL_SCHEMAS))messages.append(msg)if not msg.get("tool_calls"):return msg["content"]for c in msg["tool_calls"]:messages.append({"role": "tool","tool_call_id": c["id"],**run_tool(c["function"]["name"],json.loads(c["function"]["arguments"]))})return "Maximum steps reached. Please narrow the task scope and retry."
This code already has the key elements needed for production: explicit termination conditions, a step budget, and structured feedback of tool results. The real engineering effort is not in the loop, but in the “invisible” areas below.
4. Six Engineering Details That Determine Success
1. Context budget and trimming strategy. Context is a finite resource and must be managed explicitly. In practice, allocate quotas across “system prompt + key constraints + the most recent few turns + summary + retrieval snippets,” and when limits are exceeded, compress history first rather than deleting constraints. Summaries should be generated when a turn or token threshold is triggered, preserving to-dos and confirmed facts to avoid goal drift.
2. Tool contract design. Each tool needs a clear name, purpose description, and parameter schema; place parameter validation at the tool entry point, and return a structured error for invalid input rather than throwing an exception, giving the model a chance to self-correct. Introduce idempotency keys for write operations, and set timeouts and limited retries for external calls to avoid the loop amplifying side effects.
3. Error classification and recovery. Classify errors into retryable (rate limiting, timeouts), needs-parameter-change (validation failures), and unrecoverable (permissions, resources not found), applying backoff retries, feeding errors back, and immediate termination with reporting respectively. Never stuff all exceptions into the context and let the model “figure it out,” as that quickly exhausts the budget.
4. State persistence. Store session state separately from business data; the former can go in a cache or object storage, the latter in a database; write a checkpoint at each step to make it easy to resume after interruption and reproduce problems. A trace identifier running through the whole chain is the only clue for tracing back from logs to a specific decision.
5. Evaluation first. Build a small but fixed set of test cases covering the normal path, boundary inputs, tool failures, and malicious inducement. Run them every time you change a prompt or model version, recording task success rate, average steps, token consumption, and human takeover rate. Tuning without evaluation is just guessing.
6. Security and permission boundaries. Follow least privilege on the tool side; sensitive operations require secondary confirmation or human approval; treat external returned content as untrusted data to prevent it from carrying instructions that hijack the flow; filter sensitive information from outputs, and avoid writing full raw text to logs.
5. When You Should Still Choose a Framework
Keep a neutral technical judgment: frameworks are not something to be uniformly excluded. When a team needs to quickly validate multiple prototypes, requires a unified component ecosystem and visual orchestration, or needs standardized governance and a plugin marketplace at the organizational level, the default implementations provided by mature frameworks can significantly shorten the delivery cycle. The reasonable decision approach is thin first, then thick: use a native implementation to get the main trunk working and clarify the real constraints, then introduce abstraction only where there is genuinely duplicated work—or even just borrow its patterns without taking on the dependency.
6. Rollout Path and Cloud Support
It is recommended to proceed in four steps: first, implement a single-turn tool-call loop; second, complete context management and error recovery; third, integrate evaluation and observability; fourth, add incremental capabilities such as concurrency and multi-agent collaboration. For the runtime environment, you can use general cloud services directly: a container platform to deploy stateless orchestration processes, a cache service to store sessions, object storage to archive checkpoints and corpora, a message queue to smooth peaks and decouple long tasks, log services and monitoring alerts for metric collection and threshold notifications, and a key management service to hold credentials. If you use the relevant general capabilities of Baidu AI Cloud, follow the same principle of “thin interfaces, externalized state, built-in observability,” avoiding binding business logic to any single abstraction layer.
Core conclusion: Building an agent by hand in pure Python is not only feasible but often better in scenarios with changing requirements and a need for precise attribution. Frameworks solve the problem of “standardization and scale,” but the core of engineering capability is always loop control, context governance, tool contracts, and the evaluation system—writing these four things clearly in native code is more reliable than depending on any abstraction layer.
