Can You Build an AI Agent in Pure Python Without a Framework?
This article examines whether a usable AI agent can be built with only the Python standard library plus remote model API calls, without any agent orchestration framework. It outlines what frameworks actually abstract away, the hidden costs of debugging, version coupling, capability ceilings, and team onboarding, and the four components of a minimal agent: a model call layer, a tool registry, a main loop, and state management. It also covers the production hardening steps and a practical framework-versus-custom decision guide.
1. The Question: Is a Framework a Requirement or Just a Default?
When building agent applications, one question keeps coming up: if you use no agent orchestration framework at all, and rely only on the Python standard library plus remote model API calls, can you still build a working system? In engineering practice, the answer is yes, and in a fair number of scenarios this kind of “thin implementation” is actually easier to maintain. The guidance in one model vendor’s engineering practice documentation is representative: frameworks lower the barrier to entry, but they insert extra layers of abstraction that hide the prompts and the raw responses, making problems harder to diagnose. They also tend to nudge developers toward unnecessary complexity when a simpler approach is already sufficient. That documentation therefore recommends starting with direct model API calls, since many common patterns require only a small amount of code. It also notes that incorrect assumptions about a framework’s internal behavior are a frequent source of production issues.
Different vendors sit at different points on a spectrum: some clearly advocate calling the API directly; some ship their own lightweight orchestration library and emphasize “code first”; some support multi-framework interoperability; and others lean toward recommending established frameworks. The disagreement itself shows that a framework is not a technical necessity but a trade-off between team size, iteration speed, and control. There have also been cases in the industry where a team removed a framework from production after a year of use and reported that collaboration efficiency improved as a result.
2. What Do Frameworks Actually Solve?
To decide whether you need a framework, first look at the pain points it tries to remove. Mainstream solutions typically offer five kinds of abstraction: a unified model invocation interface to avoid vendor lock-in; chained orchestration that strings multiple calls into a flow; an autonomous decision module that lets the model choose the next action; a tool layer that connects to external systems; and a memory layer that manages state across turns. Workflow-orchestration-oriented solutions go further, offering state graphs, conditional branches, resume-from-breakpoint, and human-in-the-loop capabilities.
Each of these abstractions maps to a real problem: request and response structures do differ across model APIs; a single call cannot complete a multi-step task; the model itself cannot perform real actions; and long-running flows need recoverable state. The key point, however, is that the solutions to these problems are not unique, and not all of them require a general-purpose framework to carry them.
3. The Underrated Hidden Costs
The cost of a framework rarely shows up in initial development; it concentrates in later stages.
- Longer debugging chains. A single error may pass through prompt templates, parsers, retry policies, and callback chains before it finally lands on the actual model response. Without the raw payload, diagnosis often comes down to guesswork.
- Version coupling. Upgrades to a framework’s abstractions force business code to follow along, and the upgrade window is hard to align with the business’s own pace.
- Capability ceilings. When requirements move beyond the framework’s predefined paradigm (for example, custom parallel scheduling or a special context-trimming strategy), the implementation degrades into “working around the framework,” at which point the abstraction is nothing but a burden.
- Team cognitive load. New members have to understand both the framework’s conceptual model and the business logic, which artificially lengthens the ramp-up curve.
4. Four Building Blocks of a Minimal Viable Agent
Set the framework aside, and a reliable agent needs only four parts, all implementable with native Python capabilities.
- A model invocation layer. Wrap request construction, timeouts, retries, and structured output parsing in a single function, and confine vendor differences to that one place.
- A tool registry. Use a dictionary to maintain a “name—description—parameter schema—execution function” mapping, serialized into a tool list the model can recognize.
- A main loop. The classic “think—call—observe” loop, which is essentially a
whilewith a termination condition. - State and context. Use a mutable dictionary to hold message history and intermediate results, trimmed by turn count or token budget.
Illustrative code:
import json, httpxTOOLS = {"get_weather": {"schema": {"city": "string"},"func": lambda city: f"{city}: 24C, clear",}}def call_model(messages, tools):payload = {"model": "your-model","messages": messages,"tools": [{"name": n, "parameters": t["schema"]} for n, t in tools.items()],}r = httpx.post(API_URL, json=payload, timeout=30)r.raise_for_status()return r.json()def run_agent(query, state, max_steps=8):state["messages"].append({"role": "user", "content": query})for _ in range(max_steps):resp = call_model(state["messages"], TOOLS)msg = resp["choices"][0]["message"]state["messages"].append(msg)calls = msg.get("tool_calls") or []if not calls:return msg["content"]for c in calls:spec = TOOLS[c["function"]["name"]]try:result = spec["func"](**json.loads(c["function"]["arguments"]))except Exception as e:result = f"error: {e}" # feed the error back to the model so it can self-correctstate["messages"].append({"role": "tool", "tool_call_id": c["id"], "content": str(result)})return "Maximum steps reached; please split the task and retry"
5. What Production Requires Beyond the Minimum
A minimal implementation is only the starting point; going live requires engineering reinforcement.
- Idempotency and side-effect isolation. Write-operation tools should be designed to be retryable and deduplicable, so repeated model calls do not create duplicate data.
- Structured output validation. Validate the JSON returned by the model against a schema, and on failure feed the validation error back as an observation rather than throwing an exception and terminating.
- Budget control. Limit the maximum number of steps, total tokens, and wall-clock time at the same time, so an out-of-control loop does not lead to out-of-control cost.
- Observability. Fully log each turn’s prompt, raw response, tool inputs, and elapsed time. This is the biggest advantage of a hand-written approach over a framework: a transparent chain.
- Human confirmation checkpoints. Insert an approval step before high-risk actions; a single explicit branch in a state machine is enough, with no dedicated component required.
- Evaluation and regression. Run a fixed set of test cases to regression-test changes to prompts and tool descriptions, putting “the prompt is code” into practice in the workflow.
6. How to Decide
The criteria come down to three points: if the business flow is basically fixed and mainly linear or lightly branched, a hand-written loop has the lowest cost; if you need complex rollback, long-running suspension, and multi-role collaboration, graph-based orchestration starts to show its value; if the team is already deeply dependent on a framework’s debugging and tracing ecosystem, the migration cost of replacing it may exceed the benefit. A middle path is also common: build the core scheduling in-house and introduce a thin wrapper only where it is genuinely tedious, such as model API adaptation.
When deploying on the cloud, capabilities such as model inference, key management, logging and monitoring alerts, message queues, and object storage can be combined on demand as general categories, while the business code itself stays loosely coupled to any specific platform. General-purpose infrastructure capabilities from cloud providers such as Baidu AI Cloud can serve as the runtime foundation for this kind of self-built solution, while the scheduling logic remains fully under the developer’s control.
The conclusion is not complicated: the complexity of an agent application comes mainly from the business itself, not from the absence of a framework. First get the main loop, tools, and state running in native Python, then decide whether to introduce an orchestration layer based on measured pain points. That is usually safer than taking on the cost of abstraction from the very beginning.
