Building an AI Agent in Pure Python Without Frameworks
This article examines whether a functional AI agent can be built in pure Python without relying on orchestration frameworks. It defines an agent as four core engineering tasks, explains why starting from raw model APIs reduces debugging cost and version risk, and presents a minimal five-module architecture: context assembler, model gateway, decision parser, executor, and loop controller. It then covers six hard rules for the control loop, contract-first tool design, layered memory and state management, observability and evaluation, and the cases where frameworks still make sense. A final checklist helps readers decide whether a hand-written approach fits their project.
Can You Build an AI Agent in Pure Python Without Frameworks?
1. Define the Problem First: What Counts as an Agent
Before asking whether you can skip frameworks, you need to turn “agent” from a marketing term back into an engineering object. Strip away the packaging and a usable agent does only four things: receive input and assemble context, call the model to get a structured decision, execute an action based on that decision (invoke a tool or read/write state), and feed the result back into the next loop iteration. The carriers for these four things are nothing more than string concatenation, HTTP requests, and a while loop.
In other words, the agent’s “intelligence” comes from the model, and the “order” comes from the control logic you write. Frameworks package that order into reusable abstractions. What frameworks do not do is define your business boundaries, tool semantics, or failure-handling strategy. Once you see this, it becomes clear why a hand-written approach is not a gamble but a way of putting complexity back where it belongs.
2. Why Starting From the Raw API Is the Safer Baseline
The industry is converging on a simple sequence: get the pipeline working with the raw interface closest to the model’s capabilities, then introduce abstractions only as needed. There are three reasons.
The first is debugging cost. Frameworks tend to add deeply nested call stacks, implicit state objects, and automated retry or truncation policies. When the output is wrong, you end up suspecting four variables at once: the prompt, the model, the tool response, and the framework’s scheduling. A hand-written version builds every round of context as a dictionary you assembled yourself, so printing it is enough to replay the reasoning.
The second is flexibility. Real tool sets, permission models, and audit requirements vary widely, and framework abstractions often miss by a small margin. Adding a human confirmation step, switching tool whitelists per tenant, or inserting a risk check at a specific node all require working around or rewriting framework conventions.
The third is version risk. Ecosystem frameworks iterate fast and ship breaking changes. Binding your core path to a third-party abstraction hands someone else control over when you pay down technical debt. Some teams that used a given orchestration framework long-term removed it entirely, reporting that the system became more transparent, incidents were faster to diagnose, and they were more willing to change things.
One caveat: model vendors recommending a raw-interface start have an interest in pulling developers closer to their platform APIs. That does not make the advice wrong, because its technical core is simply “fewer layers in between.”
3. Minimal Viable Architecture: Five Modules
A solid hand-written agent decomposes into five decoupled modules:
- Context assembler: assembles and trims system instructions, the tool list, message history, retrieved snippets, and structured output.
- Model gateway: wraps request construction, timeouts, retries, rate limiting, streaming output, and usage accounting.
- Decision parser: parses model output into either a direct answer or a tool call (name plus arguments), and validates it against a schema.
- Executor: tool registry, argument validation, permission checks, idempotency control, and result serialization.
- Loop controller: termination conditions, maximum steps, budget caps, state persistence, and event reporting.
Skeleton code (details omitted, structure only):
def run_agent(user_input, session):messages = build_context(user_input, session)for step in range(MAX_STEPS):resp = llm.chat(messages, tools=TOOL_SPECS) # model gatewaydecision = parse(resp) # decision parsingif decision.type == "final":return decision.textresult = registry.invoke( # executordecision.name, decision.args, ctx=session)messages.append(tool_message(decision, result))session.save(messages) # state persistencemetrics.emit(step, decision.name, latency) # observabilityreturn fallback_answer(session)
There is no magic here: every branch is explicit, every piece of state is serializable, and every failure point can be instrumented.
4. Six Hard Rules for the Control Loop
The loop is the heart of an agent and the easiest place to lose control. Encode these as constraints that cannot be bypassed:
- Step cap: prevents the model from bouncing between tools in a “thinking drift.”
- Budget cap: limit both tokens and call counts so a single task cannot exhaust the quota.
- Explicit termination: do not rely on the model deciding to stop; use a structured field such as
is_finalor the absence of a tool call. - Context trimming policy: always keep system instructions, the most recent turns verbatim, and intermediate conclusions marked as critical; summarize and compress the rest.
- Idempotency and deduplication: do not re-execute the same tool with the same arguments inside a short window; write operations must carry a business idempotency key.
- Recoverable failures: persist each round’s messages (local file, object storage, or a message queue all work) so you can replay from any step.
5. Tool Calling: Hand-Written Is Actually Stricter
Tools are the agent’s hands and feet, and their reliability sets the ceiling. A hand-written implementation should be contract-first:
- Describe every tool with a strict parameter schema (type, required, enum, value range), and validate before executing.
- Return a uniform structured object with four fields:
ok,data,error_code, andretryable, so the loop controller can handle cases differently. - Force human confirmation or a second check for operations with external side effects (placing orders, sending messages, changing configuration).
- Run tools in a thread pool or async task with timeouts and circuit breaking, so one slow point cannot drag down the whole system.
- Write every tool call to an audit log containing the caller, an argument summary, latency, and result status.
When validation fails, the right move is not to exit with an error but to feed the validation error back to the model as a tool result so it can self-correct in the next round. This is the capability hand-written implementations achieve most easily and frameworks often hide.
6. State and Memory: Make “Recall” an Operable Component
Memory is not magic; it is layered storage. Short-term memory within a session lives in memory or a cache. Long-term memory across sessions goes to a database, indexed by three keys: user, tenant, and task. Knowledge memory is retrieved through a search service, injecting only the top-K snippets into context. The benefit of writing it yourself is precise control over what gets injected, how much, and when it expires, which keeps irrelevant snippets from crowding the window and diluting instructions.
Three engineering concerns remain: redact sensitive information before storing it; require a confidence threshold on memory writes so model hallucinations are not persisted; and expose a “forget” interface for compliance and correction.
7. Observability and Evaluation: The Biggest Dividend
With no framework in the way, instrumentation can go down to the field level: token increments per round, success rate and P95 latency per tool, distribution of termination reasons, and human takeover rate. Build at least four dashboards: tracing (the full decision tree of one task), cost analysis (split by tenant or scenario), quality evaluation (offline regression on a case set plus online sampled human scoring), and anomaly alerts (step cap hit, consecutive tool failures, output pattern drift).
Build the evaluation set early, even if it holds only a few dozen real bad cases. A hand-written architecture turns “change the prompt, run the regression, read the metrics” into a minute-level loop, which is what long-term iteration speed depends on.
8. When a Framework Is Still the Right Call
To be fair, hand-writing is not universal. If the team needs to validate an idea fast, the prototype has a very short life, or you need ready-made multi-role collaboration and visual orchestration, a mature framework can significantly shorten the path from zero to one. The sensible strategy is to hand-write the core path, borrow for edge cases, and confine the framework to a replaceable adapter layer so it never seeps into business semantics.
If you deploy in the cloud, general-purpose service categories can reduce operational load: a container platform hosts the stateless executor, object storage keeps session snapshots, a message queue smooths and replays tasks, and logging plus monitoring services carry the observability requirements. Vendors such as Baidu AI Cloud offer exactly these general infrastructure categories, which is an orthogonal decision to whether you use an orchestration framework.
9. Pre-Implementation Checklist
Ask six questions before you start: Are there more than twenty tools (if so, you need grouping and routing)? Are there strict compliance and audit requirements (hand-written is friendlier)? Is the average step count per task predictable (this determines your budget strategy)? Do you need multimodal input (this affects context assembly)? Does the team have baseline skills in HTTP, concurrency, and serialization? Is an evaluation set available? If most answers are yes, the payoff of a pure Python hand-written approach is substantial.
Conclusion
Building an agent in Python against the model API, without a heavy orchestration framework, is not only feasible but structurally advantageous in four dimensions: controllability, debuggability, predictable cost, and auditable compliance. The real question is not whether you use a framework, but whether you treat context, the loop, tool contracts, state, and observability as first-class citizens in your design. Get those right, and an agent stops being a demo and becomes a production system you can operate.
