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

    This article examines whether a functional AI Agent can be built using only Python, without an orchestration framework. It breaks down the five core abstractions frameworks typically provide, explains what "works" versus "production-ready" really means, and walks through a minimal implementation covering the model layer, tool registry, decision loop, and state management. It also covers when a graph-based workflow, human-in-the-loop steps, or a framework becomes the better choice, plus practical advice for getting started.

    1. Start With the Right Question: What Does a Framework Actually Solve?

    The debate over whether you can build an AI Agent in pure Python, without an off-the-shelf orchestration framework, usually stays at the level of opinion. To reach a rigorous conclusion, you first need to unpack the capabilities a framework encapsulates, layer by layer, and decide which ones represent real complexity and which are just syntactic sugar.

    Most mainstream Agent development solutions group their abstractions into five categories:

    1. Unified model interface: Hides differences in request formats, authentication, and streaming response structures across LLM providers, so business code is not locked to a single vendor.
    2. Chaining: Turns multiple model calls and data transformations into an ordered processing pipeline.
    3. Autonomous decision-making (the Agent loop): Lets the model decide which tool to call next and whether the task is complete.
    4. Tool integration: Wraps external systems (databases, retrieval, computation, business APIs) into actions the model can understand and invoke.
    5. State and memory management: Preserves conversation history, intermediate results, and task progress, so long-running flows can be interrupted and resumed.

    Another category of solutions focuses on state-graph workflow orchestration, offering nodes and conditional edges, execution checkpoints, and human-in-the-loop steps. These solve complex branching and recovery from breakpoints in long tasks. A third category targets multi-agent collaboration, using role definitions (responsibility, goal, context) and task dispatch to simulate division of labor in a team.

    The key judgment is this: all five abstractions map to real pain points. Provider APIs genuinely are not unified, a single call genuinely cannot complete a multi-step task, and a model genuinely cannot execute actions on its own. But none of this is irreproducible magic. It is an engineering convention you can express clearly in a few hundred lines of Python.

    2. The Verdict: Yes, but Separate “It Runs” From “It Ships”

    The conclusion has two layers:

    • Prototypes and medium-complexity scenarios are fully viable. A task-oriented Agent with a single agent, fewer than a dozen tools, and controllable branching can be supported by pure Python alone, with a more transparent debugging path.
    • Complex long-running flows and high-concurrency production scenarios require additional in-house effort. Checkpoint persistence, breakpoint recovery, human approval, multi-agent collaboration, and observability all come with default implementations in frameworks; if you build them yourself, you have to fill those gaps on your own.

    Put differently, writing it by hand is not “reinventing the wheel.” It is making explicit the decisions a framework silently makes for you. For a team with basic software engineering skills, that cost is manageable.

    3. Four Essential Modules of a Minimum Viable Agent

    1. Unified model access layer

    You do not need a third-party library. An abstract base class plus adapters is enough to isolate the differences:

    1. from abc import ABC, abstractmethod
    2. class LLMClient(ABC):
    3. @abstractmethod
    4. def chat(self, messages, tools=None, temperature=0.2):
    5. ...
    6. class VendorA(LLMClient):
    7. def chat(self, messages, tools=None, temperature=0.2):
    8. # Build the request, authenticate, parse the response,
    9. # and normalize everything into the internal message structure
    10. ...
    11. # Business code depends only on LLMClient; switching providers
    12. # means adding one more adapter

    The important part is defining an internal, unified data structure for messages and tool calls, keeping the provider’s raw response format inside the adapter. That is the core of avoiding vendor lock-in, and it is not something only a framework can do.

    2. Tool registration and invocation

    A tool is essentially a function plus a structured description (name, purpose, parameter schema). You can generate that description from Python type hints and JSON Schema, then maintain a dispatch table mapping names to functions:

    1. TOOLS = {}
    2. def tool(name, description, params_schema):
    3. def deco(fn):
    4. TOOLS[name] = {"fn": fn, "schema": {
    5. "name": name, "description": description,
    6. "parameters": params_schema}}
    7. return fn
    8. return deco
    9. @tool("query_order", "Look up order status by order ID",
    10. {"type": "object", "properties": {"id": {"type": "string"}}})
    11. def query_order(id: str):
    12. return {"status": "shipped"}

    In practice you must add three things: parameter validation, timeout control, and exception handling (return errors to the model as structured text so it has a chance to correct itself).

    3. The decision loop

    An Agent is, at its core, a constrained while loop: the model emits a structured decision, you parse it, execute the tool, feed the result back, and check whether to stop.

    1. for step in range(MAX_STEPS):
    2. resp = client.chat(messages, tools=list(TOOLS.values()))
    3. if not resp.tool_calls:
    4. return resp.content
    5. for call in resp.tool_calls:
    6. result = TOOLS[call.name]["fn"](**call.args)
    7. messages.append({"role": "tool", "content": str(result)})
    8. return "Maximum number of steps reached"

    MAX_STEPS, a per-step timeout, and an overall budget cap are safety valves you must set explicitly. Otherwise you risk runaway tool loops and out-of-control costs.

    4. State and memory

    Short-term memory is just the message list. Long-term memory can be persisted as session records in a database. Task progress can be serialized into a state dictionary. If you need breakpoint recovery, write the state to external storage (a local file, a relational database, or object storage) after each step, then deserialize and resume on restart. That is exactly what a checkpoint mechanism is, and there is nothing mysterious about it.

    4. Workflow Orchestration: Conditional Branches Are Often Clearer in Code

    Linear flows and simple branches are best expressed with ordinary Python control flow. Graph-based orchestration only pays off clearly when you have many nodes and need visualization plus unified recovery semantics. A minimal state-graph executor can be organized like this:

    1. def run(state):
    2. while not state["done"]:
    3. node = NODES[state["next"]]
    4. state = node(state) # Each node returns the updated state and the next step
    5. return state["result"]

    Human intervention is just as plain: implement the node that needs approval as “write a to-do item and suspend,” then resume execution from the suspended state after a human confirms.

    5. When Not to Build It Yourself

    The in-house cost will quickly exceed the benefit once these signals appear: long-term collaboration across multiple agents with dynamic task dispatch; a need for visual orchestration that non-developers can edit; a strong dependence on a mature checkpoint and human-approval ecosystem; or a cross-language team that needs to share the same orchestration semantics. In those cases, reusing a proven industry solution is more economical.

    If you are already building on a cloud platform, general-purpose capabilities such as model services, container platforms, message queues, object storage, and logging, monitoring, and alerting can carry the runtime and observability load, letting your in-house code focus on the business decision logic itself. Baidu AI Cloud offers a fairly complete combination of such general-purpose capabilities and can be evaluated as one option for the hosting layer.

    6. Practical Recommendations

    1. Build the minimum closed loop first (access layer + tools + loop + state) and run one real business use case end to end.
    2. Add the safety valves: step limits, timeouts, budget caps, and input/output auditing.
    3. Set up an evaluation set and use fixed cases to regression-test the effect of changes to prompts and tool descriptions.
    4. Introduce an orchestration framework only once flow complexity or collaboration needs cross the threshold. By then your abstraction boundaries are clear and migration costs are low.

    Building an Agent by hand is not only viable, it is the best way to understand the fundamentals of Agent engineering. The value of a framework is standardizing what you already understand, not thinking on your behalf.