Can You Build an AI Agent in Pure Python, Without Any Framework?
Building an AI Agent without orchestration frameworks—using only Python and model APIs—is not only feasible but often the better engineering choice. This article explains when a pure-Python approach makes sense, breaks an agent into six testable modules (model calls, control loop, tools, memory, observability, and guardrails), provides a minimal kernel code example, and covers key production details like idempotency, output versioning, and offline evaluation. It concludes with guidance on when to adopt a platform instead of building from scratch.
Can You Build an AI Agent in Pure Python, Without Any Framework?
1. The Short Answer: Yes—But “Feasible” Doesn’t Mean “No Architecture”
In real production projects, implementing an AI Agent manually in pure Python with model APIs—without any agent orchestration framework—is not only viable but often the better choice. The reason is simple: an agent’s minimal loop is not complicated. At its core, it is just “model decision-making + tool execution + state tracking + loop control + safety guardrails.” Expressing these stages in a small amount of clear code is often easier to debug, audit, and deploy than pulling in a heavy abstraction layer.
That said, pure Python does not mean casually writing a while loop. Frameworks provide unified abstractions, tool ecosystems, visual debugging, state persistence, and multi-agent orchestration. Their costs include hidden behaviors, version coupling, longer debugging chains, and unclear compliance boundaries. Pure Python’s advantages are fewer dependencies, controllable behavior, auditability, and easy embedding into existing systems; the trade-off is that you must build model-call governance, tool permissions, log tracing, and evaluation replay yourself.
Use these signals to decide. When requirements are relatively stable, the tool count is limited, observability and compliance requirements are high, low-dependency deployment is desired, and the team has strong engineering skills, a pure-Python build is more suitable. If you need complex multi-agent collaboration, dynamic task graphs, large-scale tool registration, visual orchestration, cross-team reuse, and strict SLAs, a platform approach fits better. The key question is not “framework or no framework,” but whether you have engineering discipline.
2. Break the Agent into Six Testable Modules
1. Model Call Layer: Unify First, Then Talk About Intelligence
Model calls should never be scattered across business code. Start by wrapping a unified client that handles timeouts, retries, backoff, rate limiting, error classification, structured output validation, and cost tracking. Every model decision must be a verifiable structure—one of three types: “final answer,” “call a tool,” or “request human confirmation.” On parse failures, do not retry indefinitely; log the raw output and trigger degradation or escalate to a human. A single entry point also lets you centrally manage prompt versions, model parameters, and call logs, so issues remain reproducible later.
2. Control Loop: Max Steps, Budgets, and No-Progress Detection
The agent loop typically follows “goal → plan → act → observe → decide again.” In pure Python, you must set a maximum step count, a total token budget, a wall-clock budget, and repeated-action detection. If several consecutive steps produce no new information, terminate proactively or request human intervention. Keep loop state in an explicit state object rather than global variables—this makes single-step debugging easier and lets you persist every step’s input and output for replay.
3. Tool Layer: Tools Are Not Just Randomly Exposed Functions
A tool registry should at minimum capture name, purpose description, parameter schema, risk level, timeout, idempotency flag, and permission scope. Write-type tools should require idempotency keys so retries never duplicate side effects; high-risk tools should support human confirmation; tool results should be truncated and sanitized; error messages should be readable but must not leak sensitive data. Tool whitelisting and the principle of least privilege are the first line of defense for agent safety.
4. Memory and State: Separate Short-Term Context from Long-Term Memory
Short-term memory holds the current task’s conversation and tool observations; long-term memory supports cross-task retrieval. Do not blindly stuff all history into context—apply summary compression, relevance-based retrieval, and result truncation. Task state should be persistable and versionable for failure recovery and audit. The goal of memory is not “remember as much as possible” but to provide enough decision-relevant information within budget.
5. Observability: No Trace, No Agent Engineering
Every step should record trace_id, step number, input/output summaries of the model, tool arguments and results, latency, token consumption, error stacks, and human intervention points. Logs should be structured for centralized search and replay. Without observability, when an agent hits an infinite loop, calls the wrong tool, or costs spiral, the team cannot locate the cause.
6. Safety and Governance: Guardrails Belong Inside the Loop
Input/output filtering, sensitive data masking, least-privilege access, tool whitelists, double confirmation for high-risk actions, and audit logs should all take effect inside the loop—not as afterthoughts. In particular, actions like deletion, payment, message sending, and configuration changes must require human confirmation or two-phase execution. A key advantage of the pure-Python approach is that these guardrails can be implemented exactly along your business boundaries.
3. A Minimal Kernel Code Example
The following is a framework-free illustrative structure, focusing on state, tool registration, and loop guardrails:
from dataclasses import dataclass, fieldfrom typing import Callable, Anyimport json, time, uuid, logging@dataclassclass ToolSpec:name: strdescription: strfunc: Callable[..., Any]risk: str = "low"timeout_s: int = 10idempotent: bool = False@dataclassclass AgentState:trace_id: strgoal: strhistory: list = field(default_factory=list)step: int = 0confirmed: bool = Falsedef run_agent(goal, tools, llm_client, max_steps=8):state = AgentState(trace_id=str(uuid.uuid4()), goal=goal)for _ in range(max_steps):state.step += 1decision = llm_client.decide(goal=state.goal,history=state.history,tools=[{"name": t.name, "desc": t.description} for t in tools.values()])# decision should pass structural validation; omitted here for brevityif decision["type"] == "final":return decision["content"]if decision["type"] == "tool":tool = tools.get(decision["name"])if not tool:state.history.append({"error": "unknown_tool"})continueif tool.risk == "high" and not state.confirmed:return {"status": "need_confirm", "tool": tool.name}result = tool.func(**decision.get("args", {}))state.history.append({"tool": tool.name,"args": decision.get("args", {}),"result": str(result)[:2000]})continuestate.history.append({"error": "invalid_decision"})return {"status": "stopped", "reason": "max_steps"}
This code is not meant to be feature-complete. It shows that a pure-Python kernel can be very thin: tool registration, state tracking, risk confirmation, max-step limits, and structured decisions all fit within a few hundred controllable lines. The real work lies in prompt versioning, output validation, idempotency design, log replay, and building evaluation sets.
4. Key Engineering Details for Production-Grade Pure Python
First, version your prompts and output protocols. Every change should be replayable and comparable, so a one-line prompt edit never silently breaks tool-call rates. Second, classify errors: model timeouts, parse failures, tool failures, permission denials, and business validation failures each need distinct retry strategies. Third, write operations must be idempotent—retries must never charge twice or send duplicate messages. Fourth, manage context with budgets: apply summarization, retrieval, and result truncation by priority. Fifth, build offline evaluation sets and replay mechanisms, tracking task success rate, average steps, tool error rate, human intervention rate, and cost—not just one-off demo results.
Deployment can stay lightweight: use object storage for traces and replay data, a log service for centralized search, monitoring and alerting for error rates and costs, a container platform to run the service, and a secrets manager for credentials. These are standard cloud capabilities you can combine as needed—for example, Baidu AI Cloud offers object storage, log services, monitoring and alerting, and container platforms among its general infrastructure offerings. Regardless of infrastructure choices, the agent’s core logic should remain portable and auditable.
5. When You Should NOT Build from Scratch
When the system requires complex multi-agent collaboration, dynamic task graphs, a large tool ecosystem, visual orchestration, cross-team reuse, and strict SLAs, hand-rolling quickly becomes “building your own platform,” and the cost may exceed adopting a mature platform offering. A safer path: start with a pure-Python minimal kernel, clearly abstracting the model-call, tool-protocol, state, and logging interfaces; then gradually move to a platform as reuse and governance needs grow. Frameworks are not where intelligence comes from—engineering discipline is what makes agents reliably production-ready.
