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 Python and a large model API, without any orchestration framework. It reviews the industry spectrum of technical recommendations, explains what frameworks actually solve, and lists the hidden costs of abstraction layers. A minimal runnable agent loop in under thirty lines is provided, along with the engineering pieces needed around it: tool registry, state management, memory strategy, fault tolerance, observability, and human-in-the-loop confirmation. The article closes with practical guidance on when to hand-write an agent and when to adopt a framework.
1. The Real Answer: Yes, but Know Your Boundaries
Can you build a usable AI Agent with nothing but Python and a large model API, without any orchestration framework? The answer is yes. And in a fair number of real engineering scenarios, this path is not merely viable but better.
The reason is not mysterious. The runtime core of an agent comes down to three things: string handling, API calls, and loop control. The model generates text and structured instructions; your code translates those instructions into real actions and stitches the results back into the context for the next round. These three things happen to be exactly what Python does best. When an abstraction layer brings no new capability and merely repackages a for loop and a dict, the complexity it adds is a net loss.
This is not an argument that frameworks are useless. Frameworks solve real problems; those problems just may not exist in your project, or may not yet be severe enough to justify a full abstraction layer as a hedge.
2. The Main Technical Positions Form a Spectrum
Looking at the public technical guidance from several major players, a clear spectrum of caution emerges:
- The most cautious end: One model vendor explicitly advises developers in its engineering practice documentation to “start with direct calls to the model API,” noting that frameworks add an abstraction layer that obscures the actual prompts and responses, makes debugging harder, and tends to lure developers into unnecessary complexity when a simpler approach is sufficient. The same document warns that incorrect assumptions about a framework’s internals are a frequent source of production issues.
- A middle path: Another vendor offers its own lightweight agent development toolkit that emphasizes “code first,” keeping only essential primitives and avoiding over-abstraction.
- Emphasis on interoperability: Some vendors choose to support multiple third-party orchestration options, leaving the choice to developers.
- The most framework-friendly: Others argue that for most teams, adopting a mature framework is usually the more cost-effective choice.
Notably, one team shared publicly that after using a certain orchestration framework in production for about a year, they removed it entirely, reporting that “efficiency and collaboration both improved after removal.” The value of such cases is not to prove frameworks are bad, but to highlight a commonly overlooked fact: the maintenance cost of a framework accumulates over time, while its benefits are most visible early on.
3. What Frameworks Actually Solve: Acknowledging Their Value
To make a rational choice, you must first describe accurately the pain points frameworks try to eliminate. Taking common industry solutions as examples, their core abstractions typically include:
- Unified model interface: Hides differences in request and response formats across vendors, lowering migration cost;
- Chain orchestration: Strings multiple calls into a pipeline, feeding the previous step’s output into the next;
- Autonomous decision loop: Lets the model choose which tool to call and whether to finish;
- Tool integration layer: Declares and invokes external systems in a uniform way;
- State and memory management: Saves, trims, and compresses context across turns.
One layer up, graph-based orchestration solutions offer state graphs, conditional edges, checkpoints, and human-in-the-loop nodes to handle complex branching and resume long-running tasks. Multi-agent collaboration solutions use role definitions (role, goal, background) and task dispatch to divide labor and cross-check results.
All of these capabilities map to real needs. The question is whether your needs are already strong enough to require them.
4. The Hidden Cost List: The Real Price of Abstraction
- Broken debugging chain: The error stack passes through layers of wrapping, and you see an internal framework exception rather than a problem with your prompt.
- Loss of prompt control: Templates are wrapped layer upon layer, so the text finally sent to the model is not exactly what you wrote, and behavior drift is hard to trace.
- Version coupling: Interfaces change frequently, so upgrading means refactoring; a minor version update may change default behavior.
- Capability ceiling: When you need a parameter or strategy the framework does not expose, you can only wait or hack its internals.
- Cognitive load: Team members must first learn the framework’s conceptual model before they can read the business logic.
5. A Pure Python Implementation: A Minimal Runnable Core
The core loop is under thirty lines yet covers the entire skeleton of an agent:
import json, requestsdef agent_loop(goal, tools, model, max_steps=12):messages = [{"role": "user", "content": goal}]for step in range(max_steps):resp = requests.post(model["endpoint"],headers={"Authorization": f"Bearer {model['key']}"},json={"model": model["name"], "messages": messages,"tools": tools}, timeout=60).json()msg = resp["choices"][0]["message"]messages.append(msg)if not msg.get("tool_calls"): # No tool call means convergencereturn msg["content"]for call in msg["tool_calls"]: # Execute real actions locallyresult = dispatch(call["function"]["name"],json.loads(call["function"]["arguments"]))messages.append({"role": "tool","tool_call_id": call["id"],"content": json.dumps(result, ensure_ascii=False)})return "Maximum steps reached; hand off to a human"
Around it, you fill in the engineering pieces:
- Tool registry: A
dictmapping names to functions, with JSON Schema descriptions the model uses to decide; - State management: A
dictholding the goal, completed subtasks, and intermediate conclusions, serialized to object storage or a database when you need checkpoint recovery; - Memory strategy: Sliding window plus summary compression to control token size;
- Fault tolerance: Exponential backoff retries for network and rate limits; tool exceptions returned to the model as structured errors so it can self-correct;
- Observability: Log the prompt, response, latency, and token usage of every step to a logging service, with monitoring and alerts;
- Human-in-the-loop: Insert a confirmation before critical actions with a single
if, no dedicated node abstraction required.
6. Decision Guide: When to Build Your Own and When to Use a Framework
Lean toward hand-writing: The workflow is relatively fixed; you need fine-grained control over prompts and cost; the team wants full ownership of the debugging chain; the model API you depend on is fairly stable; you need deeply customized strategies.
Lean toward a framework: Multi-agent collaboration and complex branching are core requirements; you need ready-made checkpoints and human review; the team is large and needs unified standards; you want to validate a prototype quickly.
The pragmatic advice is to go in stages: during the prototype phase, call the API directly and get the business logic working; once repeated code has stabilized into shape and the pain points are concrete and describable, introduce abstraction. Let requirements pull in the framework, rather than letting the framework define the requirements. If you run in the cloud, general capabilities such as model services, container platforms, object storage, logging, and monitoring are enough to support a self-maintained agent runtime, with no need to bind to a proprietary orchestration layer.
7. Conclusion
The feasibility of hand-building an agent does not come from “frameworks are all bad,” but from an engineering common sense: abstraction must have a counterpart in value. When your core loop is clear, observable, and rollback-able, simplicity itself is the most reliable architecture.
