Can You Build an AI Agent in Pure Python Without a Framework?

    This article examines whether you can build an AI Agent in pure Python without an orchestration framework. It breaks the agent runtime down into a minimal four-step loop—reasoning, acting, observing, and terminating—and explains that the real engineering cost lies in reliability, observability, and governance rather than the loop itself. You will find a readable minimal Python implementation, four key engineering practices covering tool protocols and idempotency, state machines and resumability, layered memory, and observability with cost control, plus guidance on when self-building makes sense and a deployment checklist.

    1. Asking the Right Question: What Is Actually Hard Without a Framework?

    Is it viable to build an AI Agent in pure Python without an off-the-shelf orchestration framework? The answer depends on which part of the agent you define as the “core.” The widely accepted view in the industry is that the agent runtime is not mysterious: it is essentially a loop of “model inference + tool invocation + state management.” What truly consumes engineering resources is not the loop itself, but the reliability, observability, and governance built around it. A more pragmatic strategy is therefore to implement the core yourself and reuse mature solutions for general-purpose capabilities—vector retrieval, relational storage, message queues, container platforms, logging services, monitoring and alerting, object storage, and so on—rather than building an entire infrastructure stack from scratch.

    1.1 The Minimal Agent Core Has Only Four Things

    • Reasoning: hand the current context to the large model and get the next intended action;
    • Action: parse the tool-call intent in the model output and execute a local function or remote API;
    • Observation: feed the execution result back into the context;
    • Termination: decide whether the task is complete, human intervention is needed, or a budget limit has been hit.

    These four steps form a closed loop. Strip away the abstraction layers of any orchestration framework, and this is what it does—only with added wrappers such as graph-based orchestration, checkpoint resume, and multi-agent collaboration.

    1.2 The Cost a Framework Actually Absorbs for You

    The value of a framework is not “can it run” but “does it keep running.” It typically solves for you: state persistence and failure retries, convergence of parallel branches, insertion of human approval nodes, call-chain tracing and metrics collection, and prompt and model version management. These fall under engineering governance. When self-building, you can cover them with general-purpose cloud services and lightweight in-house components, but you need to make clear trade-offs.

    2. A Readable Minimal Core in Pure Python

    The code below is illustrative only. It shows the structure and contains no vendor-specific interfaces:

    1. import json, time
    2. from dataclasses import dataclass, field
    3. @dataclass
    4. class AgentState:
    5. messages: list = field(default_factory=list)
    6. step: int = 0
    7. budget: int = 8 # max loop steps to prevent runaway
    8. done: bool = False
    9. def run_agent(state: AgentState, llm, tools: dict):
    10. while not state.done and state.step < state.budget:
    11. state.step += 1
    12. reply = llm(state.messages, tools_schema=list(tools.keys()))
    13. if reply.tool_call:
    14. fn = tools[reply.tool_call.name]
    15. try:
    16. result = fn(**reply.tool_call.args)
    17. except Exception as e:
    18. result = {"error": str(e)} # feed errors back so the model can self-correct
    19. state.messages.append({"role": "tool", "content": json.dumps(result)})
    20. else:
    21. state.messages.append({"role": "assistant", "content": reply.text})
    22. state.done = True
    23. time.sleep(0) # placeholder for rate limiting and instrumentation
    24. return state

    There are three key design points here: the budget cap prevents infinite loops; tool exceptions are fed back in a structured form instead of being thrown directly; and every step leaves a hook for instrumentation, making it easy to plug in logging and monitoring later.

    3. Four Engineering Essentials That Decide Success

    3.1 Tool Protocols and Idempotency

    The quality of tool descriptions (name, purpose, parameter constraints) directly determines the model’s invocation accuracy. Production environments must require: write operations carry an idempotency key; timeout and retry policies are declared explicitly; and sensitive operations are gated by a human confirmation node. Tool return values should be unified as structured data, avoiding stuffing large blocks of natural language back into the context and creating noise.

    3.2 State Machine and Checkpoint Resume

    Model the agent as a finite state machine, not a linear script. Each state should define its entry conditions, allowed transitions, and failure fallbacks. State must be serializable and persisted to external storage (a relational database or object storage both work), so that process restarts, scaling, and canary releases do not lose task progress.

    3.3 Layered Memory

    • Short-term memory: the current session context, which needs window trimming and summary compression;
    • Long-term memory: vector retrieval to recall relevant fragments, combined with metadata filtering;
    • Structured memory: business entities written to a database and used through queries rather than being “stuffed into the prompt.”

    The purpose of layering is to control context length and cost while improving recall precision.

    3.4 Observability and Cost Control

    Collect at least three types of metrics: steps and latency per task, tool success rate, and token consumption per task. Log the decision basis (the tool name and a parameter summary from the model output) to make it easy to review “why the wrong branch was taken.” Combine this with quotas and circuit breaking to avoid cost blowups triggered by abnormal input.

    4. When Not to Build Your Own

    If the goal is to quickly validate a prototype, build a knowledge-base Q&A system, or run a standard automation workflow, reusing mature general-purpose solutions offers a clear time advantage. If the core requirements are controllable scheduling semantics, private deployment, deep coupling with internal systems, and audit compliance, a self-built core is more appropriate. The middle-ground approach: build the loop and state machine yourself, delegate retrieval, storage, queues, and monitoring to general-purpose cloud services, and abstract model capabilities behind a unified model access layer to keep them replaceable.

    5. Deployment Checklist

    • Are clear termination conditions and a budget cap defined?
    • Are tools idempotent, with timeouts and error feedback?
    • Is state persistable and recoverable?
    • Is there call-chain tracing and cost alerting?
    • Is there a path for human intervention and rollback?

    Conclusion: building an AI Agent in pure Python is entirely viable. The hard part has never been the loop, but governance. Keeping the core in your own hands and handing general-purpose capabilities to mature infrastructure is the engineering solution that balances flexibility and stability.