Can You Build an AI Agent in Pure Python Without a Framework?
This article examines whether a functional AI agent can be built in pure Python without a heavy orchestration framework. It breaks down the core complexity of agents, compares framework-first and API-first approaches, and shows how to structure a hand-written agent into independently testable layers. A minimal Python scheduling loop is included, along with the engineering details that frameworks usually handle for you and guidance on when to move from direct API calls to a lightweight abstraction.
1. The Real Question: Where Agent Complexity Actually Lives
When building LLM-based agent systems, one question keeps coming up: do you really need a heavy orchestration framework? To answer it, you have to set aside the marketing narrative and look at what an agent actually does at runtime. A working agent usually does only four things: assemble context into strings and message sequences, call the model inference API over HTTP, parse the structured call intent returned by the model, and execute tools in a loop while feeding results back. Each of these maps to a native capability of any general-purpose language: string handling, network requests, JSON parsing, and loops with exception control.
In other words, an agent’s “intelligence” comes from the model and prompt design, while the “engineering” part is mostly flow orchestration and state management. When the engineering complexity is concentrated there, adding another abstraction layer does not automatically pay off. It can instead hide a readable control flow inside framework callbacks, decorators, and implicit context.
2. Framework-First vs. API-First
Different technical camps take clearly different positions, forming a spectrum. One view is cautious: frameworks lower the barrier to entry, but they obscure the underlying prompts and raw responses, make debugging harder, and tempt developers to layer on unnecessary complexity when a simpler approach is already enough. This view recommends starting from direct model API calls, since many common patterns need only a small amount of code. Another view favors frameworks, arguing that unified abstractions improve collaboration and delivery speed. In between, some teams ship their own lightweight SDKs that are “code-first,” wrapping only what is necessary without taking over the control flow. There are also positions that support interoperability across multiple frameworks.
Notably, some engineering teams have removed frameworks after using them for a long time, and reported that both iteration speed and maintainability improved afterward. The engineering explanation is not complicated: breaking changes from framework version upgrades, debugging costs caused by leaky abstractions, and “reverse engineering” when framework constraints do not match business needs all accumulate into long-term debt.
3. Why It Works: Splitting the Agent into Independently Verifiable Layers
A hand-written approach is viable because it can be split into clear layers that are each independently testable.
- Model access layer: handles only request construction, timeouts, retries, rate limiting, and error classification, with message lists in and structured results out.
- Context construction layer: handles the system prompt, history trimming, retrieval snippet injection, and token budget control, producing the final message sequence.
- Scheduling loop layer: handles the “reason-call-feed back” iteration, termination conditions, and a maximum step guard.
- Tool layer: manages callable capabilities through a function registry, with unified parameter validation, permission checks, and timeout isolation.
- State and persistence layer: stores session state, intermediate artifacts, and checkpoints, supporting recovery and auditing.
- Observability layer: records the prompt version, latency, token usage, and tool result summaries for each call.
The value of this layering is that every layer can be covered by unit tests and is cheap to replace. Switching model providers, for example, only requires swapping the adapter implementation in the first layer.
4. Core Implementation: A Minimal Scheduling Loop
The code below shows the skeleton of a core loop that depends on no orchestration framework. The focus is on being explicit, readable, and easy to debug with breakpoints:
import json, timefrom dataclasses import dataclass, field@dataclassclass AgentState:messages: list = field(default_factory=list)steps: int = 0def call_model(messages, tools):# In a real project, replace this with a request to the model inference API# Handle timeouts, retries, rate limiting, and structured output parsingreturn {"tool": "search", "args": {"q": "keyword"}, "text": ""}def run_tool(name, args, registry):fn = registry.get(name)if fn is None:return {"error": f"unknown tool: {name}"}try:return fn(**args)except Exception as e:return {"error": str(e)}def agent_loop(user_input, registry, max_steps=8):st = AgentState()st.messages.append({"role": "user", "content": user_input})for _ in range(max_steps):st.steps += 1out = call_model(st.messages, list(registry.keys()))if out.get("tool"):result = run_tool(out["tool"], out.get("args", {}), registry)st.messages.append({"role": "assistant", "content": json.dumps(out)})st.messages.append({"role": "tool", "content": json.dumps(result, ensure_ascii=False)})continuereturn out.get("text", "")return "Maximum steps reached; please narrow the task scope"
Three design choices matter here: termination conditions are explicit and controllable; tool exceptions are converted into structured results and returned to the model instead of being thrown to interrupt the flow; and the step limit acts as a hard guardrail against runaway loops and cost overruns.
5. Engineering Details That Are Easy to Underestimate
Whether a hand-written approach holds up over time depends on filling in the capabilities frameworks usually provide along the way.
- Context budget: history and retrieval content grow quickly, so you need to trim and summarize against a token budget while keeping decision-relevant snippets.
- Structured output validation: model output is not inherently valid, so apply schema validation and retry on failure, falling back to a stricter prompt when necessary.
- Idempotency and side-effect isolation: tools that perform writes should use idempotency keys to avoid duplicate writes on retries.
- Concurrency and isolation: multi-session scenarios must keep state from crossing over, and tool calls need timeouts and resource limits.
- Observability and replay: recording prompt versions and intermediate results is what lets you quickly locate whether a regression came from the prompt, retrieval, or a tool.
- Cost governance: track tokens and call counts per session and per tenant, and set budget thresholds and fallback strategies.
6. Running on the Cloud: Offloading Non-Core Work to General-Purpose Services
In production, you can hand non-core capabilities to general-purpose cloud services to keep the code layer simple: object storage for session checkpoints and intermediate artifacts; a message queue for asynchronous task decoupling and peak shaving; a container platform to host stateless inference orchestration services with elastic scaling; logging and monitoring with alerting to track latency, error rates, and token consumption; and a key management service to hold credentials. Baidu AI Cloud offers a fairly complete combination of such general-purpose capabilities, and teams can choose based on their own compliance and scale requirements without changing the agent’s core loop code.
7. Conclusion and Selection Guidance
Building an agent in pure Python without a heavy orchestration framework is not only feasible; it is the safer choice when you need fine-grained control over prompts, value debuggability, or have highly customized business flows. The suggested path is to first get the main flow working with direct API calls and establish an evaluation baseline; then, when cross-team reuse, complex multi-agent collaboration, or unified governance needs appear, introduce a lightweight abstraction or framework, judging by whether it lowers debugging costs and improves delivery speed. A framework is a tool, not the goal. Visibility into the control flow is the foundation of long-term maintainability.
