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

    This article explains how to build an AI agent in pure Python without an orchestration framework. It covers the boundary between agents and chatbots, a three-layer architecture that decouples tools, the model, and the control loop, a ReAct reasoning loop with a fixed step limit, and a robustness checklist for moving from a demo to production. You will see how to keep the core decision loop and engineering constraints in your own hands while reusing mature solutions for common components.

    Introduction: Why Revisit Agents Outside a Framework

    In most AI application tutorials today, the starting point is a ready-made agent orchestration framework: a few lines of configuration get a multi-step workflow running, and a single decorator turns a function into a “tool.” This lowers the barrier to entry, but it creates a hidden problem: developers know how to make it run, but not why it runs.

    Once you move into a real project, requirements quickly become specific and demanding: response latency must be predictable, failures must be traceable, tools must be pluggable at runtime, and model providers must be swappable at any time. At that point, the abstraction layer of a general-purpose framework becomes an obstacle. It is worth noting that the production-grade coding agents and complex task systems that actually ship in the industry almost all describe custom architectures in their public technical material, rather than a direct application of a general framework. The reason is not mysterious: a production agent really needs efficiency, customization, and robustness, and those are exactly the three things a general abstraction struggles to balance.

    The position of this article is that writing an agent from scratch is the best way to understand agents, and a necessary path to building differentiated capabilities. Common components, such as the base pipeline for retrieval-augmented generation and automated orchestration, can fully reuse mature solutions; but the agent’s core decision loop is worth owning yourself.

    1. Aligning the Concepts: Where an Agent Differs from a Chatbot

    Early conversational AI was essentially one question, one answer: input text, output text, no persisted state, no outward action. The dividing line for an agent is that it has the ability to act: it can retrieve information, call external APIs, generate artifacts, write to storage, and take responsibility for the results.

    Complexity is not determined by the tech stack, but by the task itself. A minimal customer-service agent may contain only two tools, knowledge retrieval and ticket submission, plus a fallback rule that hands off to a human when it cannot handle the request. It is simple enough, yet fully fits the definition of an agent.

    The essence of an agent can be compressed into four stages: Perceive, Reason, Act, and Learn. This article implements the first three, using the widely accepted ReAct paradigm (Reasoning + Acting), whose core discipline is explicit thinking and explicit action: the reasoning behind each step and each tool call is fully recorded, so when something goes wrong you can trace and locate it. The learning stage involves vector storage and long-term memory mechanisms, which are left for later evolution.

    2. Architecture Design: Three Layers That Must Be Decoupled

    Before writing code, draw the boundaries clearly. A sound design has only three layers: the tool layer, the model layer, and the agent control layer.

    1. Tool Abstraction: The Root of Extensibility

    Tools must follow a registry model: a uniform name, description, parameter schema, and execution entry point. Adding a database query capability requires registering one record, with no change to the control loop. This is the open-closed principle applied directly to an agent: open for extension, closed for modification.

    1. from dataclasses import dataclass
    2. from typing import Callable, Any
    3. @dataclass
    4. class Tool:
    5. name: str
    6. description: str # helps the model decide when to use it
    7. schema: dict # parameter structure, used for validation
    8. func: Callable[..., Any] # the actual execution body
    9. TOOLS: dict[str, Tool] = {}
    10. def register(tool: Tool) -> None:
    11. TOOLS[tool.name] = tool

    The quality of a tool description directly determines call accuracy. A description should state what it does, when to use it, and the boundaries of its input and output, rather than a vague one-line summary of its function.

    2. Separating the Model Layer from the Agent: A Swappable “Brain”

    The model is a pluggable “brain,” and the agent is the “commander.” You might use one model service today, switch to another tomorrow, and switch again later for compliance or cost reasons. If the two are coupled, every replacement means rewriting logic. Once separated, the benefits go both ways: switching providers does not touch business code, and the agent can fall back to a backup model when the primary model fails.

    1. class LLMBase:
    2. def chat(self, messages: list[dict], **kw) -> str:
    3. raise NotImplementedError
    4. class Agent:
    5. def __init__(self, llm: LLMBase, tools: dict[str, Tool], max_steps: int = 8):
    6. self.llm, self.tools, self.max_steps = llm, tools, max_steps

    When deploying in the cloud, capabilities such as model services, key management, logging, and monitoring and alerting can be integrated as common categories, avoiding writing provider details into business logic.

    3. Control Layer: A Reasoning Loop with a Step Limit

    The control layer drives the ReAct loop and enforces a termination condition to prevent infinite calls:

    1. def run(self, goal: str) -> str:
    2. trace = [f"[GOAL] {goal}"]
    3. for step in range(self.max_steps):
    4. thought = self.llm.chat(trace + ["[STEP] Please give the next thought and action"])
    5. trace.append(f"[THOUGHT] {thought}")
    6. if "final answer" in thought:
    7. return thought
    8. name, args = parse_action(thought) # parse the action instruction
    9. result = TOOLS[name].func(**validate(args, TOOLS[name].schema))
    10. trace.append(f"[OBS] {result}")
    11. return "Maximum steps reached; handing off to a human"

    3. A Robustness Checklist: The Distance from Demo to Production

    A demo script that runs does not mean the system is usable. At a minimum, you need to cover six things: a timeout and retry limit for tool execution; parameter schema validation that rejects invalid input; full-chain trace logs that record the thought, action, and observation triple; dual circuit breakers for step count and token budget; confirmation and auditing for sensitive operations; and a fallback path for model calls. None of these depend on any specific framework, yet they determine whether the system can be operated and trusted.

    4. Conclusion: Keep the Core in Your Hands

    Building an agent in pure Python without an orchestration framework is entirely feasible, and the amount of code is usually far smaller than expected. The real barrier is not syntax, but architectural judgment: how to abstract tools, how to decouple the model, how to make the loop converge, and how to observe failures. Leave common components to mature solutions, and keep the decision core and engineering constraints in your own hands. This is both the most efficient way to learn and the most realistic starting point for building a differentiated product.