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

    This article explores whether you can build an AI Agent from scratch using only pure Python, without any orchestration framework. It explains the core difference between an Agent and a chatbot, walks through a minimal and repeatable Agent loop, and highlights four engineering details that determine reliability: tool contracts, context management, termination and fallback, and observability. It also covers when a custom build is not the right choice and offers practical steps to move from a minimal loop to a production-ready system.

    1. The Question: Why Developers Are Rethinking Framework Dependency

    A common pattern emerges when learning and deploying AI Agents: most introductory material starts with some kind of heavy orchestration framework and quickly assembles a “working” demo through several layers of abstraction. This approach is highly efficient during prototype validation. But once a project moves into a real business scenario, developers often hit three bottlenecks: execution paths are hard to control precisely, debugging chains are obscured by multiple layers of wrapping, and ongoing friction arises between custom requirements and generic abstractions.

    This leads to a serious technical question: Is it actually feasible to build an AI Agent from scratch using only pure Python, without any orchestration framework?

    The answer is yes, but we need to define “feasible” clearly. Feasible does not mean “less effort.” It means the essence of an Agent is not mysterious: it is control logic that follows a fixed loop. Implementing it in pure Python requires little code and delivers stronger controllability and debuggability. The real effort is not in “getting it to run,” but in “keeping it stable.”

    2. Aligning Concepts: The Fundamental Difference Between an Agent and a Chatbot

    Early conversational models were essentially “one question, one answer” information returners: input a piece of text, output a piece of text, with no state and no actions. The key change an Agent introduces is action capability and loop-based decision making:

    • It can call tools: retrieve knowledge, perform calculations, access external APIs, generate images, and more.
    • It can observe results: feed tool return values back into the context.
    • It can decide whether it is done: if not, it continues to the next action.

    So the minimal form of an Agent can be summarized as a loop: perceive context → decide the next step → execute an action → observe the result → decide whether to terminate.

    Complexity depends entirely on the business goal. A customer service Agent may only need a “knowledge retrieval tool + ticket/email sending tool + fallback to a human agent.” An automated operations Agent needs more tools, a stricter state machine, and more complete rollback mechanisms. But regardless of complexity, the underlying skeleton is the same.

    3. The Core Skeleton: An Agent Loop You Can Validate Repeatedly

    The minimal closed loop in pure Python typically contains five elements: a model client, a tool registry, a message context, a loop controller, and termination conditions. The sample code below (structure only, no vendor-specific APIs):

    1. def run_agent(user_input, tools, model_client, max_steps=8):
    2. messages = [
    3. {"role": "system", "content": "You are an assistant that can call tools; use them when necessary."},
    4. {"role": "user", "content": user_input},
    5. ]
    6. for step in range(max_steps):
    7. resp = model_client.chat(messages, tools=tools) # 1. Decide
    8. messages.append(resp.message)
    9. if not resp.tool_calls: # 2. Check termination
    10. return resp.message.content
    11. for call in resp.tool_calls: # 3. Execute action
    12. result = tools[call.name](**call.arguments)
    13. messages.append({ # 4. Observe result
    14. "role": "tool",
    15. "tool_call_id": call.id,
    16. "content": str(result),
    17. })
    18. return "Maximum steps reached; entering fallback flow."

    This code uses no framework, yet fully expresses the operational essence of an Agent. What truly determines quality is the set of engineering details below.

    4. Four Engineering Details That Decide Success or Failure

    1. Tool Contracts: The First Line of Defense for Agent Reliability

    A tool’s naming, parameter structure, and return format must be stable and self-explanatory. In practice: keep parameters as flat and enumerated as possible; standardize return values as structured data with a short summary; and for failures, return clear error semantics instead of throwing an exception that breaks the loop. A vague tool description leads the model to misuse the tool, which is one of the most common failure sources in production.

    2. Context Management: Controlling Cost and Drift

    Context is not better when it is longer. It needs layered design: system constraints stay resident, task goals stay resident, tool results are retained on demand, and historical dialogue is compressed through summarization. For long tasks, use “rolling summary + key facts list” to explicitly persist information that must not be lost, preventing the model from forgetting the initial goal over a long chain.

    3. Termination and Fallback: Avoiding Infinite Loops and Runaway Actions

    You must set up three layers of protection: maximum steps, per-step timeout, and repeated action detection (interrupt when the same tool with the same parameters appears consecutively). You also need a fallback path, such as handing off to a human, degrading to read-only mode, or outputting a list of items awaiting confirmation. For tools that involve write operations, it is recommended to introduce a “second confirmation” mechanism.

    4. Observability: No Logs, No Production

    Every step’s decision input, tool call, return result, elapsed time, and token consumption should be persisted in a structured way, forming a replayable execution trace. When a problem occurs, you can pinpoint whether “the tool returned an anomaly” or “the model made a wrong decision,” which is more valuable than any abstraction layer.

    5. When Not to Build It Yourself

    Building it yourself is not a cure-all. If the requirement is a generic retrieval-augmented flow, standard automation orchestration, or quickly validating an idea, using a mature solution is more cost-effective. The criteria can be summarized in three points:

    • Do you need precise control over the execution path and state? If yes, build your own.
    • Is there already a stable, generic abstraction available? If yes, reuse it.
    • Does the team have the ability to maintain low-level logic? If not, use a generic solution first.

    A clear industry trend is that high-performance, highly personalized intelligent coding tools and complex task-oriented Agents generally adopt custom architectures, precisely because generic abstractions struggle to satisfy efficiency, personalization, and robustness at the same time. Self-developing the core logic and reusing generic capabilities is a more pragmatic division of labor.

    6. Implementation Advice: From a Minimal Loop to Production-Ready

    1. First implement a “single-tool closed loop” to validate the loop and termination logic.
    2. Then expand to multiple tools and parallel calls, filling in error semantics.
    3. Introduce state persistence, write execution traces to a logging service, and add monitoring and alerting.
    4. Connect retrieval-augmented flows for knowledge capabilities, and use a message queue to decouple asynchronous tasks.
    5. Finally, run load tests and fault injection to verify stability under timeouts, rate limiting, and abnormal returns.

    If you need to quickly set up a supporting environment, you can leverage generic cloud capabilities, such as a container platform to host the runtime, object storage to save artifacts, and logging and monitoring services to provide observability. These all belong to generic categories and do not change the essence of self-developed core logic.

    7. Conclusion

    Building an Agent in pure Python is not only feasible but also the best path to understanding Agents. Frameworks solve “speed from 0 to 1”; self-development solves “quality from 1 to 100.” When the business makes real demands on efficiency, personalization, and robustness, keeping the core loop and tool contracts in your own hands is the sustainable engineering choice.