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 an orchestration framework. It breaks an agent into five modules—perception, planning, execution, memory, and evaluation—and shows a minimal kernel of roughly twenty lines: a loop, a tool contract, and an explicit termination condition. It then covers practical implementation points for state-machine planning, local tool validation, layered memory, context governance, and regression evaluation, plus structured logging and cost controls. The conclusion: a hand-written agent is viable and offers structural advantages in controllability, observability, and cost predictability, with a hybrid approach recommended for most teams.

    1. Define the Problem First: An Agent Is a Feedback Control Loop

    Before asking whether you can skip a framework, strip away the marketing language and return to the engineering fundamentals. A usable agent system is not just a wrapped chat endpoint. It consists of five modules that can evolve independently:

    • The perception layer turns user input and external state into structured context.
    • The planning layer decomposes a goal into executable steps.
    • The execution layer calls tools and handles failures.
    • The memory layer persists facts and intermediate conclusions across turns.
    • The evaluation layer decides whether the output meets the bar and drives iteration.

    What mainstream orchestration frameworks actually do is connect these five layers through a unified set of abstractions, adding conveniences such as visualization, caching, and callbacks. They lower the startup cost, but they also introduce abstraction leaks: when the business requires fine-grained control over retry policies, context-trimming order, or concurrency, developers often have to read through the framework source code. The value of building your own lies precisely here—you write a control flow with clear business semantics, rather than configuration options buried in someone else’s abstraction.

    2. The Minimal Viable Kernel: One Loop and One Tool Contract

    The starting point for a hand-written agent is simple: a while loop, a tool description, and one model call. Example code:

    1. def run_agent(goal: str, tools: dict, max_steps: int = 8):
    2. history = [{"role": "system", "content": SYSTEM_PROMPT}]
    3. for step in range(max_steps):
    4. history.append({"role": "user", "content": goal if step == 0 else "continue"})
    5. resp = llm.chat(history, tools=tool_schema(tools))
    6. if resp.tool_calls:
    7. history.append(resp.message)
    8. for call in resp.tool_calls:
    9. result = tools[call.name](**call.args) # execute and catch exceptions
    10. history.append({"role": "tool", "content": str(result)})
    11. else:
    12. return resp.content
    13. return "Maximum steps reached; hand off to a human"

    This code is only about twenty lines, yet it covers the three most critical engineering decisions for an agent: a step limit (to prevent infinite loops and runaway costs), a structured contract for tool calls (arguments generated by the model and validated locally), and an explicit definition of the termination condition. A real project only needs to grow retry, parallelism, auditing, and fallback capabilities on top of this foundation.

    3. Implementation Points for the Five Modules

    Planning: prefer an explicit state machine over free-form thinking. The stable approach in production is to model the flow as a finite set of states, with transitions between nodes driven by business conditions, and let the model make only local decisions inside a node. This makes every step testable and replayable, and when something goes wrong you can pinpoint a specific state instead of saying “the model suddenly went off track.”

    Tool calls: keep validation local. Model-generated arguments are untrusted, so you must perform type checks, range constraints, and permission checks before execution; write operations should introduce an idempotency key to avoid duplicate submissions. A tool should return a trimmed, structured result rather than the entire raw payload, or the context will quickly be overrun.

    Memory: layer it, don’t pile it up. Short-term memory holds intermediate conclusions for the current task; long-term memory uses vector retrieval plus metadata filtering for recall; factual information is written to structured storage. The key is to set a write threshold and an expiration policy so that noise does not settle into “long-term facts.”

    Context governance: the biggest hidden benefit of building your own. You can precisely control the trimming order, summary granularity, and token budget, prioritizing the limited window for system constraints and the latest evidence rather than leaving it to a framework’s default policy.

    Evaluation: no evaluation, no iteration. Build a regression set containing typical cases, edge cases, and adversarial cases, and monitor baselines for accuracy, tool-call success rate, average steps, and cost per run. Run the regression after any prompt or model change.

    4. Observability and Cost: Turning the Black Box White

    A hand-written system should emit structured logs by default: an input summary for each step, the model’s raw response, tool arguments and latency, and token consumption. Combined with a general logging service and monitoring/alerting capabilities, this forms request-level tracing. For cost governance, you can implement tiered model routing (simple intents go to a lightweight model), result caching, batching, and concurrency limits. If you need elastic capacity, you can deploy stateless executors on a container platform and scale them on demand, keeping state external in object storage or a database—a common pattern with general-purpose infrastructure from cloud providers such as Baidu AI Cloud.

    5. When Not to Build Your Own

    The conclusion is not that frameworks are useless. If the goal is to validate an idea quickly, the team lacks agent engineering experience, or you need ready-made multi-role collaboration and visual debugging, a mature orchestration solution is more efficient. Building your own fits three scenarios: strongly regulated processes that require end-to-end auditing, extreme sensitivity to latency and cost, and highly customized toolchains. The pragmatic route is a hybrid: build the kernel yourself to control the flow, and bring in surrounding capabilities as needed.

    In summary, a hand-written agent in pure Python is not only feasible but also has structural advantages in controllability, observability, and cost predictability. The real barrier is not the amount of code, but whether you are willing to do the three “unglamorous” things—state, validation, and evaluation—solidly.