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

    This article examines whether a production-grade AI agent can be built in pure Python without a heavy orchestration framework. It defines what "hand-rolled" actually means, explains why custom architectures often win on efficiency, personalization, and robustness, and breaks down five core modules: input normalization, planning and decision-making, layered memory, tool execution, and the main loop with termination conditions. It also covers six engineering essentials for production, including idempotency, context governance, fault tolerance, observability, security, and evaluation, plus a practical framework for deciding what to build versus adopt.

    First, Define the Problem: What “Hand-Rolled” Actually Means

    Before discussing feasibility, it helps to set boundaries. “Pure Python, hand-rolled” here means building the complete agent loop without a heavyweight agent orchestration framework, relying only on the language standard library and a few general-purpose capabilities (HTTP calls, JSON parsing, logging, and basic vector retrieval algorithms). It does not rule out using foundation model services, object storage, message queues, container platforms, logging services, or monitoring and alerting. Instead, it keeps the core asset—decision logic and flow control—in your own hands.

    This distinction matters because many debates come from mismatched definitions: one side means “no dependencies at all,” while the other means “no orchestration framework.” Once the boundary is clear, the conclusion becomes sharper—build the core in-house and source general capabilities externally is the more pragmatic engineering path today.

    Why Production Agents Tend Toward Custom Architectures

    General-purpose orchestration solutions excel at compressing the time from prototype to demo, which is extremely valuable when validating an idea. But once a system enters production, three requirements surface that generic abstractions struggle to satisfy at the same time:

    • Efficiency: Real business is highly sensitive to time-to-first-token, end-to-end latency, and per-task cost. To cover more scenarios, general frameworks often introduce multiple layers of abstraction and implicit scheduling, lengthening the chain and reducing controllability.
    • Personalization: Business rules, domain terminology, approval workflows, and data boundaries all differ. A custom architecture can encode domain constraints directly into planning and validation, rather than “praying” that a prompt makes the model understand.
    • Robustness: Production must handle timeouts, rate limiting, tool failures, context overflow, and non-compliant model output. A hand-rolled loop gives precise control over retry, fallback, circuit breaking, and rollback strategies.

    This is why leading teams generally build the core themselves—not to show off, but because generic solutions struggle to cover efficiency, personalization, and robustness simultaneously.

    The Five Core Modules of a Hand-Rolled Agent

    A usable agent is essentially a controlled loop with tools and memory. It can be broken into five modules.

    1. Perception and Input Normalization

    First, unify user input, environment state, and history summaries into structured objects, then apply length trimming, sensitive-information detection, and language and format normalization. This step sets the ceiling for everything downstream.

    1. from dataclasses import dataclass, field
    2. from typing import Any
    3. @dataclass
    4. class Observation:
    5. user_input: str
    6. context: dict[str, Any] = field(default_factory=dict)
    7. trace_id: str = ""

    2. Planning and Decision-Making

    Planning does not need to be complex from the start. A good starting point is “single-turn decision plus a finite state machine”: the model only selects an action (call a tool or reply directly), and the state machine validates legality. Once the scenario stabilizes, introduce task decomposition and multi-step planning.

    1. def decide(obs: Observation, tools: dict[str, callable]) -> dict:
    2. # Illustration: in a real implementation, the model outputs structured JSON, followed by schema validation
    3. action = model_choose_action(obs, available_tools=list(tools))
    4. if action["type"] == "tool" and action["name"] not in tools:
    5. return {"type": "reply", "text": "This capability is currently unavailable. Please adjust your request."}
    6. return action

    3. Memory System

    Memory should be layered: short-term in the conversation window, mid-term in task state, and long-term in retrievable domain knowledge. For long-term memory, use a general retrieval pipeline of “chunk—vectorize—retrieve—rerank,” and keep source identifiers for traceability. Never stuff all history into the context; that makes cost and latency spiral out of control at the same time.

    4. Tool Invocation and Execution

    The tool layer should follow three principles: idempotent interfaces, strict parameter validation, and controllable timeouts. Design write operations to be retryable or compensable where possible, avoiding the gray zone of “the call succeeded but the result is unknown.”

    1. def run_tool(name: str, args: dict, tools: dict[str, callable]) -> dict:
    2. tool = tools[name]
    3. schema_ok, err = validate(args, tool.schema)
    4. if not schema_ok:
    5. return {"ok": False, "error": err}
    6. try:
    7. return {"ok": True, "data": tool.fn(**args)}
    8. except TimeoutError:
    9. return {"ok": False, "error": "timeout", "retryable": True}
    10. except Exception as e:
    11. return {"ok": False, "error": str(e), "retryable": False}

    5. Main Loop and Termination Conditions

    The main loop must explicitly define a maximum number of steps, a budget cap, and termination conditions to prevent infinite loops and runaway costs.

    1. def agent_loop(obs: Observation, tools: dict, max_steps: int = 8) -> str:
    2. for step in range(max_steps):
    3. action = decide(obs, tools)
    4. if action["type"] == "reply":
    5. return action["text"]
    6. result = run_tool(action["name"], action["args"], tools)
    7. obs.context.setdefault("steps", []).append({"step": step, "result": result})
    8. return "Maximum processing steps reached. Please split the task and retry."

    Six Things You Must Add for Production

    The gap between a working demo and one that withstands live traffic is engineering detail.

    • Idempotency and compensation: Generate a unique key for each tool call so repeated execution produces no side effects; on failure, fall back to compensation or manual handling.
    • Context governance: Use layered summarization, on-demand retrieval, and dynamic trimming, treating the token budget as a first-class citizen.
    • Fault tolerance and fallback: Distinguish retryable from non-retryable errors and apply exponential backoff; when necessary, switch to a smaller-parameter model or return a templated reply.
    • Observability: Assign a trace identifier to each run, log decisions, tool inputs and outputs, latency, and cost, and connect to logging services and monitoring alerts.
    • Security and permissions: Grant tools least-privilege access, require secondary confirmation for sensitive operations, and validate compliance on both input and output.
    • Evaluation loop: Build an offline test set and regression baseline, and continuously track accuracy, task completion rate, average steps, and cost per run.

    Build vs. Buy: How to Choose

    The pragmatic approach is not either/or but layering: for prototype validation, general retrieval pipelines, and standardized automation workflows, adopt mature solutions directly in exchange for speed; for core business rules, critical decision paths, and cost- and latency-sensitive steps, build in-house and gradually accumulate internal capabilities. The test is simple—is this logic your differentiator, and does it require fine-grained trade-offs across efficiency, personalization, and robustness?

    Conclusion

    Building an AI agent in pure Python without a framework is not only feasible but also an effective path to understanding what an agent really is and building long-term competitiveness. The barrier is not the amount of code but whether you have thought through the loop, memory, tools, fault tolerance, and evaluation. Get the minimal loop stable first, then evolve it under real business pressure—that is a sustainable engineering rhythm.